three.cjs 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634
  1. /**
  2. * @license
  3. * Copyright 2010-2025 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. * A `source + destination` blending equation.
  146. *
  147. * @type {number}
  148. * @constant
  149. */
  150. const AddEquation = 100;
  151. /**
  152. * A `source - destination` blending equation.
  153. *
  154. * @type {number}
  155. * @constant
  156. */
  157. const SubtractEquation = 101;
  158. /**
  159. * A `destination - source` blending equation.
  160. *
  161. * @type {number}
  162. * @constant
  163. */
  164. const ReverseSubtractEquation = 102;
  165. /**
  166. * A blend equation that uses the minimum of source and destination.
  167. *
  168. * @type {number}
  169. * @constant
  170. */
  171. const MinEquation = 103;
  172. /**
  173. * A blend equation that uses the maximum of source and destination.
  174. *
  175. * @type {number}
  176. * @constant
  177. */
  178. const MaxEquation = 104;
  179. /**
  180. * Multiplies all colors by `0`.
  181. *
  182. * @type {number}
  183. * @constant
  184. */
  185. const ZeroFactor = 200;
  186. /**
  187. * Multiplies all colors by `1`.
  188. *
  189. * @type {number}
  190. * @constant
  191. */
  192. const OneFactor = 201;
  193. /**
  194. * Multiplies all colors by the source colors.
  195. *
  196. * @type {number}
  197. * @constant
  198. */
  199. const SrcColorFactor = 202;
  200. /**
  201. * Multiplies all colors by `1` minus each source color.
  202. *
  203. * @type {number}
  204. * @constant
  205. */
  206. const OneMinusSrcColorFactor = 203;
  207. /**
  208. * Multiplies all colors by the source alpha value.
  209. *
  210. * @type {number}
  211. * @constant
  212. */
  213. const SrcAlphaFactor = 204;
  214. /**
  215. * Multiplies all colors by 1 minus the source alpha value.
  216. *
  217. * @type {number}
  218. * @constant
  219. */
  220. const OneMinusSrcAlphaFactor = 205;
  221. /**
  222. * Multiplies all colors by the destination alpha value.
  223. *
  224. * @type {number}
  225. * @constant
  226. */
  227. const DstAlphaFactor = 206;
  228. /**
  229. * Multiplies all colors by `1` minus the destination alpha value.
  230. *
  231. * @type {number}
  232. * @constant
  233. */
  234. const OneMinusDstAlphaFactor = 207;
  235. /**
  236. * Multiplies all colors by the destination color.
  237. *
  238. * @type {number}
  239. * @constant
  240. */
  241. const DstColorFactor = 208;
  242. /**
  243. * Multiplies all colors by `1` minus each destination color.
  244. *
  245. * @type {number}
  246. * @constant
  247. */
  248. const OneMinusDstColorFactor = 209;
  249. /**
  250. * Multiplies the RGB colors by the smaller of either the source alpha
  251. * value or the value of `1` minus the destination alpha value. The alpha
  252. * value is multiplied by `1`.
  253. *
  254. * @type {number}
  255. * @constant
  256. */
  257. const SrcAlphaSaturateFactor = 210;
  258. /**
  259. * Multiplies all colors by a constant color.
  260. *
  261. * @type {number}
  262. * @constant
  263. */
  264. const ConstantColorFactor = 211;
  265. /**
  266. * Multiplies all colors by `1` minus a constant color.
  267. *
  268. * @type {number}
  269. * @constant
  270. */
  271. const OneMinusConstantColorFactor = 212;
  272. /**
  273. * Multiplies all colors by a constant alpha value.
  274. *
  275. * @type {number}
  276. * @constant
  277. */
  278. const ConstantAlphaFactor = 213;
  279. /**
  280. * Multiplies all colors by 1 minus a constant alpha value.
  281. *
  282. * @type {number}
  283. * @constant
  284. */
  285. const OneMinusConstantAlphaFactor = 214;
  286. /**
  287. * Never pass.
  288. *
  289. * @type {number}
  290. * @constant
  291. */
  292. const NeverDepth = 0;
  293. /**
  294. * Always pass.
  295. *
  296. * @type {number}
  297. * @constant
  298. */
  299. const AlwaysDepth = 1;
  300. /**
  301. * Pass if the incoming value is less than the depth buffer value.
  302. *
  303. * @type {number}
  304. * @constant
  305. */
  306. const LessDepth = 2;
  307. /**
  308. * Pass if the incoming value is less than or equal to the depth buffer value.
  309. *
  310. * @type {number}
  311. * @constant
  312. */
  313. const LessEqualDepth = 3;
  314. /**
  315. * Pass if the incoming value equals the depth buffer value.
  316. *
  317. * @type {number}
  318. * @constant
  319. */
  320. const EqualDepth = 4;
  321. /**
  322. * Pass if the incoming value is greater than or equal to the depth buffer value.
  323. *
  324. * @type {number}
  325. * @constant
  326. */
  327. const GreaterEqualDepth = 5;
  328. /**
  329. * Pass if the incoming value is greater than the depth buffer value.
  330. *
  331. * @type {number}
  332. * @constant
  333. */
  334. const GreaterDepth = 6;
  335. /**
  336. * Pass if the incoming value is not equal to the depth buffer value.
  337. *
  338. * @type {number}
  339. * @constant
  340. */
  341. const NotEqualDepth = 7;
  342. /**
  343. * Multiplies the environment map color with the surface color.
  344. *
  345. * @type {number}
  346. * @constant
  347. */
  348. const MultiplyOperation = 0;
  349. /**
  350. * Uses reflectivity to blend between the two colors.
  351. *
  352. * @type {number}
  353. * @constant
  354. */
  355. const MixOperation = 1;
  356. /**
  357. * Adds the two colors.
  358. *
  359. * @type {number}
  360. * @constant
  361. */
  362. const AddOperation = 2;
  363. /**
  364. * No tone mapping is applied.
  365. *
  366. * @type {number}
  367. * @constant
  368. */
  369. const NoToneMapping = 0;
  370. /**
  371. * Linear tone mapping.
  372. *
  373. * @type {number}
  374. * @constant
  375. */
  376. const LinearToneMapping = 1;
  377. /**
  378. * Reinhard tone mapping.
  379. *
  380. * @type {number}
  381. * @constant
  382. */
  383. const ReinhardToneMapping = 2;
  384. /**
  385. * Cineon tone mapping.
  386. *
  387. * @type {number}
  388. * @constant
  389. */
  390. const CineonToneMapping = 3;
  391. /**
  392. * ACES Filmic tone mapping.
  393. *
  394. * @type {number}
  395. * @constant
  396. */
  397. const ACESFilmicToneMapping = 4;
  398. /**
  399. * Custom tone mapping.
  400. *
  401. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  402. *
  403. * @type {number}
  404. * @constant
  405. */
  406. const CustomToneMapping = 5;
  407. /**
  408. * AgX tone mapping.
  409. *
  410. * @type {number}
  411. * @constant
  412. */
  413. const AgXToneMapping = 6;
  414. /**
  415. * Neutral tone mapping.
  416. *
  417. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  418. *
  419. * @type {number}
  420. * @constant
  421. */
  422. const NeutralToneMapping = 7;
  423. /**
  424. * The skinned mesh shares the same world space as the skeleton.
  425. *
  426. * @type {string}
  427. * @constant
  428. */
  429. const AttachedBindMode = 'attached';
  430. /**
  431. * The skinned mesh does not share the same world space as the skeleton.
  432. * This is useful when a skeleton is shared across multiple skinned meshes.
  433. *
  434. * @type {string}
  435. * @constant
  436. */
  437. const DetachedBindMode = 'detached';
  438. /**
  439. * Maps textures using the geometry's UV coordinates.
  440. *
  441. * @type {number}
  442. * @constant
  443. */
  444. const UVMapping = 300;
  445. /**
  446. * Reflection mapping for cube textures.
  447. *
  448. * @type {number}
  449. * @constant
  450. */
  451. const CubeReflectionMapping = 301;
  452. /**
  453. * Refraction mapping for cube textures.
  454. *
  455. * @type {number}
  456. * @constant
  457. */
  458. const CubeRefractionMapping = 302;
  459. /**
  460. * Reflection mapping for equirectangular textures.
  461. *
  462. * @type {number}
  463. * @constant
  464. */
  465. const EquirectangularReflectionMapping = 303;
  466. /**
  467. * Refraction mapping for equirectangular textures.
  468. *
  469. * @type {number}
  470. * @constant
  471. */
  472. const EquirectangularRefractionMapping = 304;
  473. /**
  474. * Reflection mapping for PMREM textures.
  475. *
  476. * @type {number}
  477. * @constant
  478. */
  479. const CubeUVReflectionMapping = 306;
  480. /**
  481. * The texture will simply repeat to infinity.
  482. *
  483. * @type {number}
  484. * @constant
  485. */
  486. const RepeatWrapping = 1000;
  487. /**
  488. * The last pixel of the texture stretches to the edge of the mesh.
  489. *
  490. * @type {number}
  491. * @constant
  492. */
  493. const ClampToEdgeWrapping = 1001;
  494. /**
  495. * The texture will repeats to infinity, mirroring on each repeat.
  496. *
  497. * @type {number}
  498. * @constant
  499. */
  500. const MirroredRepeatWrapping = 1002;
  501. /**
  502. * Returns the value of the texture element that is nearest (in Manhattan distance)
  503. * to the specified texture coordinates.
  504. *
  505. * @type {number}
  506. * @constant
  507. */
  508. const NearestFilter = 1003;
  509. /**
  510. * Chooses the mipmap that most closely matches the size of the pixel being textured
  511. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  512. * to produce a texture value.
  513. *
  514. * @type {number}
  515. * @constant
  516. */
  517. const NearestMipmapNearestFilter = 1004;
  518. const NearestMipMapNearestFilter = 1004; // legacy
  519. /**
  520. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  521. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  522. * The final texture value is a weighted average of those two values.
  523. *
  524. * @type {number}
  525. * @constant
  526. */
  527. const NearestMipmapLinearFilter = 1005;
  528. const NearestMipMapLinearFilter = 1005; // legacy
  529. /**
  530. * Returns the weighted average of the four texture elements that are closest to the specified
  531. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  532. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  533. *
  534. * @type {number}
  535. * @constant
  536. */
  537. const LinearFilter = 1006;
  538. /**
  539. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  540. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  541. * center of the pixel) to produce a texture value.
  542. *
  543. * @type {number}
  544. * @constant
  545. */
  546. const LinearMipmapNearestFilter = 1007;
  547. const LinearMipMapNearestFilter = 1007; // legacy
  548. /**
  549. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  550. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  551. * is a weighted average of those two values.
  552. *
  553. * @type {number}
  554. * @constant
  555. */
  556. const LinearMipmapLinearFilter = 1008;
  557. const LinearMipMapLinearFilter = 1008; // legacy
  558. /**
  559. * An unsigned byte data type for textures.
  560. *
  561. * @type {number}
  562. * @constant
  563. */
  564. const UnsignedByteType = 1009;
  565. /**
  566. * A byte data type for textures.
  567. *
  568. * @type {number}
  569. * @constant
  570. */
  571. const ByteType = 1010;
  572. /**
  573. * A short data type for textures.
  574. *
  575. * @type {number}
  576. * @constant
  577. */
  578. const ShortType = 1011;
  579. /**
  580. * An unsigned short data type for textures.
  581. *
  582. * @type {number}
  583. * @constant
  584. */
  585. const UnsignedShortType = 1012;
  586. /**
  587. * An int data type for textures.
  588. *
  589. * @type {number}
  590. * @constant
  591. */
  592. const IntType = 1013;
  593. /**
  594. * An unsigned int data type for textures.
  595. *
  596. * @type {number}
  597. * @constant
  598. */
  599. const UnsignedIntType = 1014;
  600. /**
  601. * A float data type for textures.
  602. *
  603. * @type {number}
  604. * @constant
  605. */
  606. const FloatType = 1015;
  607. /**
  608. * A half float data type for textures.
  609. *
  610. * @type {number}
  611. * @constant
  612. */
  613. const HalfFloatType = 1016;
  614. /**
  615. * An unsigned short 4_4_4_4 (packed) data type for textures.
  616. *
  617. * @type {number}
  618. * @constant
  619. */
  620. const UnsignedShort4444Type = 1017;
  621. /**
  622. * An unsigned short 5_5_5_1 (packed) data type for textures.
  623. *
  624. * @type {number}
  625. * @constant
  626. */
  627. const UnsignedShort5551Type = 1018;
  628. /**
  629. * An unsigned int 24_8 data type for textures.
  630. *
  631. * @type {number}
  632. * @constant
  633. */
  634. const UnsignedInt248Type = 1020;
  635. /**
  636. * An unsigned int 5_9_9_9 (packed) data type for textures.
  637. *
  638. * @type {number}
  639. * @constant
  640. */
  641. const UnsignedInt5999Type = 35902;
  642. /**
  643. * An unsigned int 10_11_11 (packed) data type for textures.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const UnsignedInt101111Type = 35899;
  649. /**
  650. * Discards the red, green and blue components and reads just the alpha component.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const AlphaFormat = 1021;
  656. /**
  657. * Discards the alpha component and reads the red, green and blue component.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const RGBFormat = 1022;
  663. /**
  664. * Reads the red, green, blue and alpha components.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const RGBAFormat = 1023;
  670. /**
  671. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const DepthFormat = 1026;
  677. /**
  678. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  679. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  680. *
  681. * @type {number}
  682. * @constant
  683. */
  684. const DepthStencilFormat = 1027;
  685. /**
  686. * Discards the green, blue and alpha components and reads just the red component.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const RedFormat = 1028;
  692. /**
  693. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RedIntegerFormat = 1029;
  699. /**
  700. * Discards the alpha, and blue components and reads the red, and green components.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RGFormat = 1030;
  706. /**
  707. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGIntegerFormat = 1031;
  713. /**
  714. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGBIntegerFormat = 1032;
  720. /**
  721. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGBAIntegerFormat = 1033;
  727. /**
  728. * A DXT1-compressed image in an RGB image format.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGB_S3TC_DXT1_Format = 33776;
  734. /**
  735. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGBA_S3TC_DXT1_Format = 33777;
  741. /**
  742. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT3_Format = 33778;
  748. /**
  749. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  750. * compression in how the alpha compression is done.
  751. *
  752. * @type {number}
  753. * @constant
  754. */
  755. const RGBA_S3TC_DXT5_Format = 33779;
  756. /**
  757. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGB_PVRTC_4BPPV1_Format = 35840;
  763. /**
  764. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGB_PVRTC_2BPPV1_Format = 35841;
  770. /**
  771. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGBA_PVRTC_4BPPV1_Format = 35842;
  777. /**
  778. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGBA_PVRTC_2BPPV1_Format = 35843;
  784. /**
  785. * ETC1 RGB format.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGB_ETC1_Format = 36196;
  791. /**
  792. * ETC2 RGB format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGB_ETC2_Format = 37492;
  798. /**
  799. * ETC2 RGBA format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGBA_ETC2_EAC_Format = 37496;
  805. /**
  806. * EAC R11 UNORM format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const R11_EAC_Format = 37488; // 0x9270
  812. /**
  813. * EAC R11 SNORM format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  819. /**
  820. * EAC RG11 UNORM format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const RG11_EAC_Format = 37490; // 0x9272
  826. /**
  827. * EAC RG11 SNORM format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  833. /**
  834. * ASTC RGBA 4x4 format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const RGBA_ASTC_4x4_Format = 37808;
  840. /**
  841. * ASTC RGBA 5x4 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_5x4_Format = 37809;
  847. /**
  848. * ASTC RGBA 5x5 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_5x5_Format = 37810;
  854. /**
  855. * ASTC RGBA 6x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_6x5_Format = 37811;
  861. /**
  862. * ASTC RGBA 6x6 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_6x6_Format = 37812;
  868. /**
  869. * ASTC RGBA 8x5 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_8x5_Format = 37813;
  875. /**
  876. * ASTC RGBA 8x6 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_8x6_Format = 37814;
  882. /**
  883. * ASTC RGBA 8x8 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_8x8_Format = 37815;
  889. /**
  890. * ASTC RGBA 10x5 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_10x5_Format = 37816;
  896. /**
  897. * ASTC RGBA 10x6 format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_ASTC_10x6_Format = 37817;
  903. /**
  904. * ASTC RGBA 10x8 format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGBA_ASTC_10x8_Format = 37818;
  910. /**
  911. * ASTC RGBA 10x10 format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGBA_ASTC_10x10_Format = 37819;
  917. /**
  918. * ASTC RGBA 12x10 format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RGBA_ASTC_12x10_Format = 37820;
  924. /**
  925. * ASTC RGBA 12x12 format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const RGBA_ASTC_12x12_Format = 37821;
  931. /**
  932. * BPTC RGBA format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RGBA_BPTC_Format = 36492;
  938. /**
  939. * BPTC Signed RGB format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const RGB_BPTC_SIGNED_Format = 36494;
  945. /**
  946. * BPTC Unsigned RGB format.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const RGB_BPTC_UNSIGNED_Format = 36495;
  952. /**
  953. * RGTC1 Red format.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const RED_RGTC1_Format = 36283;
  959. /**
  960. * RGTC1 Signed Red format.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const SIGNED_RED_RGTC1_Format = 36284;
  966. /**
  967. * RGTC2 Red Green format.
  968. *
  969. * @type {number}
  970. * @constant
  971. */
  972. const RED_GREEN_RGTC2_Format = 36285;
  973. /**
  974. * RGTC2 Signed Red Green format.
  975. *
  976. * @type {number}
  977. * @constant
  978. */
  979. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  980. /**
  981. * Animations are played once.
  982. *
  983. * @type {number}
  984. * @constant
  985. */
  986. const LoopOnce = 2200;
  987. /**
  988. * Animations are played with a chosen number of repetitions, each time jumping from
  989. * the end of the clip directly to its beginning.
  990. *
  991. * @type {number}
  992. * @constant
  993. */
  994. const LoopRepeat = 2201;
  995. /**
  996. * Animations are played with a chosen number of repetitions, alternately playing forward
  997. * and backward.
  998. *
  999. * @type {number}
  1000. * @constant
  1001. */
  1002. const LoopPingPong = 2202;
  1003. /**
  1004. * Discrete interpolation mode for keyframe tracks.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const InterpolateDiscrete = 2300;
  1010. /**
  1011. * Linear interpolation mode for keyframe tracks.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const InterpolateLinear = 2301;
  1017. /**
  1018. * Smooth interpolation mode for keyframe tracks.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const InterpolateSmooth = 2302;
  1024. /**
  1025. * Zero curvature ending for animations.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const ZeroCurvatureEnding = 2400;
  1031. /**
  1032. * Zero slope ending for animations.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const ZeroSlopeEnding = 2401;
  1038. /**
  1039. * Wrap around ending for animations.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const WrapAroundEnding = 2402;
  1045. /**
  1046. * Default animation blend mode.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const NormalAnimationBlendMode = 2500;
  1052. /**
  1053. * Additive animation blend mode. Can be used to layer motions on top of
  1054. * each other to build complex performances from smaller re-usable assets.
  1055. *
  1056. * @type {number}
  1057. * @constant
  1058. */
  1059. const AdditiveAnimationBlendMode = 2501;
  1060. /**
  1061. * For every three vertices draw a single triangle.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const TrianglesDrawMode = 0;
  1067. /**
  1068. * For each vertex draw a triangle from the last three vertices.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const TriangleStripDrawMode = 1;
  1074. /**
  1075. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const TriangleFanDrawMode = 2;
  1081. /**
  1082. * The depth value is inverted (1.0 - z) for visualization purposes.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const BasicDepthPacking = 3200;
  1088. /**
  1089. * The depth value is packed into 32 bit RGBA.
  1090. *
  1091. * @type {number}
  1092. * @constant
  1093. */
  1094. const RGBADepthPacking = 3201;
  1095. /**
  1096. * The depth value is packed into 24 bit RGB.
  1097. *
  1098. * @type {number}
  1099. * @constant
  1100. */
  1101. const RGBDepthPacking = 3202;
  1102. /**
  1103. * The depth value is packed into 16 bit RG.
  1104. *
  1105. * @type {number}
  1106. * @constant
  1107. */
  1108. const RGDepthPacking = 3203;
  1109. /**
  1110. * Normal information is relative to the underlying surface.
  1111. *
  1112. * @type {number}
  1113. * @constant
  1114. */
  1115. const TangentSpaceNormalMap = 0;
  1116. /**
  1117. * Normal information is relative to the object orientation.
  1118. *
  1119. * @type {number}
  1120. * @constant
  1121. */
  1122. const ObjectSpaceNormalMap = 1;
  1123. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1124. /**
  1125. * No color space.
  1126. *
  1127. * @type {string}
  1128. * @constant
  1129. */
  1130. const NoColorSpace = '';
  1131. /**
  1132. * sRGB color space.
  1133. *
  1134. * @type {string}
  1135. * @constant
  1136. */
  1137. const SRGBColorSpace = 'srgb';
  1138. /**
  1139. * sRGB-linear color space.
  1140. *
  1141. * @type {string}
  1142. * @constant
  1143. */
  1144. const LinearSRGBColorSpace = 'srgb-linear';
  1145. /**
  1146. * Linear transfer function.
  1147. *
  1148. * @type {string}
  1149. * @constant
  1150. */
  1151. const LinearTransfer = 'linear';
  1152. /**
  1153. * sRGB transfer function.
  1154. *
  1155. * @type {string}
  1156. * @constant
  1157. */
  1158. const SRGBTransfer = 'srgb';
  1159. /**
  1160. * No normal map packing.
  1161. *
  1162. * @type {string}
  1163. * @constant
  1164. */
  1165. const NoNormalPacking = '';
  1166. /**
  1167. * Normal RG packing.
  1168. *
  1169. * @type {string}
  1170. * @constant
  1171. */
  1172. const NormalRGPacking = 'rg';
  1173. /**
  1174. * Normal GA packing.
  1175. *
  1176. * @type {string}
  1177. * @constant
  1178. */
  1179. const NormalGAPacking = 'ga';
  1180. /**
  1181. * Sets the stencil buffer value to `0`.
  1182. *
  1183. * @type {number}
  1184. * @constant
  1185. */
  1186. const ZeroStencilOp = 0;
  1187. /**
  1188. * Keeps the current value.
  1189. *
  1190. * @type {number}
  1191. * @constant
  1192. */
  1193. const KeepStencilOp = 7680;
  1194. /**
  1195. * Sets the stencil buffer value to the specified reference value.
  1196. *
  1197. * @type {number}
  1198. * @constant
  1199. */
  1200. const ReplaceStencilOp = 7681;
  1201. /**
  1202. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1203. *
  1204. * @type {number}
  1205. * @constant
  1206. */
  1207. const IncrementStencilOp = 7682;
  1208. /**
  1209. * Decrements the current stencil buffer value. Clamps to `0`.
  1210. *
  1211. * @type {number}
  1212. * @constant
  1213. */
  1214. const DecrementStencilOp = 7683;
  1215. /**
  1216. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1217. * the maximum representable unsigned value.
  1218. *
  1219. * @type {number}
  1220. * @constant
  1221. */
  1222. const IncrementWrapStencilOp = 34055;
  1223. /**
  1224. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1225. * unsigned value when decrementing a stencil buffer value of `0`.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const DecrementWrapStencilOp = 34056;
  1231. /**
  1232. * Inverts the current stencil buffer value bitwise.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const InvertStencilOp = 5386;
  1238. /**
  1239. * Will never return true.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const NeverStencilFunc = 512;
  1245. /**
  1246. * Will return true if the stencil reference value is less than the current stencil value.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const LessStencilFunc = 513;
  1252. /**
  1253. * Will return true if the stencil reference value is equal to the current stencil value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const EqualStencilFunc = 514;
  1259. /**
  1260. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const LessEqualStencilFunc = 515;
  1266. /**
  1267. * Will return true if the stencil reference value is greater than the current stencil value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const GreaterStencilFunc = 516;
  1273. /**
  1274. * Will return true if the stencil reference value is not equal to the current stencil value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const NotEqualStencilFunc = 517;
  1280. /**
  1281. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const GreaterEqualStencilFunc = 518;
  1287. /**
  1288. * Will always return true.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const AlwaysStencilFunc = 519;
  1294. /**
  1295. * Never pass.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const NeverCompare = 512;
  1301. /**
  1302. * Pass if the incoming value is less than the texture value.
  1303. *
  1304. * @type {number}
  1305. * @constant
  1306. */
  1307. const LessCompare = 513;
  1308. /**
  1309. * Pass if the incoming value equals the texture value.
  1310. *
  1311. * @type {number}
  1312. * @constant
  1313. */
  1314. const EqualCompare = 514;
  1315. /**
  1316. * Pass if the incoming value is less than or equal to the texture value.
  1317. *
  1318. * @type {number}
  1319. * @constant
  1320. */
  1321. const LessEqualCompare = 515;
  1322. /**
  1323. * Pass if the incoming value is greater than the texture value.
  1324. *
  1325. * @type {number}
  1326. * @constant
  1327. */
  1328. const GreaterCompare = 516;
  1329. /**
  1330. * Pass if the incoming value is not equal to the texture value.
  1331. *
  1332. * @type {number}
  1333. * @constant
  1334. */
  1335. const NotEqualCompare = 517;
  1336. /**
  1337. * Pass if the incoming value is greater than or equal to the texture value.
  1338. *
  1339. * @type {number}
  1340. * @constant
  1341. */
  1342. const GreaterEqualCompare = 518;
  1343. /**
  1344. * Always pass.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const AlwaysCompare = 519;
  1350. /**
  1351. * The contents are intended to be specified once by the application, and used many
  1352. * times as the source for drawing and image specification commands.
  1353. *
  1354. * @type {number}
  1355. * @constant
  1356. */
  1357. const StaticDrawUsage = 35044;
  1358. /**
  1359. * The contents are intended to be respecified repeatedly by the application, and
  1360. * used many times as the source for drawing and image specification commands.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const DynamicDrawUsage = 35048;
  1366. /**
  1367. * The contents are intended to be specified once by the application, and used at most
  1368. * a few times as the source for drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const StreamDrawUsage = 35040;
  1374. /**
  1375. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1376. * many times by the application.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const StaticReadUsage = 35045;
  1382. /**
  1383. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1384. * many times by the application.
  1385. *
  1386. * @type {number}
  1387. * @constant
  1388. */
  1389. const DynamicReadUsage = 35049;
  1390. /**
  1391. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1392. * a few times by the application
  1393. *
  1394. * @type {number}
  1395. * @constant
  1396. */
  1397. const StreamReadUsage = 35041;
  1398. /**
  1399. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1400. * the source for WebGL drawing and image specification commands.
  1401. *
  1402. * @type {number}
  1403. * @constant
  1404. */
  1405. const StaticCopyUsage = 35046;
  1406. /**
  1407. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1408. * as the source for WebGL drawing and image specification commands.
  1409. *
  1410. * @type {number}
  1411. * @constant
  1412. */
  1413. const DynamicCopyUsage = 35050;
  1414. /**
  1415. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1416. * as the source for WebGL drawing and image specification commands.
  1417. *
  1418. * @type {number}
  1419. * @constant
  1420. */
  1421. const StreamCopyUsage = 35042;
  1422. /**
  1423. * GLSL 1 shader code.
  1424. *
  1425. * @type {string}
  1426. * @constant
  1427. */
  1428. const GLSL1 = '100';
  1429. /**
  1430. * GLSL 3 shader code.
  1431. *
  1432. * @type {string}
  1433. * @constant
  1434. */
  1435. const GLSL3 = '300 es';
  1436. /**
  1437. * WebGL coordinate system.
  1438. *
  1439. * @type {number}
  1440. * @constant
  1441. */
  1442. const WebGLCoordinateSystem = 2000;
  1443. /**
  1444. * WebGPU coordinate system.
  1445. *
  1446. * @type {number}
  1447. * @constant
  1448. */
  1449. const WebGPUCoordinateSystem = 2001;
  1450. /**
  1451. * Represents the different timestamp query types.
  1452. *
  1453. * @type {ConstantsTimestampQuery}
  1454. * @constant
  1455. */
  1456. const TimestampQuery = {
  1457. COMPUTE: 'compute',
  1458. RENDER: 'render'
  1459. };
  1460. /**
  1461. * Represents mouse buttons and interaction types in context of controls.
  1462. *
  1463. * @type {ConstantsInterpolationSamplingType}
  1464. * @constant
  1465. */
  1466. const InterpolationSamplingType = {
  1467. PERSPECTIVE: 'perspective',
  1468. LINEAR: 'linear',
  1469. FLAT: 'flat'
  1470. };
  1471. /**
  1472. * Represents the different interpolation sampling modes.
  1473. *
  1474. * @type {ConstantsInterpolationSamplingMode}
  1475. * @constant
  1476. */
  1477. const InterpolationSamplingMode = {
  1478. NORMAL: 'normal',
  1479. CENTROID: 'centroid',
  1480. SAMPLE: 'sample',
  1481. FIRST: 'first',
  1482. EITHER: 'either'
  1483. };
  1484. /**
  1485. * Compatibility flags for features that may not be supported across all platforms.
  1486. *
  1487. * @type {Object}
  1488. * @constant
  1489. */
  1490. const Compatibility = {
  1491. TEXTURE_COMPARE: 'depthTextureCompare'
  1492. };
  1493. /**
  1494. * This type represents mouse buttons and interaction types in context of controls.
  1495. *
  1496. * @typedef {Object} ConstantsMouse
  1497. * @property {number} MIDDLE - The left mouse button.
  1498. * @property {number} LEFT - The middle mouse button.
  1499. * @property {number} RIGHT - The right mouse button.
  1500. * @property {number} ROTATE - A rotate interaction.
  1501. * @property {number} DOLLY - A dolly interaction.
  1502. * @property {number} PAN - A pan interaction.
  1503. **/
  1504. /**
  1505. * This type represents touch interaction types in context of controls.
  1506. *
  1507. * @typedef {Object} ConstantsTouch
  1508. * @property {number} ROTATE - A rotate interaction.
  1509. * @property {number} PAN - A pan interaction.
  1510. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1511. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1512. **/
  1513. /**
  1514. * This type represents the different timestamp query types.
  1515. *
  1516. * @typedef {Object} ConstantsTimestampQuery
  1517. * @property {string} COMPUTE - A `compute` timestamp query.
  1518. * @property {string} RENDER - A `render` timestamp query.
  1519. **/
  1520. /**
  1521. * Represents the different interpolation sampling types.
  1522. *
  1523. * @typedef {Object} ConstantsInterpolationSamplingType
  1524. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1525. * @property {string} LINEAR - Linear interpolation.
  1526. * @property {string} FLAT - Flat interpolation.
  1527. */
  1528. /**
  1529. * Represents the different interpolation sampling modes.
  1530. *
  1531. * @typedef {Object} ConstantsInterpolationSamplingMode
  1532. * @property {string} NORMAL - Normal sampling mode.
  1533. * @property {string} CENTROID - Centroid sampling mode.
  1534. * @property {string} SAMPLE - Sample-specific sampling mode.
  1535. * @property {string} FIRST - Flat interpolation using the first vertex.
  1536. * @property {string} EITHER - Flat interpolation using either vertex.
  1537. */
  1538. function arrayNeedsUint32( array ) {
  1539. // assumes larger values usually on last
  1540. for ( let i = array.length - 1; i >= 0; -- i ) {
  1541. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1542. }
  1543. return false;
  1544. }
  1545. const TYPED_ARRAYS = {
  1546. Int8Array: Int8Array,
  1547. Uint8Array: Uint8Array,
  1548. Uint8ClampedArray: Uint8ClampedArray,
  1549. Int16Array: Int16Array,
  1550. Uint16Array: Uint16Array,
  1551. Int32Array: Int32Array,
  1552. Uint32Array: Uint32Array,
  1553. Float32Array: Float32Array,
  1554. Float64Array: Float64Array
  1555. };
  1556. function getTypedArray( type, buffer ) {
  1557. return new TYPED_ARRAYS[ type ]( buffer );
  1558. }
  1559. /**
  1560. * Returns `true` if the given object is a typed array.
  1561. *
  1562. * @param {any} array - The object to check.
  1563. * @return {boolean} Whether the given object is a typed array.
  1564. */
  1565. function isTypedArray( array ) {
  1566. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1567. }
  1568. function createElementNS( name ) {
  1569. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1570. }
  1571. function createCanvasElement() {
  1572. const canvas = createElementNS( 'canvas' );
  1573. canvas.style.display = 'block';
  1574. return canvas;
  1575. }
  1576. const _cache = {};
  1577. let _setConsoleFunction = null;
  1578. function setConsoleFunction( fn ) {
  1579. _setConsoleFunction = fn;
  1580. }
  1581. function getConsoleFunction() {
  1582. return _setConsoleFunction;
  1583. }
  1584. function log( ...params ) {
  1585. const message = 'THREE.' + params.shift();
  1586. if ( _setConsoleFunction ) {
  1587. _setConsoleFunction( 'log', message, ...params );
  1588. } else {
  1589. console.log( message, ...params );
  1590. }
  1591. }
  1592. function warn( ...params ) {
  1593. const message = 'THREE.' + params.shift();
  1594. if ( _setConsoleFunction ) {
  1595. _setConsoleFunction( 'warn', message, ...params );
  1596. } else {
  1597. console.warn( message, ...params );
  1598. }
  1599. }
  1600. function error( ...params ) {
  1601. const message = 'THREE.' + params.shift();
  1602. if ( _setConsoleFunction ) {
  1603. _setConsoleFunction( 'error', message, ...params );
  1604. } else {
  1605. console.error( message, ...params );
  1606. }
  1607. }
  1608. function warnOnce( ...params ) {
  1609. const message = params.join( ' ' );
  1610. if ( message in _cache ) return;
  1611. _cache[ message ] = true;
  1612. warn( ...params );
  1613. }
  1614. function probeAsync( gl, sync, interval ) {
  1615. return new Promise( function ( resolve, reject ) {
  1616. function probe() {
  1617. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1618. case gl.WAIT_FAILED:
  1619. reject();
  1620. break;
  1621. case gl.TIMEOUT_EXPIRED:
  1622. setTimeout( probe, interval );
  1623. break;
  1624. default:
  1625. resolve();
  1626. }
  1627. }
  1628. setTimeout( probe, interval );
  1629. } );
  1630. }
  1631. /**
  1632. * This modules allows to dispatch event objects on custom JavaScript objects.
  1633. *
  1634. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1635. *
  1636. * Code Example:
  1637. * ```js
  1638. * class Car extends EventDispatcher {
  1639. * start() {
  1640. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1641. * }
  1642. *};
  1643. *
  1644. * // Using events with the custom object
  1645. * const car = new Car();
  1646. * car.addEventListener( 'start', function ( event ) {
  1647. * alert( event.message );
  1648. * } );
  1649. *
  1650. * car.start();
  1651. * ```
  1652. */
  1653. class EventDispatcher {
  1654. /**
  1655. * Adds the given event listener to the given event type.
  1656. *
  1657. * @param {string} type - The type of event to listen to.
  1658. * @param {Function} listener - The function that gets called when the event is fired.
  1659. */
  1660. addEventListener( type, listener ) {
  1661. if ( this._listeners === undefined ) this._listeners = {};
  1662. const listeners = this._listeners;
  1663. if ( listeners[ type ] === undefined ) {
  1664. listeners[ type ] = [];
  1665. }
  1666. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1667. listeners[ type ].push( listener );
  1668. }
  1669. }
  1670. /**
  1671. * Returns `true` if the given event listener has been added to the given event type.
  1672. *
  1673. * @param {string} type - The type of event.
  1674. * @param {Function} listener - The listener to check.
  1675. * @return {boolean} Whether the given event listener has been added to the given event type.
  1676. */
  1677. hasEventListener( type, listener ) {
  1678. const listeners = this._listeners;
  1679. if ( listeners === undefined ) return false;
  1680. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1681. }
  1682. /**
  1683. * Removes the given event listener from the given event type.
  1684. *
  1685. * @param {string} type - The type of event.
  1686. * @param {Function} listener - The listener to remove.
  1687. */
  1688. removeEventListener( type, listener ) {
  1689. const listeners = this._listeners;
  1690. if ( listeners === undefined ) return;
  1691. const listenerArray = listeners[ type ];
  1692. if ( listenerArray !== undefined ) {
  1693. const index = listenerArray.indexOf( listener );
  1694. if ( index !== -1 ) {
  1695. listenerArray.splice( index, 1 );
  1696. }
  1697. }
  1698. }
  1699. /**
  1700. * Dispatches an event object.
  1701. *
  1702. * @param {Object} event - The event that gets fired.
  1703. */
  1704. dispatchEvent( event ) {
  1705. const listeners = this._listeners;
  1706. if ( listeners === undefined ) return;
  1707. const listenerArray = listeners[ event.type ];
  1708. if ( listenerArray !== undefined ) {
  1709. event.target = this;
  1710. // Make a copy, in case listeners are removed while iterating.
  1711. const array = listenerArray.slice( 0 );
  1712. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1713. array[ i ].call( this, event );
  1714. }
  1715. event.target = null;
  1716. }
  1717. }
  1718. }
  1719. 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' ];
  1720. let _seed = 1234567;
  1721. const DEG2RAD = Math.PI / 180;
  1722. const RAD2DEG = 180 / Math.PI;
  1723. /**
  1724. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1725. * (universally unique identifier).
  1726. *
  1727. * @return {string} The UUID.
  1728. */
  1729. function generateUUID() {
  1730. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1731. const d0 = Math.random() * 0xffffffff | 0;
  1732. const d1 = Math.random() * 0xffffffff | 0;
  1733. const d2 = Math.random() * 0xffffffff | 0;
  1734. const d3 = Math.random() * 0xffffffff | 0;
  1735. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1736. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1737. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1738. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1739. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1740. return uuid.toLowerCase();
  1741. }
  1742. /**
  1743. * Clamps the given value between min and max.
  1744. *
  1745. * @param {number} value - The value to clamp.
  1746. * @param {number} min - The min value.
  1747. * @param {number} max - The max value.
  1748. * @return {number} The clamped value.
  1749. */
  1750. function clamp( value, min, max ) {
  1751. return Math.max( min, Math.min( max, value ) );
  1752. }
  1753. /**
  1754. * Computes the Euclidean modulo of the given parameters that
  1755. * is `( ( n % m ) + m ) % m`.
  1756. *
  1757. * @param {number} n - The first parameter.
  1758. * @param {number} m - The second parameter.
  1759. * @return {number} The Euclidean modulo.
  1760. */
  1761. function euclideanModulo( n, m ) {
  1762. // https://en.wikipedia.org/wiki/Modulo_operation
  1763. return ( ( n % m ) + m ) % m;
  1764. }
  1765. /**
  1766. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1767. * for the given value.
  1768. *
  1769. * @param {number} x - The value to be mapped.
  1770. * @param {number} a1 - Minimum value for range A.
  1771. * @param {number} a2 - Maximum value for range A.
  1772. * @param {number} b1 - Minimum value for range B.
  1773. * @param {number} b2 - Maximum value for range B.
  1774. * @return {number} The mapped value.
  1775. */
  1776. function mapLinear( x, a1, a2, b1, b2 ) {
  1777. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1778. }
  1779. /**
  1780. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1781. * between the start and end point.
  1782. *
  1783. * @param {number} x - The start point
  1784. * @param {number} y - The end point.
  1785. * @param {number} value - A value between start and end.
  1786. * @return {number} The interpolation factor.
  1787. */
  1788. function inverseLerp( x, y, value ) {
  1789. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1790. if ( x !== y ) {
  1791. return ( value - x ) / ( y - x );
  1792. } else {
  1793. return 0;
  1794. }
  1795. }
  1796. /**
  1797. * Returns a value linearly interpolated from two known points based on the given interval -
  1798. * `t = 0` will return `x` and `t = 1` will return `y`.
  1799. *
  1800. * @param {number} x - The start point
  1801. * @param {number} y - The end point.
  1802. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1803. * @return {number} The interpolated value.
  1804. */
  1805. function lerp( x, y, t ) {
  1806. return ( 1 - t ) * x + t * y;
  1807. }
  1808. /**
  1809. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1810. * time to maintain frame rate independent movement. For details, see
  1811. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1812. *
  1813. * @param {number} x - The current point.
  1814. * @param {number} y - The target point.
  1815. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1816. * and a lower value will make the movement more gradual.
  1817. * @param {number} dt - Delta time in seconds.
  1818. * @return {number} The interpolated value.
  1819. */
  1820. function damp( x, y, lambda, dt ) {
  1821. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1822. }
  1823. /**
  1824. * Returns a value that alternates between `0` and the given `length` parameter.
  1825. *
  1826. * @param {number} x - The value to pingpong.
  1827. * @param {number} [length=1] - The positive value the function will pingpong to.
  1828. * @return {number} The alternated value.
  1829. */
  1830. function pingpong( x, length = 1 ) {
  1831. // https://www.desmos.com/calculator/vcsjnyz7x4
  1832. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1833. }
  1834. /**
  1835. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1836. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1837. * the `min` and `max`.
  1838. *
  1839. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1840. *
  1841. * @param {number} x - The value to evaluate based on its position between min and max.
  1842. * @param {number} min - The min value. Any x value below min will be `0`.
  1843. * @param {number} max - The max value. Any x value above max will be `1`.
  1844. * @return {number} The alternated value.
  1845. */
  1846. function smoothstep( x, min, max ) {
  1847. if ( x <= min ) return 0;
  1848. if ( x >= max ) return 1;
  1849. x = ( x - min ) / ( max - min );
  1850. return x * x * ( 3 - 2 * x );
  1851. }
  1852. /**
  1853. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1854. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1855. *
  1856. * @param {number} x - The value to evaluate based on its position between min and max.
  1857. * @param {number} min - The min value. Any x value below min will be `0`.
  1858. * @param {number} max - The max value. Any x value above max will be `1`.
  1859. * @return {number} The alternated value.
  1860. */
  1861. function smootherstep( x, min, max ) {
  1862. if ( x <= min ) return 0;
  1863. if ( x >= max ) return 1;
  1864. x = ( x - min ) / ( max - min );
  1865. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1866. }
  1867. /**
  1868. * Returns a random integer from `<low, high>` interval.
  1869. *
  1870. * @param {number} low - The lower value boundary.
  1871. * @param {number} high - The upper value boundary
  1872. * @return {number} A random integer.
  1873. */
  1874. function randInt( low, high ) {
  1875. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1876. }
  1877. /**
  1878. * Returns a random float from `<low, high>` interval.
  1879. *
  1880. * @param {number} low - The lower value boundary.
  1881. * @param {number} high - The upper value boundary
  1882. * @return {number} A random float.
  1883. */
  1884. function randFloat( low, high ) {
  1885. return low + Math.random() * ( high - low );
  1886. }
  1887. /**
  1888. * Returns a random integer from `<-range/2, range/2>` interval.
  1889. *
  1890. * @param {number} range - Defines the value range.
  1891. * @return {number} A random float.
  1892. */
  1893. function randFloatSpread( range ) {
  1894. return range * ( 0.5 - Math.random() );
  1895. }
  1896. /**
  1897. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1898. *
  1899. * @param {number} [s] - The integer seed.
  1900. * @return {number} A random float.
  1901. */
  1902. function seededRandom( s ) {
  1903. if ( s !== undefined ) _seed = s;
  1904. // Mulberry32 generator
  1905. let t = _seed += 0x6D2B79F5;
  1906. t = Math.imul( t ^ t >>> 15, t | 1 );
  1907. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1908. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1909. }
  1910. /**
  1911. * Converts degrees to radians.
  1912. *
  1913. * @param {number} degrees - A value in degrees.
  1914. * @return {number} The converted value in radians.
  1915. */
  1916. function degToRad( degrees ) {
  1917. return degrees * DEG2RAD;
  1918. }
  1919. /**
  1920. * Converts radians to degrees.
  1921. *
  1922. * @param {number} radians - A value in radians.
  1923. * @return {number} The converted value in degrees.
  1924. */
  1925. function radToDeg( radians ) {
  1926. return radians * RAD2DEG;
  1927. }
  1928. /**
  1929. * Returns `true` if the given number is a power of two.
  1930. *
  1931. * @param {number} value - The value to check.
  1932. * @return {boolean} Whether the given number is a power of two or not.
  1933. */
  1934. function isPowerOfTwo( value ) {
  1935. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1936. }
  1937. /**
  1938. * Returns the smallest power of two that is greater than or equal to the given number.
  1939. *
  1940. * @param {number} value - The value to find a POT for.
  1941. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1942. */
  1943. function ceilPowerOfTwo( value ) {
  1944. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1945. }
  1946. /**
  1947. * Returns the largest power of two that is less than or equal to the given number.
  1948. *
  1949. * @param {number} value - The value to find a POT for.
  1950. * @return {number} The largest power of two that is less than or equal to the given number.
  1951. */
  1952. function floorPowerOfTwo( value ) {
  1953. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1954. }
  1955. /**
  1956. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  1957. * defined by the given angles and order.
  1958. *
  1959. * Rotations are applied to the axes in the order specified by order:
  1960. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1961. *
  1962. * @param {Quaternion} q - The quaternion to set.
  1963. * @param {number} a - The rotation applied to the first axis, in radians.
  1964. * @param {number} b - The rotation applied to the second axis, in radians.
  1965. * @param {number} c - The rotation applied to the third axis, in radians.
  1966. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1967. */
  1968. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1969. const cos = Math.cos;
  1970. const sin = Math.sin;
  1971. const c2 = cos( b / 2 );
  1972. const s2 = sin( b / 2 );
  1973. const c13 = cos( ( a + c ) / 2 );
  1974. const s13 = sin( ( a + c ) / 2 );
  1975. const c1_3 = cos( ( a - c ) / 2 );
  1976. const s1_3 = sin( ( a - c ) / 2 );
  1977. const c3_1 = cos( ( c - a ) / 2 );
  1978. const s3_1 = sin( ( c - a ) / 2 );
  1979. switch ( order ) {
  1980. case 'XYX':
  1981. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1982. break;
  1983. case 'YZY':
  1984. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1985. break;
  1986. case 'ZXZ':
  1987. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1988. break;
  1989. case 'XZX':
  1990. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1991. break;
  1992. case 'YXY':
  1993. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1994. break;
  1995. case 'ZYZ':
  1996. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1997. break;
  1998. default:
  1999. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2000. }
  2001. }
  2002. /**
  2003. * Denormalizes the given value according to the given typed array.
  2004. *
  2005. * @param {number} value - The value to denormalize.
  2006. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2007. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2008. */
  2009. function denormalize( value, array ) {
  2010. switch ( array.constructor ) {
  2011. case Float32Array:
  2012. return value;
  2013. case Uint32Array:
  2014. return value / 4294967295.0;
  2015. case Uint16Array:
  2016. return value / 65535.0;
  2017. case Uint8Array:
  2018. return value / 255.0;
  2019. case Int32Array:
  2020. return Math.max( value / 2147483647.0, -1 );
  2021. case Int16Array:
  2022. return Math.max( value / 32767.0, -1 );
  2023. case Int8Array:
  2024. return Math.max( value / 127.0, -1 );
  2025. default:
  2026. throw new Error( 'Invalid component type.' );
  2027. }
  2028. }
  2029. /**
  2030. * Normalizes the given value according to the given typed array.
  2031. *
  2032. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2033. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2034. * @return {number} The normalize value.
  2035. */
  2036. function normalize( value, array ) {
  2037. switch ( array.constructor ) {
  2038. case Float32Array:
  2039. return value;
  2040. case Uint32Array:
  2041. return Math.round( value * 4294967295.0 );
  2042. case Uint16Array:
  2043. return Math.round( value * 65535.0 );
  2044. case Uint8Array:
  2045. return Math.round( value * 255.0 );
  2046. case Int32Array:
  2047. return Math.round( value * 2147483647.0 );
  2048. case Int16Array:
  2049. return Math.round( value * 32767.0 );
  2050. case Int8Array:
  2051. return Math.round( value * 127.0 );
  2052. default:
  2053. throw new Error( 'Invalid component type.' );
  2054. }
  2055. }
  2056. /**
  2057. * @class
  2058. * @classdesc A collection of math utility functions.
  2059. * @hideconstructor
  2060. */
  2061. const MathUtils = {
  2062. DEG2RAD: DEG2RAD,
  2063. RAD2DEG: RAD2DEG,
  2064. /**
  2065. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2066. * (universally unique identifier).
  2067. *
  2068. * @static
  2069. * @method
  2070. * @return {string} The UUID.
  2071. */
  2072. generateUUID: generateUUID,
  2073. /**
  2074. * Clamps the given value between min and max.
  2075. *
  2076. * @static
  2077. * @method
  2078. * @param {number} value - The value to clamp.
  2079. * @param {number} min - The min value.
  2080. * @param {number} max - The max value.
  2081. * @return {number} The clamped value.
  2082. */
  2083. clamp: clamp,
  2084. /**
  2085. * Computes the Euclidean modulo of the given parameters that
  2086. * is `( ( n % m ) + m ) % m`.
  2087. *
  2088. * @static
  2089. * @method
  2090. * @param {number} n - The first parameter.
  2091. * @param {number} m - The second parameter.
  2092. * @return {number} The Euclidean modulo.
  2093. */
  2094. euclideanModulo: euclideanModulo,
  2095. /**
  2096. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2097. * for the given value.
  2098. *
  2099. * @static
  2100. * @method
  2101. * @param {number} x - The value to be mapped.
  2102. * @param {number} a1 - Minimum value for range A.
  2103. * @param {number} a2 - Maximum value for range A.
  2104. * @param {number} b1 - Minimum value for range B.
  2105. * @param {number} b2 - Maximum value for range B.
  2106. * @return {number} The mapped value.
  2107. */
  2108. mapLinear: mapLinear,
  2109. /**
  2110. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2111. * between the start and end point.
  2112. *
  2113. * @static
  2114. * @method
  2115. * @param {number} x - The start point
  2116. * @param {number} y - The end point.
  2117. * @param {number} value - A value between start and end.
  2118. * @return {number} The interpolation factor.
  2119. */
  2120. inverseLerp: inverseLerp,
  2121. /**
  2122. * Returns a value linearly interpolated from two known points based on the given interval -
  2123. * `t = 0` will return `x` and `t = 1` will return `y`.
  2124. *
  2125. * @static
  2126. * @method
  2127. * @param {number} x - The start point
  2128. * @param {number} y - The end point.
  2129. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2130. * @return {number} The interpolated value.
  2131. */
  2132. lerp: lerp,
  2133. /**
  2134. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2135. * time to maintain frame rate independent movement. For details, see
  2136. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2137. *
  2138. * @static
  2139. * @method
  2140. * @param {number} x - The current point.
  2141. * @param {number} y - The target point.
  2142. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2143. * and a lower value will make the movement more gradual.
  2144. * @param {number} dt - Delta time in seconds.
  2145. * @return {number} The interpolated value.
  2146. */
  2147. damp: damp,
  2148. /**
  2149. * Returns a value that alternates between `0` and the given `length` parameter.
  2150. *
  2151. * @static
  2152. * @method
  2153. * @param {number} x - The value to pingpong.
  2154. * @param {number} [length=1] - The positive value the function will pingpong to.
  2155. * @return {number} The alternated value.
  2156. */
  2157. pingpong: pingpong,
  2158. /**
  2159. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2160. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2161. * the `min` and `max`.
  2162. *
  2163. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2164. *
  2165. * @static
  2166. * @method
  2167. * @param {number} x - The value to evaluate based on its position between min and max.
  2168. * @param {number} min - The min value. Any x value below min will be `0`.
  2169. * @param {number} max - The max value. Any x value above max will be `1`.
  2170. * @return {number} The alternated value.
  2171. */
  2172. smoothstep: smoothstep,
  2173. /**
  2174. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2175. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2176. *
  2177. * @static
  2178. * @method
  2179. * @param {number} x - The value to evaluate based on its position between min and max.
  2180. * @param {number} min - The min value. Any x value below min will be `0`.
  2181. * @param {number} max - The max value. Any x value above max will be `1`.
  2182. * @return {number} The alternated value.
  2183. */
  2184. smootherstep: smootherstep,
  2185. /**
  2186. * Returns a random integer from `<low, high>` interval.
  2187. *
  2188. * @static
  2189. * @method
  2190. * @param {number} low - The lower value boundary.
  2191. * @param {number} high - The upper value boundary
  2192. * @return {number} A random integer.
  2193. */
  2194. randInt: randInt,
  2195. /**
  2196. * Returns a random float from `<low, high>` interval.
  2197. *
  2198. * @static
  2199. * @method
  2200. * @param {number} low - The lower value boundary.
  2201. * @param {number} high - The upper value boundary
  2202. * @return {number} A random float.
  2203. */
  2204. randFloat: randFloat,
  2205. /**
  2206. * Returns a random integer from `<-range/2, range/2>` interval.
  2207. *
  2208. * @static
  2209. * @method
  2210. * @param {number} range - Defines the value range.
  2211. * @return {number} A random float.
  2212. */
  2213. randFloatSpread: randFloatSpread,
  2214. /**
  2215. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2216. *
  2217. * @static
  2218. * @method
  2219. * @param {number} [s] - The integer seed.
  2220. * @return {number} A random float.
  2221. */
  2222. seededRandom: seededRandom,
  2223. /**
  2224. * Converts degrees to radians.
  2225. *
  2226. * @static
  2227. * @method
  2228. * @param {number} degrees - A value in degrees.
  2229. * @return {number} The converted value in radians.
  2230. */
  2231. degToRad: degToRad,
  2232. /**
  2233. * Converts radians to degrees.
  2234. *
  2235. * @static
  2236. * @method
  2237. * @param {number} radians - A value in radians.
  2238. * @return {number} The converted value in degrees.
  2239. */
  2240. radToDeg: radToDeg,
  2241. /**
  2242. * Returns `true` if the given number is a power of two.
  2243. *
  2244. * @static
  2245. * @method
  2246. * @param {number} value - The value to check.
  2247. * @return {boolean} Whether the given number is a power of two or not.
  2248. */
  2249. isPowerOfTwo: isPowerOfTwo,
  2250. /**
  2251. * Returns the smallest power of two that is greater than or equal to the given number.
  2252. *
  2253. * @static
  2254. * @method
  2255. * @param {number} value - The value to find a POT for.
  2256. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2257. */
  2258. ceilPowerOfTwo: ceilPowerOfTwo,
  2259. /**
  2260. * Returns the largest power of two that is less than or equal to the given number.
  2261. *
  2262. * @static
  2263. * @method
  2264. * @param {number} value - The value to find a POT for.
  2265. * @return {number} The largest power of two that is less than or equal to the given number.
  2266. */
  2267. floorPowerOfTwo: floorPowerOfTwo,
  2268. /**
  2269. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2270. * defined by the given angles and order.
  2271. *
  2272. * Rotations are applied to the axes in the order specified by order:
  2273. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2274. *
  2275. * @static
  2276. * @method
  2277. * @param {Quaternion} q - The quaternion to set.
  2278. * @param {number} a - The rotation applied to the first axis, in radians.
  2279. * @param {number} b - The rotation applied to the second axis, in radians.
  2280. * @param {number} c - The rotation applied to the third axis, in radians.
  2281. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2282. */
  2283. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2284. /**
  2285. * Normalizes the given value according to the given typed array.
  2286. *
  2287. * @static
  2288. * @method
  2289. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2290. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2291. * @return {number} The normalize value.
  2292. */
  2293. normalize: normalize,
  2294. /**
  2295. * Denormalizes the given value according to the given typed array.
  2296. *
  2297. * @static
  2298. * @method
  2299. * @param {number} value - The value to denormalize.
  2300. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2301. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2302. */
  2303. denormalize: denormalize
  2304. };
  2305. /**
  2306. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2307. * (labeled x and y), which can be used to represent a number of things, such as:
  2308. *
  2309. * - A point in 2D space (i.e. a position on a plane).
  2310. * - A direction and length across a plane. In three.js the length will
  2311. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2312. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2313. * - Any arbitrary ordered pair of numbers.
  2314. *
  2315. * There are other things a 2D vector can be used to represent, such as
  2316. * momentum vectors, complex numbers and so on, however these are the most
  2317. * common uses in three.js.
  2318. *
  2319. * Iterating through a vector instance will yield its components `(x, y)` in
  2320. * the corresponding order.
  2321. * ```js
  2322. * const a = new THREE.Vector2( 0, 1 );
  2323. *
  2324. * //no arguments; will be initialised to (0, 0)
  2325. * const b = new THREE.Vector2( );
  2326. *
  2327. * const d = a.distanceTo( b );
  2328. * ```
  2329. */
  2330. class Vector2 {
  2331. /**
  2332. * Constructs a new 2D vector.
  2333. *
  2334. * @param {number} [x=0] - The x value of this vector.
  2335. * @param {number} [y=0] - The y value of this vector.
  2336. */
  2337. constructor( x = 0, y = 0 ) {
  2338. /**
  2339. * This flag can be used for type testing.
  2340. *
  2341. * @type {boolean}
  2342. * @readonly
  2343. * @default true
  2344. */
  2345. Vector2.prototype.isVector2 = true;
  2346. /**
  2347. * The x value of this vector.
  2348. *
  2349. * @type {number}
  2350. */
  2351. this.x = x;
  2352. /**
  2353. * The y value of this vector.
  2354. *
  2355. * @type {number}
  2356. */
  2357. this.y = y;
  2358. }
  2359. /**
  2360. * Alias for {@link Vector2#x}.
  2361. *
  2362. * @type {number}
  2363. */
  2364. get width() {
  2365. return this.x;
  2366. }
  2367. set width( value ) {
  2368. this.x = value;
  2369. }
  2370. /**
  2371. * Alias for {@link Vector2#y}.
  2372. *
  2373. * @type {number}
  2374. */
  2375. get height() {
  2376. return this.y;
  2377. }
  2378. set height( value ) {
  2379. this.y = value;
  2380. }
  2381. /**
  2382. * Sets the vector components.
  2383. *
  2384. * @param {number} x - The value of the x component.
  2385. * @param {number} y - The value of the y component.
  2386. * @return {Vector2} A reference to this vector.
  2387. */
  2388. set( x, y ) {
  2389. this.x = x;
  2390. this.y = y;
  2391. return this;
  2392. }
  2393. /**
  2394. * Sets the vector components to the same value.
  2395. *
  2396. * @param {number} scalar - The value to set for all vector components.
  2397. * @return {Vector2} A reference to this vector.
  2398. */
  2399. setScalar( scalar ) {
  2400. this.x = scalar;
  2401. this.y = scalar;
  2402. return this;
  2403. }
  2404. /**
  2405. * Sets the vector's x component to the given value
  2406. *
  2407. * @param {number} x - The value to set.
  2408. * @return {Vector2} A reference to this vector.
  2409. */
  2410. setX( x ) {
  2411. this.x = x;
  2412. return this;
  2413. }
  2414. /**
  2415. * Sets the vector's y component to the given value
  2416. *
  2417. * @param {number} y - The value to set.
  2418. * @return {Vector2} A reference to this vector.
  2419. */
  2420. setY( y ) {
  2421. this.y = y;
  2422. return this;
  2423. }
  2424. /**
  2425. * Allows to set a vector component with an index.
  2426. *
  2427. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2428. * @param {number} value - The value to set.
  2429. * @return {Vector2} A reference to this vector.
  2430. */
  2431. setComponent( index, value ) {
  2432. switch ( index ) {
  2433. case 0: this.x = value; break;
  2434. case 1: this.y = value; break;
  2435. default: throw new Error( 'index is out of range: ' + index );
  2436. }
  2437. return this;
  2438. }
  2439. /**
  2440. * Returns the value of the vector component which matches the given index.
  2441. *
  2442. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2443. * @return {number} A vector component value.
  2444. */
  2445. getComponent( index ) {
  2446. switch ( index ) {
  2447. case 0: return this.x;
  2448. case 1: return this.y;
  2449. default: throw new Error( 'index is out of range: ' + index );
  2450. }
  2451. }
  2452. /**
  2453. * Returns a new vector with copied values from this instance.
  2454. *
  2455. * @return {Vector2} A clone of this instance.
  2456. */
  2457. clone() {
  2458. return new this.constructor( this.x, this.y );
  2459. }
  2460. /**
  2461. * Copies the values of the given vector to this instance.
  2462. *
  2463. * @param {Vector2} v - The vector to copy.
  2464. * @return {Vector2} A reference to this vector.
  2465. */
  2466. copy( v ) {
  2467. this.x = v.x;
  2468. this.y = v.y;
  2469. return this;
  2470. }
  2471. /**
  2472. * Adds the given vector to this instance.
  2473. *
  2474. * @param {Vector2} v - The vector to add.
  2475. * @return {Vector2} A reference to this vector.
  2476. */
  2477. add( v ) {
  2478. this.x += v.x;
  2479. this.y += v.y;
  2480. return this;
  2481. }
  2482. /**
  2483. * Adds the given scalar value to all components of this instance.
  2484. *
  2485. * @param {number} s - The scalar to add.
  2486. * @return {Vector2} A reference to this vector.
  2487. */
  2488. addScalar( s ) {
  2489. this.x += s;
  2490. this.y += s;
  2491. return this;
  2492. }
  2493. /**
  2494. * Adds the given vectors and stores the result in this instance.
  2495. *
  2496. * @param {Vector2} a - The first vector.
  2497. * @param {Vector2} b - The second vector.
  2498. * @return {Vector2} A reference to this vector.
  2499. */
  2500. addVectors( a, b ) {
  2501. this.x = a.x + b.x;
  2502. this.y = a.y + b.y;
  2503. return this;
  2504. }
  2505. /**
  2506. * Adds the given vector scaled by the given factor to this instance.
  2507. *
  2508. * @param {Vector2} v - The vector.
  2509. * @param {number} s - The factor that scales `v`.
  2510. * @return {Vector2} A reference to this vector.
  2511. */
  2512. addScaledVector( v, s ) {
  2513. this.x += v.x * s;
  2514. this.y += v.y * s;
  2515. return this;
  2516. }
  2517. /**
  2518. * Subtracts the given vector from this instance.
  2519. *
  2520. * @param {Vector2} v - The vector to subtract.
  2521. * @return {Vector2} A reference to this vector.
  2522. */
  2523. sub( v ) {
  2524. this.x -= v.x;
  2525. this.y -= v.y;
  2526. return this;
  2527. }
  2528. /**
  2529. * Subtracts the given scalar value from all components of this instance.
  2530. *
  2531. * @param {number} s - The scalar to subtract.
  2532. * @return {Vector2} A reference to this vector.
  2533. */
  2534. subScalar( s ) {
  2535. this.x -= s;
  2536. this.y -= s;
  2537. return this;
  2538. }
  2539. /**
  2540. * Subtracts the given vectors and stores the result in this instance.
  2541. *
  2542. * @param {Vector2} a - The first vector.
  2543. * @param {Vector2} b - The second vector.
  2544. * @return {Vector2} A reference to this vector.
  2545. */
  2546. subVectors( a, b ) {
  2547. this.x = a.x - b.x;
  2548. this.y = a.y - b.y;
  2549. return this;
  2550. }
  2551. /**
  2552. * Multiplies the given vector with this instance.
  2553. *
  2554. * @param {Vector2} v - The vector to multiply.
  2555. * @return {Vector2} A reference to this vector.
  2556. */
  2557. multiply( v ) {
  2558. this.x *= v.x;
  2559. this.y *= v.y;
  2560. return this;
  2561. }
  2562. /**
  2563. * Multiplies the given scalar value with all components of this instance.
  2564. *
  2565. * @param {number} scalar - The scalar to multiply.
  2566. * @return {Vector2} A reference to this vector.
  2567. */
  2568. multiplyScalar( scalar ) {
  2569. this.x *= scalar;
  2570. this.y *= scalar;
  2571. return this;
  2572. }
  2573. /**
  2574. * Divides this instance by the given vector.
  2575. *
  2576. * @param {Vector2} v - The vector to divide.
  2577. * @return {Vector2} A reference to this vector.
  2578. */
  2579. divide( v ) {
  2580. this.x /= v.x;
  2581. this.y /= v.y;
  2582. return this;
  2583. }
  2584. /**
  2585. * Divides this vector by the given scalar.
  2586. *
  2587. * @param {number} scalar - The scalar to divide.
  2588. * @return {Vector2} A reference to this vector.
  2589. */
  2590. divideScalar( scalar ) {
  2591. return this.multiplyScalar( 1 / scalar );
  2592. }
  2593. /**
  2594. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2595. * the given 3x3 matrix.
  2596. *
  2597. * @param {Matrix3} m - The matrix to apply.
  2598. * @return {Vector2} A reference to this vector.
  2599. */
  2600. applyMatrix3( m ) {
  2601. const x = this.x, y = this.y;
  2602. const e = m.elements;
  2603. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2604. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2605. return this;
  2606. }
  2607. /**
  2608. * If this vector's x or y value is greater than the given vector's x or y
  2609. * value, replace that value with the corresponding min value.
  2610. *
  2611. * @param {Vector2} v - The vector.
  2612. * @return {Vector2} A reference to this vector.
  2613. */
  2614. min( v ) {
  2615. this.x = Math.min( this.x, v.x );
  2616. this.y = Math.min( this.y, v.y );
  2617. return this;
  2618. }
  2619. /**
  2620. * If this vector's x or y value is less than the given vector's x or y
  2621. * value, replace that value with the corresponding max value.
  2622. *
  2623. * @param {Vector2} v - The vector.
  2624. * @return {Vector2} A reference to this vector.
  2625. */
  2626. max( v ) {
  2627. this.x = Math.max( this.x, v.x );
  2628. this.y = Math.max( this.y, v.y );
  2629. return this;
  2630. }
  2631. /**
  2632. * If this vector's x or y value is greater than the max vector's x or y
  2633. * value, it is replaced by the corresponding value.
  2634. * If this vector's x or y value is less than the min vector's x or y value,
  2635. * it is replaced by the corresponding value.
  2636. *
  2637. * @param {Vector2} min - The minimum x and y values.
  2638. * @param {Vector2} max - The maximum x and y values in the desired range.
  2639. * @return {Vector2} A reference to this vector.
  2640. */
  2641. clamp( min, max ) {
  2642. // assumes min < max, componentwise
  2643. this.x = clamp( this.x, min.x, max.x );
  2644. this.y = clamp( this.y, min.y, max.y );
  2645. return this;
  2646. }
  2647. /**
  2648. * If this vector's x or y values are greater than the max value, they are
  2649. * replaced by the max value.
  2650. * If this vector's x or y values are less than the min value, they are
  2651. * replaced by the min value.
  2652. *
  2653. * @param {number} minVal - The minimum value the components will be clamped to.
  2654. * @param {number} maxVal - The maximum value the components will be clamped to.
  2655. * @return {Vector2} A reference to this vector.
  2656. */
  2657. clampScalar( minVal, maxVal ) {
  2658. this.x = clamp( this.x, minVal, maxVal );
  2659. this.y = clamp( this.y, minVal, maxVal );
  2660. return this;
  2661. }
  2662. /**
  2663. * If this vector's length is greater than the max value, it is replaced by
  2664. * the max value.
  2665. * If this vector's length is less than the min value, it is replaced by the
  2666. * min value.
  2667. *
  2668. * @param {number} min - The minimum value the vector length will be clamped to.
  2669. * @param {number} max - The maximum value the vector length will be clamped to.
  2670. * @return {Vector2} A reference to this vector.
  2671. */
  2672. clampLength( min, max ) {
  2673. const length = this.length();
  2674. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2675. }
  2676. /**
  2677. * The components of this vector are rounded down to the nearest integer value.
  2678. *
  2679. * @return {Vector2} A reference to this vector.
  2680. */
  2681. floor() {
  2682. this.x = Math.floor( this.x );
  2683. this.y = Math.floor( this.y );
  2684. return this;
  2685. }
  2686. /**
  2687. * The components of this vector are rounded up to the nearest integer value.
  2688. *
  2689. * @return {Vector2} A reference to this vector.
  2690. */
  2691. ceil() {
  2692. this.x = Math.ceil( this.x );
  2693. this.y = Math.ceil( this.y );
  2694. return this;
  2695. }
  2696. /**
  2697. * The components of this vector are rounded to the nearest integer value
  2698. *
  2699. * @return {Vector2} A reference to this vector.
  2700. */
  2701. round() {
  2702. this.x = Math.round( this.x );
  2703. this.y = Math.round( this.y );
  2704. return this;
  2705. }
  2706. /**
  2707. * The components of this vector are rounded towards zero (up if negative,
  2708. * down if positive) to an integer value.
  2709. *
  2710. * @return {Vector2} A reference to this vector.
  2711. */
  2712. roundToZero() {
  2713. this.x = Math.trunc( this.x );
  2714. this.y = Math.trunc( this.y );
  2715. return this;
  2716. }
  2717. /**
  2718. * Inverts this vector - i.e. sets x = -x and y = -y.
  2719. *
  2720. * @return {Vector2} A reference to this vector.
  2721. */
  2722. negate() {
  2723. this.x = - this.x;
  2724. this.y = - this.y;
  2725. return this;
  2726. }
  2727. /**
  2728. * Calculates the dot product of the given vector with this instance.
  2729. *
  2730. * @param {Vector2} v - The vector to compute the dot product with.
  2731. * @return {number} The result of the dot product.
  2732. */
  2733. dot( v ) {
  2734. return this.x * v.x + this.y * v.y;
  2735. }
  2736. /**
  2737. * Calculates the cross product of the given vector with this instance.
  2738. *
  2739. * @param {Vector2} v - The vector to compute the cross product with.
  2740. * @return {number} The result of the cross product.
  2741. */
  2742. cross( v ) {
  2743. return this.x * v.y - this.y * v.x;
  2744. }
  2745. /**
  2746. * Computes the square of the Euclidean length (straight-line length) from
  2747. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2748. * compare the length squared instead as it is slightly more efficient to calculate.
  2749. *
  2750. * @return {number} The square length of this vector.
  2751. */
  2752. lengthSq() {
  2753. return this.x * this.x + this.y * this.y;
  2754. }
  2755. /**
  2756. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2757. *
  2758. * @return {number} The length of this vector.
  2759. */
  2760. length() {
  2761. return Math.sqrt( this.x * this.x + this.y * this.y );
  2762. }
  2763. /**
  2764. * Computes the Manhattan length of this vector.
  2765. *
  2766. * @return {number} The length of this vector.
  2767. */
  2768. manhattanLength() {
  2769. return Math.abs( this.x ) + Math.abs( this.y );
  2770. }
  2771. /**
  2772. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2773. * with the same direction as this one, but with a vector length of `1`.
  2774. *
  2775. * @return {Vector2} A reference to this vector.
  2776. */
  2777. normalize() {
  2778. return this.divideScalar( this.length() || 1 );
  2779. }
  2780. /**
  2781. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2782. *
  2783. * @return {number} The angle in radians.
  2784. */
  2785. angle() {
  2786. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2787. return angle;
  2788. }
  2789. /**
  2790. * Returns the angle between the given vector and this instance in radians.
  2791. *
  2792. * @param {Vector2} v - The vector to compute the angle with.
  2793. * @return {number} The angle in radians.
  2794. */
  2795. angleTo( v ) {
  2796. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2797. if ( denominator === 0 ) return Math.PI / 2;
  2798. const theta = this.dot( v ) / denominator;
  2799. // clamp, to handle numerical problems
  2800. return Math.acos( clamp( theta, -1, 1 ) );
  2801. }
  2802. /**
  2803. * Computes the distance from the given vector to this instance.
  2804. *
  2805. * @param {Vector2} v - The vector to compute the distance to.
  2806. * @return {number} The distance.
  2807. */
  2808. distanceTo( v ) {
  2809. return Math.sqrt( this.distanceToSquared( v ) );
  2810. }
  2811. /**
  2812. * Computes the squared distance from the given vector to this instance.
  2813. * If you are just comparing the distance with another distance, you should compare
  2814. * the distance squared instead as it is slightly more efficient to calculate.
  2815. *
  2816. * @param {Vector2} v - The vector to compute the squared distance to.
  2817. * @return {number} The squared distance.
  2818. */
  2819. distanceToSquared( v ) {
  2820. const dx = this.x - v.x, dy = this.y - v.y;
  2821. return dx * dx + dy * dy;
  2822. }
  2823. /**
  2824. * Computes the Manhattan distance from the given vector to this instance.
  2825. *
  2826. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2827. * @return {number} The Manhattan distance.
  2828. */
  2829. manhattanDistanceTo( v ) {
  2830. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2831. }
  2832. /**
  2833. * Sets this vector to a vector with the same direction as this one, but
  2834. * with the specified length.
  2835. *
  2836. * @param {number} length - The new length of this vector.
  2837. * @return {Vector2} A reference to this vector.
  2838. */
  2839. setLength( length ) {
  2840. return this.normalize().multiplyScalar( length );
  2841. }
  2842. /**
  2843. * Linearly interpolates between the given vector and this instance, where
  2844. * alpha is the percent distance along the line - alpha = 0 will be this
  2845. * vector, and alpha = 1 will be the given one.
  2846. *
  2847. * @param {Vector2} v - The vector to interpolate towards.
  2848. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2849. * @return {Vector2} A reference to this vector.
  2850. */
  2851. lerp( v, alpha ) {
  2852. this.x += ( v.x - this.x ) * alpha;
  2853. this.y += ( v.y - this.y ) * alpha;
  2854. return this;
  2855. }
  2856. /**
  2857. * Linearly interpolates between the given vectors, where alpha is the percent
  2858. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2859. * be the second one. The result is stored in this instance.
  2860. *
  2861. * @param {Vector2} v1 - The first vector.
  2862. * @param {Vector2} v2 - The second vector.
  2863. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2864. * @return {Vector2} A reference to this vector.
  2865. */
  2866. lerpVectors( v1, v2, alpha ) {
  2867. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2868. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2869. return this;
  2870. }
  2871. /**
  2872. * Returns `true` if this vector is equal with the given one.
  2873. *
  2874. * @param {Vector2} v - The vector to test for equality.
  2875. * @return {boolean} Whether this vector is equal with the given one.
  2876. */
  2877. equals( v ) {
  2878. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2879. }
  2880. /**
  2881. * Sets this vector's x value to be `array[ offset ]` and y
  2882. * value to be `array[ offset + 1 ]`.
  2883. *
  2884. * @param {Array<number>} array - An array holding the vector component values.
  2885. * @param {number} [offset=0] - The offset into the array.
  2886. * @return {Vector2} A reference to this vector.
  2887. */
  2888. fromArray( array, offset = 0 ) {
  2889. this.x = array[ offset ];
  2890. this.y = array[ offset + 1 ];
  2891. return this;
  2892. }
  2893. /**
  2894. * Writes the components of this vector to the given array. If no array is provided,
  2895. * the method returns a new instance.
  2896. *
  2897. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2898. * @param {number} [offset=0] - Index of the first element in the array.
  2899. * @return {Array<number>} The vector components.
  2900. */
  2901. toArray( array = [], offset = 0 ) {
  2902. array[ offset ] = this.x;
  2903. array[ offset + 1 ] = this.y;
  2904. return array;
  2905. }
  2906. /**
  2907. * Sets the components of this vector from the given buffer attribute.
  2908. *
  2909. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2910. * @param {number} index - The index into the attribute.
  2911. * @return {Vector2} A reference to this vector.
  2912. */
  2913. fromBufferAttribute( attribute, index ) {
  2914. this.x = attribute.getX( index );
  2915. this.y = attribute.getY( index );
  2916. return this;
  2917. }
  2918. /**
  2919. * Rotates this vector around the given center by the given angle.
  2920. *
  2921. * @param {Vector2} center - The point around which to rotate.
  2922. * @param {number} angle - The angle to rotate, in radians.
  2923. * @return {Vector2} A reference to this vector.
  2924. */
  2925. rotateAround( center, angle ) {
  2926. const c = Math.cos( angle ), s = Math.sin( angle );
  2927. const x = this.x - center.x;
  2928. const y = this.y - center.y;
  2929. this.x = x * c - y * s + center.x;
  2930. this.y = x * s + y * c + center.y;
  2931. return this;
  2932. }
  2933. /**
  2934. * Sets each component of this vector to a pseudo-random value between `0` and
  2935. * `1`, excluding `1`.
  2936. *
  2937. * @return {Vector2} A reference to this vector.
  2938. */
  2939. random() {
  2940. this.x = Math.random();
  2941. this.y = Math.random();
  2942. return this;
  2943. }
  2944. *[ Symbol.iterator ]() {
  2945. yield this.x;
  2946. yield this.y;
  2947. }
  2948. }
  2949. /**
  2950. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2951. *
  2952. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2953. * the corresponding order.
  2954. *
  2955. * Note that three.js expects Quaternions to be normalized.
  2956. * ```js
  2957. * const quaternion = new THREE.Quaternion();
  2958. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2959. *
  2960. * const vector = new THREE.Vector3( 1, 0, 0 );
  2961. * vector.applyQuaternion( quaternion );
  2962. * ```
  2963. */
  2964. class Quaternion {
  2965. /**
  2966. * Constructs a new quaternion.
  2967. *
  2968. * @param {number} [x=0] - The x value of this quaternion.
  2969. * @param {number} [y=0] - The y value of this quaternion.
  2970. * @param {number} [z=0] - The z value of this quaternion.
  2971. * @param {number} [w=1] - The w value of this quaternion.
  2972. */
  2973. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2974. /**
  2975. * This flag can be used for type testing.
  2976. *
  2977. * @type {boolean}
  2978. * @readonly
  2979. * @default true
  2980. */
  2981. this.isQuaternion = true;
  2982. this._x = x;
  2983. this._y = y;
  2984. this._z = z;
  2985. this._w = w;
  2986. }
  2987. /**
  2988. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2989. * quaternion data are managed in flat arrays.
  2990. *
  2991. * @param {Array<number>} dst - The destination array.
  2992. * @param {number} dstOffset - An offset into the destination array.
  2993. * @param {Array<number>} src0 - The source array of the first quaternion.
  2994. * @param {number} srcOffset0 - An offset into the first source array.
  2995. * @param {Array<number>} src1 - The source array of the second quaternion.
  2996. * @param {number} srcOffset1 - An offset into the second source array.
  2997. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  2998. * @see {@link Quaternion#slerp}
  2999. */
  3000. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3001. let x0 = src0[ srcOffset0 + 0 ],
  3002. y0 = src0[ srcOffset0 + 1 ],
  3003. z0 = src0[ srcOffset0 + 2 ],
  3004. w0 = src0[ srcOffset0 + 3 ];
  3005. let x1 = src1[ srcOffset1 + 0 ],
  3006. y1 = src1[ srcOffset1 + 1 ],
  3007. z1 = src1[ srcOffset1 + 2 ],
  3008. w1 = src1[ srcOffset1 + 3 ];
  3009. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3010. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3011. if ( dot < 0 ) {
  3012. x1 = - x1;
  3013. y1 = - y1;
  3014. z1 = - z1;
  3015. w1 = - w1;
  3016. dot = - dot;
  3017. }
  3018. let s = 1 - t;
  3019. if ( dot < 0.9995 ) {
  3020. // slerp
  3021. const theta = Math.acos( dot );
  3022. const sin = Math.sin( theta );
  3023. s = Math.sin( s * theta ) / sin;
  3024. t = Math.sin( t * theta ) / sin;
  3025. x0 = x0 * s + x1 * t;
  3026. y0 = y0 * s + y1 * t;
  3027. z0 = z0 * s + z1 * t;
  3028. w0 = w0 * s + w1 * t;
  3029. } else {
  3030. // for small angles, lerp then normalize
  3031. x0 = x0 * s + x1 * t;
  3032. y0 = y0 * s + y1 * t;
  3033. z0 = z0 * s + z1 * t;
  3034. w0 = w0 * s + w1 * t;
  3035. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3036. x0 *= f;
  3037. y0 *= f;
  3038. z0 *= f;
  3039. w0 *= f;
  3040. }
  3041. }
  3042. dst[ dstOffset ] = x0;
  3043. dst[ dstOffset + 1 ] = y0;
  3044. dst[ dstOffset + 2 ] = z0;
  3045. dst[ dstOffset + 3 ] = w0;
  3046. }
  3047. /**
  3048. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3049. * in flat arrays.
  3050. *
  3051. * @param {Array<number>} dst - The destination array.
  3052. * @param {number} dstOffset - An offset into the destination array.
  3053. * @param {Array<number>} src0 - The source array of the first quaternion.
  3054. * @param {number} srcOffset0 - An offset into the first source array.
  3055. * @param {Array<number>} src1 - The source array of the second quaternion.
  3056. * @param {number} srcOffset1 - An offset into the second source array.
  3057. * @return {Array<number>} The destination array.
  3058. * @see {@link Quaternion#multiplyQuaternions}.
  3059. */
  3060. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3061. const x0 = src0[ srcOffset0 ];
  3062. const y0 = src0[ srcOffset0 + 1 ];
  3063. const z0 = src0[ srcOffset0 + 2 ];
  3064. const w0 = src0[ srcOffset0 + 3 ];
  3065. const x1 = src1[ srcOffset1 ];
  3066. const y1 = src1[ srcOffset1 + 1 ];
  3067. const z1 = src1[ srcOffset1 + 2 ];
  3068. const w1 = src1[ srcOffset1 + 3 ];
  3069. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3070. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3071. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3072. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3073. return dst;
  3074. }
  3075. /**
  3076. * The x value of this quaternion.
  3077. *
  3078. * @type {number}
  3079. * @default 0
  3080. */
  3081. get x() {
  3082. return this._x;
  3083. }
  3084. set x( value ) {
  3085. this._x = value;
  3086. this._onChangeCallback();
  3087. }
  3088. /**
  3089. * The y value of this quaternion.
  3090. *
  3091. * @type {number}
  3092. * @default 0
  3093. */
  3094. get y() {
  3095. return this._y;
  3096. }
  3097. set y( value ) {
  3098. this._y = value;
  3099. this._onChangeCallback();
  3100. }
  3101. /**
  3102. * The z value of this quaternion.
  3103. *
  3104. * @type {number}
  3105. * @default 0
  3106. */
  3107. get z() {
  3108. return this._z;
  3109. }
  3110. set z( value ) {
  3111. this._z = value;
  3112. this._onChangeCallback();
  3113. }
  3114. /**
  3115. * The w value of this quaternion.
  3116. *
  3117. * @type {number}
  3118. * @default 1
  3119. */
  3120. get w() {
  3121. return this._w;
  3122. }
  3123. set w( value ) {
  3124. this._w = value;
  3125. this._onChangeCallback();
  3126. }
  3127. /**
  3128. * Sets the quaternion components.
  3129. *
  3130. * @param {number} x - The x value of this quaternion.
  3131. * @param {number} y - The y value of this quaternion.
  3132. * @param {number} z - The z value of this quaternion.
  3133. * @param {number} w - The w value of this quaternion.
  3134. * @return {Quaternion} A reference to this quaternion.
  3135. */
  3136. set( x, y, z, w ) {
  3137. this._x = x;
  3138. this._y = y;
  3139. this._z = z;
  3140. this._w = w;
  3141. this._onChangeCallback();
  3142. return this;
  3143. }
  3144. /**
  3145. * Returns a new quaternion with copied values from this instance.
  3146. *
  3147. * @return {Quaternion} A clone of this instance.
  3148. */
  3149. clone() {
  3150. return new this.constructor( this._x, this._y, this._z, this._w );
  3151. }
  3152. /**
  3153. * Copies the values of the given quaternion to this instance.
  3154. *
  3155. * @param {Quaternion} quaternion - The quaternion to copy.
  3156. * @return {Quaternion} A reference to this quaternion.
  3157. */
  3158. copy( quaternion ) {
  3159. this._x = quaternion.x;
  3160. this._y = quaternion.y;
  3161. this._z = quaternion.z;
  3162. this._w = quaternion.w;
  3163. this._onChangeCallback();
  3164. return this;
  3165. }
  3166. /**
  3167. * Sets this quaternion from the rotation specified by the given
  3168. * Euler angles.
  3169. *
  3170. * @param {Euler} euler - The Euler angles.
  3171. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3172. * @return {Quaternion} A reference to this quaternion.
  3173. */
  3174. setFromEuler( euler, update = true ) {
  3175. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3176. // http://www.mathworks.com/matlabcentral/fileexchange/
  3177. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3178. // content/SpinCalc.m
  3179. const cos = Math.cos;
  3180. const sin = Math.sin;
  3181. const c1 = cos( x / 2 );
  3182. const c2 = cos( y / 2 );
  3183. const c3 = cos( z / 2 );
  3184. const s1 = sin( x / 2 );
  3185. const s2 = sin( y / 2 );
  3186. const s3 = sin( z / 2 );
  3187. switch ( order ) {
  3188. case 'XYZ':
  3189. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3190. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3191. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3192. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3193. break;
  3194. case 'YXZ':
  3195. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3196. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3197. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3198. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3199. break;
  3200. case 'ZXY':
  3201. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3202. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3203. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3204. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3205. break;
  3206. case 'ZYX':
  3207. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3208. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3209. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3210. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3211. break;
  3212. case 'YZX':
  3213. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3214. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3215. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3216. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3217. break;
  3218. case 'XZY':
  3219. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3220. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3221. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3222. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3223. break;
  3224. default:
  3225. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3226. }
  3227. if ( update === true ) this._onChangeCallback();
  3228. return this;
  3229. }
  3230. /**
  3231. * Sets this quaternion from the given axis and angle.
  3232. *
  3233. * @param {Vector3} axis - The normalized axis.
  3234. * @param {number} angle - The angle in radians.
  3235. * @return {Quaternion} A reference to this quaternion.
  3236. */
  3237. setFromAxisAngle( axis, angle ) {
  3238. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3239. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3240. this._x = axis.x * s;
  3241. this._y = axis.y * s;
  3242. this._z = axis.z * s;
  3243. this._w = Math.cos( halfAngle );
  3244. this._onChangeCallback();
  3245. return this;
  3246. }
  3247. /**
  3248. * Sets this quaternion from the given rotation matrix.
  3249. *
  3250. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3251. * @return {Quaternion} A reference to this quaternion.
  3252. */
  3253. setFromRotationMatrix( m ) {
  3254. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3255. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3256. const te = m.elements,
  3257. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3258. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3259. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3260. trace = m11 + m22 + m33;
  3261. if ( trace > 0 ) {
  3262. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3263. this._w = 0.25 / s;
  3264. this._x = ( m32 - m23 ) * s;
  3265. this._y = ( m13 - m31 ) * s;
  3266. this._z = ( m21 - m12 ) * s;
  3267. } else if ( m11 > m22 && m11 > m33 ) {
  3268. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3269. this._w = ( m32 - m23 ) / s;
  3270. this._x = 0.25 * s;
  3271. this._y = ( m12 + m21 ) / s;
  3272. this._z = ( m13 + m31 ) / s;
  3273. } else if ( m22 > m33 ) {
  3274. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3275. this._w = ( m13 - m31 ) / s;
  3276. this._x = ( m12 + m21 ) / s;
  3277. this._y = 0.25 * s;
  3278. this._z = ( m23 + m32 ) / s;
  3279. } else {
  3280. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3281. this._w = ( m21 - m12 ) / s;
  3282. this._x = ( m13 + m31 ) / s;
  3283. this._y = ( m23 + m32 ) / s;
  3284. this._z = 0.25 * s;
  3285. }
  3286. this._onChangeCallback();
  3287. return this;
  3288. }
  3289. /**
  3290. * Sets this quaternion to the rotation required to rotate the direction vector
  3291. * `vFrom` to the direction vector `vTo`.
  3292. *
  3293. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3294. * @param {Vector3} vTo - The second (normalized) direction vector.
  3295. * @return {Quaternion} A reference to this quaternion.
  3296. */
  3297. setFromUnitVectors( vFrom, vTo ) {
  3298. // assumes direction vectors vFrom and vTo are normalized
  3299. let r = vFrom.dot( vTo ) + 1;
  3300. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3301. // vFrom and vTo point in opposite directions
  3302. r = 0;
  3303. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3304. this._x = - vFrom.y;
  3305. this._y = vFrom.x;
  3306. this._z = 0;
  3307. this._w = r;
  3308. } else {
  3309. this._x = 0;
  3310. this._y = - vFrom.z;
  3311. this._z = vFrom.y;
  3312. this._w = r;
  3313. }
  3314. } else {
  3315. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3316. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3317. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3318. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3319. this._w = r;
  3320. }
  3321. return this.normalize();
  3322. }
  3323. /**
  3324. * Returns the angle between this quaternion and the given one in radians.
  3325. *
  3326. * @param {Quaternion} q - The quaternion to compute the angle with.
  3327. * @return {number} The angle in radians.
  3328. */
  3329. angleTo( q ) {
  3330. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3331. }
  3332. /**
  3333. * Rotates this quaternion by a given angular step to the given quaternion.
  3334. * The method ensures that the final quaternion will not overshoot `q`.
  3335. *
  3336. * @param {Quaternion} q - The target quaternion.
  3337. * @param {number} step - The angular step in radians.
  3338. * @return {Quaternion} A reference to this quaternion.
  3339. */
  3340. rotateTowards( q, step ) {
  3341. const angle = this.angleTo( q );
  3342. if ( angle === 0 ) return this;
  3343. const t = Math.min( 1, step / angle );
  3344. this.slerp( q, t );
  3345. return this;
  3346. }
  3347. /**
  3348. * Sets this quaternion to the identity quaternion; that is, to the
  3349. * quaternion that represents "no rotation".
  3350. *
  3351. * @return {Quaternion} A reference to this quaternion.
  3352. */
  3353. identity() {
  3354. return this.set( 0, 0, 0, 1 );
  3355. }
  3356. /**
  3357. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3358. * quaternion is assumed to have unit length.
  3359. *
  3360. * @return {Quaternion} A reference to this quaternion.
  3361. */
  3362. invert() {
  3363. return this.conjugate();
  3364. }
  3365. /**
  3366. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3367. * quaternion represents the same rotation in the opposite direction about
  3368. * the rotational axis.
  3369. *
  3370. * @return {Quaternion} A reference to this quaternion.
  3371. */
  3372. conjugate() {
  3373. this._x *= -1;
  3374. this._y *= -1;
  3375. this._z *= -1;
  3376. this._onChangeCallback();
  3377. return this;
  3378. }
  3379. /**
  3380. * Calculates the dot product of this quaternion and the given one.
  3381. *
  3382. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3383. * @return {number} The result of the dot product.
  3384. */
  3385. dot( v ) {
  3386. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3387. }
  3388. /**
  3389. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3390. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3391. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3392. * {@link Quaternion#length}.
  3393. *
  3394. * @return {number} The squared Euclidean length.
  3395. */
  3396. lengthSq() {
  3397. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3398. }
  3399. /**
  3400. * Computes the Euclidean length (straight-line length) of this quaternion,
  3401. * considered as a 4 dimensional vector.
  3402. *
  3403. * @return {number} The Euclidean length.
  3404. */
  3405. length() {
  3406. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3407. }
  3408. /**
  3409. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3410. * the same rotation as this one, but has a length equal to `1`.
  3411. *
  3412. * @return {Quaternion} A reference to this quaternion.
  3413. */
  3414. normalize() {
  3415. let l = this.length();
  3416. if ( l === 0 ) {
  3417. this._x = 0;
  3418. this._y = 0;
  3419. this._z = 0;
  3420. this._w = 1;
  3421. } else {
  3422. l = 1 / l;
  3423. this._x = this._x * l;
  3424. this._y = this._y * l;
  3425. this._z = this._z * l;
  3426. this._w = this._w * l;
  3427. }
  3428. this._onChangeCallback();
  3429. return this;
  3430. }
  3431. /**
  3432. * Multiplies this quaternion by the given one.
  3433. *
  3434. * @param {Quaternion} q - The quaternion.
  3435. * @return {Quaternion} A reference to this quaternion.
  3436. */
  3437. multiply( q ) {
  3438. return this.multiplyQuaternions( this, q );
  3439. }
  3440. /**
  3441. * Pre-multiplies this quaternion by the given one.
  3442. *
  3443. * @param {Quaternion} q - The quaternion.
  3444. * @return {Quaternion} A reference to this quaternion.
  3445. */
  3446. premultiply( q ) {
  3447. return this.multiplyQuaternions( q, this );
  3448. }
  3449. /**
  3450. * Multiplies the given quaternions and stores the result in this instance.
  3451. *
  3452. * @param {Quaternion} a - The first quaternion.
  3453. * @param {Quaternion} b - The second quaternion.
  3454. * @return {Quaternion} A reference to this quaternion.
  3455. */
  3456. multiplyQuaternions( a, b ) {
  3457. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3458. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3459. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3460. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3461. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3462. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3463. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3464. this._onChangeCallback();
  3465. return this;
  3466. }
  3467. /**
  3468. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3469. *
  3470. * @param {Quaternion} qb - The target quaternion.
  3471. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3472. * @return {Quaternion} A reference to this quaternion.
  3473. */
  3474. slerp( qb, t ) {
  3475. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3476. let dot = this.dot( qb );
  3477. if ( dot < 0 ) {
  3478. x = - x;
  3479. y = - y;
  3480. z = - z;
  3481. w = - w;
  3482. dot = - dot;
  3483. }
  3484. let s = 1 - t;
  3485. if ( dot < 0.9995 ) {
  3486. // slerp
  3487. const theta = Math.acos( dot );
  3488. const sin = Math.sin( theta );
  3489. s = Math.sin( s * theta ) / sin;
  3490. t = Math.sin( t * theta ) / sin;
  3491. this._x = this._x * s + x * t;
  3492. this._y = this._y * s + y * t;
  3493. this._z = this._z * s + z * t;
  3494. this._w = this._w * s + w * t;
  3495. this._onChangeCallback();
  3496. } else {
  3497. // for small angles, lerp then normalize
  3498. this._x = this._x * s + x * t;
  3499. this._y = this._y * s + y * t;
  3500. this._z = this._z * s + z * t;
  3501. this._w = this._w * s + w * t;
  3502. this.normalize(); // normalize calls _onChangeCallback()
  3503. }
  3504. return this;
  3505. }
  3506. /**
  3507. * Performs a spherical linear interpolation between the given quaternions
  3508. * and stores the result in this quaternion.
  3509. *
  3510. * @param {Quaternion} qa - The source quaternion.
  3511. * @param {Quaternion} qb - The target quaternion.
  3512. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3513. * @return {Quaternion} A reference to this quaternion.
  3514. */
  3515. slerpQuaternions( qa, qb, t ) {
  3516. return this.copy( qa ).slerp( qb, t );
  3517. }
  3518. /**
  3519. * Sets this quaternion to a uniformly random, normalized quaternion.
  3520. *
  3521. * @return {Quaternion} A reference to this quaternion.
  3522. */
  3523. random() {
  3524. // Ken Shoemake
  3525. // Uniform random rotations
  3526. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3527. const theta1 = 2 * Math.PI * Math.random();
  3528. const theta2 = 2 * Math.PI * Math.random();
  3529. const x0 = Math.random();
  3530. const r1 = Math.sqrt( 1 - x0 );
  3531. const r2 = Math.sqrt( x0 );
  3532. return this.set(
  3533. r1 * Math.sin( theta1 ),
  3534. r1 * Math.cos( theta1 ),
  3535. r2 * Math.sin( theta2 ),
  3536. r2 * Math.cos( theta2 ),
  3537. );
  3538. }
  3539. /**
  3540. * Returns `true` if this quaternion is equal with the given one.
  3541. *
  3542. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3543. * @return {boolean} Whether this quaternion is equal with the given one.
  3544. */
  3545. equals( quaternion ) {
  3546. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3547. }
  3548. /**
  3549. * Sets this quaternion's components from the given array.
  3550. *
  3551. * @param {Array<number>} array - An array holding the quaternion component values.
  3552. * @param {number} [offset=0] - The offset into the array.
  3553. * @return {Quaternion} A reference to this quaternion.
  3554. */
  3555. fromArray( array, offset = 0 ) {
  3556. this._x = array[ offset ];
  3557. this._y = array[ offset + 1 ];
  3558. this._z = array[ offset + 2 ];
  3559. this._w = array[ offset + 3 ];
  3560. this._onChangeCallback();
  3561. return this;
  3562. }
  3563. /**
  3564. * Writes the components of this quaternion to the given array. If no array is provided,
  3565. * the method returns a new instance.
  3566. *
  3567. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3568. * @param {number} [offset=0] - Index of the first element in the array.
  3569. * @return {Array<number>} The quaternion components.
  3570. */
  3571. toArray( array = [], offset = 0 ) {
  3572. array[ offset ] = this._x;
  3573. array[ offset + 1 ] = this._y;
  3574. array[ offset + 2 ] = this._z;
  3575. array[ offset + 3 ] = this._w;
  3576. return array;
  3577. }
  3578. /**
  3579. * Sets the components of this quaternion from the given buffer attribute.
  3580. *
  3581. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3582. * @param {number} index - The index into the attribute.
  3583. * @return {Quaternion} A reference to this quaternion.
  3584. */
  3585. fromBufferAttribute( attribute, index ) {
  3586. this._x = attribute.getX( index );
  3587. this._y = attribute.getY( index );
  3588. this._z = attribute.getZ( index );
  3589. this._w = attribute.getW( index );
  3590. this._onChangeCallback();
  3591. return this;
  3592. }
  3593. /**
  3594. * This methods defines the serialization result of this class. Returns the
  3595. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3596. *
  3597. * @return {Array<number>} The serialized quaternion.
  3598. */
  3599. toJSON() {
  3600. return this.toArray();
  3601. }
  3602. _onChange( callback ) {
  3603. this._onChangeCallback = callback;
  3604. return this;
  3605. }
  3606. _onChangeCallback() {}
  3607. *[ Symbol.iterator ]() {
  3608. yield this._x;
  3609. yield this._y;
  3610. yield this._z;
  3611. yield this._w;
  3612. }
  3613. }
  3614. /**
  3615. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3616. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3617. *
  3618. * - A point in 3D space.
  3619. * - A direction and length in 3D space. In three.js the length will
  3620. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3621. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3622. * - Any arbitrary ordered triplet of numbers.
  3623. *
  3624. * There are other things a 3D vector can be used to represent, such as
  3625. * momentum vectors and so on, however these are the most
  3626. * common uses in three.js.
  3627. *
  3628. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3629. * the corresponding order.
  3630. * ```js
  3631. * const a = new THREE.Vector3( 0, 1, 0 );
  3632. *
  3633. * //no arguments; will be initialised to (0, 0, 0)
  3634. * const b = new THREE.Vector3( );
  3635. *
  3636. * const d = a.distanceTo( b );
  3637. * ```
  3638. */
  3639. class Vector3 {
  3640. /**
  3641. * Constructs a new 3D vector.
  3642. *
  3643. * @param {number} [x=0] - The x value of this vector.
  3644. * @param {number} [y=0] - The y value of this vector.
  3645. * @param {number} [z=0] - The z value of this vector.
  3646. */
  3647. constructor( x = 0, y = 0, z = 0 ) {
  3648. /**
  3649. * This flag can be used for type testing.
  3650. *
  3651. * @type {boolean}
  3652. * @readonly
  3653. * @default true
  3654. */
  3655. Vector3.prototype.isVector3 = true;
  3656. /**
  3657. * The x value of this vector.
  3658. *
  3659. * @type {number}
  3660. */
  3661. this.x = x;
  3662. /**
  3663. * The y value of this vector.
  3664. *
  3665. * @type {number}
  3666. */
  3667. this.y = y;
  3668. /**
  3669. * The z value of this vector.
  3670. *
  3671. * @type {number}
  3672. */
  3673. this.z = z;
  3674. }
  3675. /**
  3676. * Sets the vector components.
  3677. *
  3678. * @param {number} x - The value of the x component.
  3679. * @param {number} y - The value of the y component.
  3680. * @param {number} z - The value of the z component.
  3681. * @return {Vector3} A reference to this vector.
  3682. */
  3683. set( x, y, z ) {
  3684. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3685. this.x = x;
  3686. this.y = y;
  3687. this.z = z;
  3688. return this;
  3689. }
  3690. /**
  3691. * Sets the vector components to the same value.
  3692. *
  3693. * @param {number} scalar - The value to set for all vector components.
  3694. * @return {Vector3} A reference to this vector.
  3695. */
  3696. setScalar( scalar ) {
  3697. this.x = scalar;
  3698. this.y = scalar;
  3699. this.z = scalar;
  3700. return this;
  3701. }
  3702. /**
  3703. * Sets the vector's x component to the given value
  3704. *
  3705. * @param {number} x - The value to set.
  3706. * @return {Vector3} A reference to this vector.
  3707. */
  3708. setX( x ) {
  3709. this.x = x;
  3710. return this;
  3711. }
  3712. /**
  3713. * Sets the vector's y component to the given value
  3714. *
  3715. * @param {number} y - The value to set.
  3716. * @return {Vector3} A reference to this vector.
  3717. */
  3718. setY( y ) {
  3719. this.y = y;
  3720. return this;
  3721. }
  3722. /**
  3723. * Sets the vector's z component to the given value
  3724. *
  3725. * @param {number} z - The value to set.
  3726. * @return {Vector3} A reference to this vector.
  3727. */
  3728. setZ( z ) {
  3729. this.z = z;
  3730. return this;
  3731. }
  3732. /**
  3733. * Allows to set a vector component with an index.
  3734. *
  3735. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3736. * @param {number} value - The value to set.
  3737. * @return {Vector3} A reference to this vector.
  3738. */
  3739. setComponent( index, value ) {
  3740. switch ( index ) {
  3741. case 0: this.x = value; break;
  3742. case 1: this.y = value; break;
  3743. case 2: this.z = value; break;
  3744. default: throw new Error( 'index is out of range: ' + index );
  3745. }
  3746. return this;
  3747. }
  3748. /**
  3749. * Returns the value of the vector component which matches the given index.
  3750. *
  3751. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3752. * @return {number} A vector component value.
  3753. */
  3754. getComponent( index ) {
  3755. switch ( index ) {
  3756. case 0: return this.x;
  3757. case 1: return this.y;
  3758. case 2: return this.z;
  3759. default: throw new Error( 'index is out of range: ' + index );
  3760. }
  3761. }
  3762. /**
  3763. * Returns a new vector with copied values from this instance.
  3764. *
  3765. * @return {Vector3} A clone of this instance.
  3766. */
  3767. clone() {
  3768. return new this.constructor( this.x, this.y, this.z );
  3769. }
  3770. /**
  3771. * Copies the values of the given vector to this instance.
  3772. *
  3773. * @param {Vector3} v - The vector to copy.
  3774. * @return {Vector3} A reference to this vector.
  3775. */
  3776. copy( v ) {
  3777. this.x = v.x;
  3778. this.y = v.y;
  3779. this.z = v.z;
  3780. return this;
  3781. }
  3782. /**
  3783. * Adds the given vector to this instance.
  3784. *
  3785. * @param {Vector3} v - The vector to add.
  3786. * @return {Vector3} A reference to this vector.
  3787. */
  3788. add( v ) {
  3789. this.x += v.x;
  3790. this.y += v.y;
  3791. this.z += v.z;
  3792. return this;
  3793. }
  3794. /**
  3795. * Adds the given scalar value to all components of this instance.
  3796. *
  3797. * @param {number} s - The scalar to add.
  3798. * @return {Vector3} A reference to this vector.
  3799. */
  3800. addScalar( s ) {
  3801. this.x += s;
  3802. this.y += s;
  3803. this.z += s;
  3804. return this;
  3805. }
  3806. /**
  3807. * Adds the given vectors and stores the result in this instance.
  3808. *
  3809. * @param {Vector3} a - The first vector.
  3810. * @param {Vector3} b - The second vector.
  3811. * @return {Vector3} A reference to this vector.
  3812. */
  3813. addVectors( a, b ) {
  3814. this.x = a.x + b.x;
  3815. this.y = a.y + b.y;
  3816. this.z = a.z + b.z;
  3817. return this;
  3818. }
  3819. /**
  3820. * Adds the given vector scaled by the given factor to this instance.
  3821. *
  3822. * @param {Vector3|Vector4} v - The vector.
  3823. * @param {number} s - The factor that scales `v`.
  3824. * @return {Vector3} A reference to this vector.
  3825. */
  3826. addScaledVector( v, s ) {
  3827. this.x += v.x * s;
  3828. this.y += v.y * s;
  3829. this.z += v.z * s;
  3830. return this;
  3831. }
  3832. /**
  3833. * Subtracts the given vector from this instance.
  3834. *
  3835. * @param {Vector3} v - The vector to subtract.
  3836. * @return {Vector3} A reference to this vector.
  3837. */
  3838. sub( v ) {
  3839. this.x -= v.x;
  3840. this.y -= v.y;
  3841. this.z -= v.z;
  3842. return this;
  3843. }
  3844. /**
  3845. * Subtracts the given scalar value from all components of this instance.
  3846. *
  3847. * @param {number} s - The scalar to subtract.
  3848. * @return {Vector3} A reference to this vector.
  3849. */
  3850. subScalar( s ) {
  3851. this.x -= s;
  3852. this.y -= s;
  3853. this.z -= s;
  3854. return this;
  3855. }
  3856. /**
  3857. * Subtracts the given vectors and stores the result in this instance.
  3858. *
  3859. * @param {Vector3} a - The first vector.
  3860. * @param {Vector3} b - The second vector.
  3861. * @return {Vector3} A reference to this vector.
  3862. */
  3863. subVectors( a, b ) {
  3864. this.x = a.x - b.x;
  3865. this.y = a.y - b.y;
  3866. this.z = a.z - b.z;
  3867. return this;
  3868. }
  3869. /**
  3870. * Multiplies the given vector with this instance.
  3871. *
  3872. * @param {Vector3} v - The vector to multiply.
  3873. * @return {Vector3} A reference to this vector.
  3874. */
  3875. multiply( v ) {
  3876. this.x *= v.x;
  3877. this.y *= v.y;
  3878. this.z *= v.z;
  3879. return this;
  3880. }
  3881. /**
  3882. * Multiplies the given scalar value with all components of this instance.
  3883. *
  3884. * @param {number} scalar - The scalar to multiply.
  3885. * @return {Vector3} A reference to this vector.
  3886. */
  3887. multiplyScalar( scalar ) {
  3888. this.x *= scalar;
  3889. this.y *= scalar;
  3890. this.z *= scalar;
  3891. return this;
  3892. }
  3893. /**
  3894. * Multiplies the given vectors and stores the result in this instance.
  3895. *
  3896. * @param {Vector3} a - The first vector.
  3897. * @param {Vector3} b - The second vector.
  3898. * @return {Vector3} A reference to this vector.
  3899. */
  3900. multiplyVectors( a, b ) {
  3901. this.x = a.x * b.x;
  3902. this.y = a.y * b.y;
  3903. this.z = a.z * b.z;
  3904. return this;
  3905. }
  3906. /**
  3907. * Applies the given Euler rotation to this vector.
  3908. *
  3909. * @param {Euler} euler - The Euler angles.
  3910. * @return {Vector3} A reference to this vector.
  3911. */
  3912. applyEuler( euler ) {
  3913. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3914. }
  3915. /**
  3916. * Applies a rotation specified by an axis and an angle to this vector.
  3917. *
  3918. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3919. * @param {number} angle - The angle in radians.
  3920. * @return {Vector3} A reference to this vector.
  3921. */
  3922. applyAxisAngle( axis, angle ) {
  3923. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3924. }
  3925. /**
  3926. * Multiplies this vector with the given 3x3 matrix.
  3927. *
  3928. * @param {Matrix3} m - The 3x3 matrix.
  3929. * @return {Vector3} A reference to this vector.
  3930. */
  3931. applyMatrix3( m ) {
  3932. const x = this.x, y = this.y, z = this.z;
  3933. const e = m.elements;
  3934. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3935. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3936. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3937. return this;
  3938. }
  3939. /**
  3940. * Multiplies this vector by the given normal matrix and normalizes
  3941. * the result.
  3942. *
  3943. * @param {Matrix3} m - The normal matrix.
  3944. * @return {Vector3} A reference to this vector.
  3945. */
  3946. applyNormalMatrix( m ) {
  3947. return this.applyMatrix3( m ).normalize();
  3948. }
  3949. /**
  3950. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3951. * divides by perspective.
  3952. *
  3953. * @param {Matrix4} m - The matrix to apply.
  3954. * @return {Vector3} A reference to this vector.
  3955. */
  3956. applyMatrix4( m ) {
  3957. const x = this.x, y = this.y, z = this.z;
  3958. const e = m.elements;
  3959. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3960. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3961. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3962. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3963. return this;
  3964. }
  3965. /**
  3966. * Applies the given Quaternion to this vector.
  3967. *
  3968. * @param {Quaternion} q - The Quaternion.
  3969. * @return {Vector3} A reference to this vector.
  3970. */
  3971. applyQuaternion( q ) {
  3972. // quaternion q is assumed to have unit length
  3973. const vx = this.x, vy = this.y, vz = this.z;
  3974. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3975. // t = 2 * cross( q.xyz, v );
  3976. const tx = 2 * ( qy * vz - qz * vy );
  3977. const ty = 2 * ( qz * vx - qx * vz );
  3978. const tz = 2 * ( qx * vy - qy * vx );
  3979. // v + q.w * t + cross( q.xyz, t );
  3980. this.x = vx + qw * tx + qy * tz - qz * ty;
  3981. this.y = vy + qw * ty + qz * tx - qx * tz;
  3982. this.z = vz + qw * tz + qx * ty - qy * tx;
  3983. return this;
  3984. }
  3985. /**
  3986. * Projects this vector from world space into the camera's normalized
  3987. * device coordinate (NDC) space.
  3988. *
  3989. * @param {Camera} camera - The camera.
  3990. * @return {Vector3} A reference to this vector.
  3991. */
  3992. project( camera ) {
  3993. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3994. }
  3995. /**
  3996. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3997. * space into world space.
  3998. *
  3999. * @param {Camera} camera - The camera.
  4000. * @return {Vector3} A reference to this vector.
  4001. */
  4002. unproject( camera ) {
  4003. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4004. }
  4005. /**
  4006. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4007. * subset of the given 4x4 matrix and then normalizes the result.
  4008. *
  4009. * @param {Matrix4} m - The matrix.
  4010. * @return {Vector3} A reference to this vector.
  4011. */
  4012. transformDirection( m ) {
  4013. // input: THREE.Matrix4 affine matrix
  4014. // vector interpreted as a direction
  4015. const x = this.x, y = this.y, z = this.z;
  4016. const e = m.elements;
  4017. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4018. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4019. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4020. return this.normalize();
  4021. }
  4022. /**
  4023. * Divides this instance by the given vector.
  4024. *
  4025. * @param {Vector3} v - The vector to divide.
  4026. * @return {Vector3} A reference to this vector.
  4027. */
  4028. divide( v ) {
  4029. this.x /= v.x;
  4030. this.y /= v.y;
  4031. this.z /= v.z;
  4032. return this;
  4033. }
  4034. /**
  4035. * Divides this vector by the given scalar.
  4036. *
  4037. * @param {number} scalar - The scalar to divide.
  4038. * @return {Vector3} A reference to this vector.
  4039. */
  4040. divideScalar( scalar ) {
  4041. return this.multiplyScalar( 1 / scalar );
  4042. }
  4043. /**
  4044. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4045. * value, replace that value with the corresponding min value.
  4046. *
  4047. * @param {Vector3} v - The vector.
  4048. * @return {Vector3} A reference to this vector.
  4049. */
  4050. min( v ) {
  4051. this.x = Math.min( this.x, v.x );
  4052. this.y = Math.min( this.y, v.y );
  4053. this.z = Math.min( this.z, v.z );
  4054. return this;
  4055. }
  4056. /**
  4057. * If this vector's x, y or z value is less than the given vector's x, y or z
  4058. * value, replace that value with the corresponding max value.
  4059. *
  4060. * @param {Vector3} v - The vector.
  4061. * @return {Vector3} A reference to this vector.
  4062. */
  4063. max( v ) {
  4064. this.x = Math.max( this.x, v.x );
  4065. this.y = Math.max( this.y, v.y );
  4066. this.z = Math.max( this.z, v.z );
  4067. return this;
  4068. }
  4069. /**
  4070. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4071. * value, it is replaced by the corresponding value.
  4072. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4073. * it is replaced by the corresponding value.
  4074. *
  4075. * @param {Vector3} min - The minimum x, y and z values.
  4076. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4077. * @return {Vector3} A reference to this vector.
  4078. */
  4079. clamp( min, max ) {
  4080. // assumes min < max, componentwise
  4081. this.x = clamp( this.x, min.x, max.x );
  4082. this.y = clamp( this.y, min.y, max.y );
  4083. this.z = clamp( this.z, min.z, max.z );
  4084. return this;
  4085. }
  4086. /**
  4087. * If this vector's x, y or z values are greater than the max value, they are
  4088. * replaced by the max value.
  4089. * If this vector's x, y or z values are less than the min value, they are
  4090. * replaced by the min value.
  4091. *
  4092. * @param {number} minVal - The minimum value the components will be clamped to.
  4093. * @param {number} maxVal - The maximum value the components will be clamped to.
  4094. * @return {Vector3} A reference to this vector.
  4095. */
  4096. clampScalar( minVal, maxVal ) {
  4097. this.x = clamp( this.x, minVal, maxVal );
  4098. this.y = clamp( this.y, minVal, maxVal );
  4099. this.z = clamp( this.z, minVal, maxVal );
  4100. return this;
  4101. }
  4102. /**
  4103. * If this vector's length is greater than the max value, it is replaced by
  4104. * the max value.
  4105. * If this vector's length is less than the min value, it is replaced by the
  4106. * min value.
  4107. *
  4108. * @param {number} min - The minimum value the vector length will be clamped to.
  4109. * @param {number} max - The maximum value the vector length will be clamped to.
  4110. * @return {Vector3} A reference to this vector.
  4111. */
  4112. clampLength( min, max ) {
  4113. const length = this.length();
  4114. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4115. }
  4116. /**
  4117. * The components of this vector are rounded down to the nearest integer value.
  4118. *
  4119. * @return {Vector3} A reference to this vector.
  4120. */
  4121. floor() {
  4122. this.x = Math.floor( this.x );
  4123. this.y = Math.floor( this.y );
  4124. this.z = Math.floor( this.z );
  4125. return this;
  4126. }
  4127. /**
  4128. * The components of this vector are rounded up to the nearest integer value.
  4129. *
  4130. * @return {Vector3} A reference to this vector.
  4131. */
  4132. ceil() {
  4133. this.x = Math.ceil( this.x );
  4134. this.y = Math.ceil( this.y );
  4135. this.z = Math.ceil( this.z );
  4136. return this;
  4137. }
  4138. /**
  4139. * The components of this vector are rounded to the nearest integer value
  4140. *
  4141. * @return {Vector3} A reference to this vector.
  4142. */
  4143. round() {
  4144. this.x = Math.round( this.x );
  4145. this.y = Math.round( this.y );
  4146. this.z = Math.round( this.z );
  4147. return this;
  4148. }
  4149. /**
  4150. * The components of this vector are rounded towards zero (up if negative,
  4151. * down if positive) to an integer value.
  4152. *
  4153. * @return {Vector3} A reference to this vector.
  4154. */
  4155. roundToZero() {
  4156. this.x = Math.trunc( this.x );
  4157. this.y = Math.trunc( this.y );
  4158. this.z = Math.trunc( this.z );
  4159. return this;
  4160. }
  4161. /**
  4162. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4163. *
  4164. * @return {Vector3} A reference to this vector.
  4165. */
  4166. negate() {
  4167. this.x = - this.x;
  4168. this.y = - this.y;
  4169. this.z = - this.z;
  4170. return this;
  4171. }
  4172. /**
  4173. * Calculates the dot product of the given vector with this instance.
  4174. *
  4175. * @param {Vector3} v - The vector to compute the dot product with.
  4176. * @return {number} The result of the dot product.
  4177. */
  4178. dot( v ) {
  4179. return this.x * v.x + this.y * v.y + this.z * v.z;
  4180. }
  4181. /**
  4182. * Computes the square of the Euclidean length (straight-line length) from
  4183. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4184. * compare the length squared instead as it is slightly more efficient to calculate.
  4185. *
  4186. * @return {number} The square length of this vector.
  4187. */
  4188. lengthSq() {
  4189. return this.x * this.x + this.y * this.y + this.z * this.z;
  4190. }
  4191. /**
  4192. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4193. *
  4194. * @return {number} The length of this vector.
  4195. */
  4196. length() {
  4197. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4198. }
  4199. /**
  4200. * Computes the Manhattan length of this vector.
  4201. *
  4202. * @return {number} The length of this vector.
  4203. */
  4204. manhattanLength() {
  4205. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4206. }
  4207. /**
  4208. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4209. * with the same direction as this one, but with a vector length of `1`.
  4210. *
  4211. * @return {Vector3} A reference to this vector.
  4212. */
  4213. normalize() {
  4214. return this.divideScalar( this.length() || 1 );
  4215. }
  4216. /**
  4217. * Sets this vector to a vector with the same direction as this one, but
  4218. * with the specified length.
  4219. *
  4220. * @param {number} length - The new length of this vector.
  4221. * @return {Vector3} A reference to this vector.
  4222. */
  4223. setLength( length ) {
  4224. return this.normalize().multiplyScalar( length );
  4225. }
  4226. /**
  4227. * Linearly interpolates between the given vector and this instance, where
  4228. * alpha is the percent distance along the line - alpha = 0 will be this
  4229. * vector, and alpha = 1 will be the given one.
  4230. *
  4231. * @param {Vector3} v - The vector to interpolate towards.
  4232. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4233. * @return {Vector3} A reference to this vector.
  4234. */
  4235. lerp( v, alpha ) {
  4236. this.x += ( v.x - this.x ) * alpha;
  4237. this.y += ( v.y - this.y ) * alpha;
  4238. this.z += ( v.z - this.z ) * alpha;
  4239. return this;
  4240. }
  4241. /**
  4242. * Linearly interpolates between the given vectors, where alpha is the percent
  4243. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4244. * be the second one. The result is stored in this instance.
  4245. *
  4246. * @param {Vector3} v1 - The first vector.
  4247. * @param {Vector3} v2 - The second vector.
  4248. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4249. * @return {Vector3} A reference to this vector.
  4250. */
  4251. lerpVectors( v1, v2, alpha ) {
  4252. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4253. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4254. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4255. return this;
  4256. }
  4257. /**
  4258. * Calculates the cross product of the given vector with this instance.
  4259. *
  4260. * @param {Vector3} v - The vector to compute the cross product with.
  4261. * @return {Vector3} The result of the cross product.
  4262. */
  4263. cross( v ) {
  4264. return this.crossVectors( this, v );
  4265. }
  4266. /**
  4267. * Calculates the cross product of the given vectors and stores the result
  4268. * in this instance.
  4269. *
  4270. * @param {Vector3} a - The first vector.
  4271. * @param {Vector3} b - The second vector.
  4272. * @return {Vector3} A reference to this vector.
  4273. */
  4274. crossVectors( a, b ) {
  4275. const ax = a.x, ay = a.y, az = a.z;
  4276. const bx = b.x, by = b.y, bz = b.z;
  4277. this.x = ay * bz - az * by;
  4278. this.y = az * bx - ax * bz;
  4279. this.z = ax * by - ay * bx;
  4280. return this;
  4281. }
  4282. /**
  4283. * Projects this vector onto the given one.
  4284. *
  4285. * @param {Vector3} v - The vector to project to.
  4286. * @return {Vector3} A reference to this vector.
  4287. */
  4288. projectOnVector( v ) {
  4289. const denominator = v.lengthSq();
  4290. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4291. const scalar = v.dot( this ) / denominator;
  4292. return this.copy( v ).multiplyScalar( scalar );
  4293. }
  4294. /**
  4295. * Projects this vector onto a plane by subtracting this
  4296. * vector projected onto the plane's normal from this vector.
  4297. *
  4298. * @param {Vector3} planeNormal - The plane normal.
  4299. * @return {Vector3} A reference to this vector.
  4300. */
  4301. projectOnPlane( planeNormal ) {
  4302. _vector$c.copy( this ).projectOnVector( planeNormal );
  4303. return this.sub( _vector$c );
  4304. }
  4305. /**
  4306. * Reflects this vector off a plane orthogonal to the given normal vector.
  4307. *
  4308. * @param {Vector3} normal - The (normalized) normal vector.
  4309. * @return {Vector3} A reference to this vector.
  4310. */
  4311. reflect( normal ) {
  4312. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4313. }
  4314. /**
  4315. * Returns the angle between the given vector and this instance in radians.
  4316. *
  4317. * @param {Vector3} v - The vector to compute the angle with.
  4318. * @return {number} The angle in radians.
  4319. */
  4320. angleTo( v ) {
  4321. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4322. if ( denominator === 0 ) return Math.PI / 2;
  4323. const theta = this.dot( v ) / denominator;
  4324. // clamp, to handle numerical problems
  4325. return Math.acos( clamp( theta, -1, 1 ) );
  4326. }
  4327. /**
  4328. * Computes the distance from the given vector to this instance.
  4329. *
  4330. * @param {Vector3} v - The vector to compute the distance to.
  4331. * @return {number} The distance.
  4332. */
  4333. distanceTo( v ) {
  4334. return Math.sqrt( this.distanceToSquared( v ) );
  4335. }
  4336. /**
  4337. * Computes the squared distance from the given vector to this instance.
  4338. * If you are just comparing the distance with another distance, you should compare
  4339. * the distance squared instead as it is slightly more efficient to calculate.
  4340. *
  4341. * @param {Vector3} v - The vector to compute the squared distance to.
  4342. * @return {number} The squared distance.
  4343. */
  4344. distanceToSquared( v ) {
  4345. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4346. return dx * dx + dy * dy + dz * dz;
  4347. }
  4348. /**
  4349. * Computes the Manhattan distance from the given vector to this instance.
  4350. *
  4351. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4352. * @return {number} The Manhattan distance.
  4353. */
  4354. manhattanDistanceTo( v ) {
  4355. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4356. }
  4357. /**
  4358. * Sets the vector components from the given spherical coordinates.
  4359. *
  4360. * @param {Spherical} s - The spherical coordinates.
  4361. * @return {Vector3} A reference to this vector.
  4362. */
  4363. setFromSpherical( s ) {
  4364. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4365. }
  4366. /**
  4367. * Sets the vector components from the given spherical coordinates.
  4368. *
  4369. * @param {number} radius - The radius.
  4370. * @param {number} phi - The phi angle in radians.
  4371. * @param {number} theta - The theta angle in radians.
  4372. * @return {Vector3} A reference to this vector.
  4373. */
  4374. setFromSphericalCoords( radius, phi, theta ) {
  4375. const sinPhiRadius = Math.sin( phi ) * radius;
  4376. this.x = sinPhiRadius * Math.sin( theta );
  4377. this.y = Math.cos( phi ) * radius;
  4378. this.z = sinPhiRadius * Math.cos( theta );
  4379. return this;
  4380. }
  4381. /**
  4382. * Sets the vector components from the given cylindrical coordinates.
  4383. *
  4384. * @param {Cylindrical} c - The cylindrical coordinates.
  4385. * @return {Vector3} A reference to this vector.
  4386. */
  4387. setFromCylindrical( c ) {
  4388. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4389. }
  4390. /**
  4391. * Sets the vector components from the given cylindrical coordinates.
  4392. *
  4393. * @param {number} radius - The radius.
  4394. * @param {number} theta - The theta angle in radians.
  4395. * @param {number} y - The y value.
  4396. * @return {Vector3} A reference to this vector.
  4397. */
  4398. setFromCylindricalCoords( radius, theta, y ) {
  4399. this.x = radius * Math.sin( theta );
  4400. this.y = y;
  4401. this.z = radius * Math.cos( theta );
  4402. return this;
  4403. }
  4404. /**
  4405. * Sets the vector components to the position elements of the
  4406. * given transformation matrix.
  4407. *
  4408. * @param {Matrix4} m - The 4x4 matrix.
  4409. * @return {Vector3} A reference to this vector.
  4410. */
  4411. setFromMatrixPosition( m ) {
  4412. const e = m.elements;
  4413. this.x = e[ 12 ];
  4414. this.y = e[ 13 ];
  4415. this.z = e[ 14 ];
  4416. return this;
  4417. }
  4418. /**
  4419. * Sets the vector components to the scale elements of the
  4420. * given transformation matrix.
  4421. *
  4422. * @param {Matrix4} m - The 4x4 matrix.
  4423. * @return {Vector3} A reference to this vector.
  4424. */
  4425. setFromMatrixScale( m ) {
  4426. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4427. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4428. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4429. this.x = sx;
  4430. this.y = sy;
  4431. this.z = sz;
  4432. return this;
  4433. }
  4434. /**
  4435. * Sets the vector components from the specified matrix column.
  4436. *
  4437. * @param {Matrix4} m - The 4x4 matrix.
  4438. * @param {number} index - The column index.
  4439. * @return {Vector3} A reference to this vector.
  4440. */
  4441. setFromMatrixColumn( m, index ) {
  4442. return this.fromArray( m.elements, index * 4 );
  4443. }
  4444. /**
  4445. * Sets the vector components from the specified matrix column.
  4446. *
  4447. * @param {Matrix3} m - The 3x3 matrix.
  4448. * @param {number} index - The column index.
  4449. * @return {Vector3} A reference to this vector.
  4450. */
  4451. setFromMatrix3Column( m, index ) {
  4452. return this.fromArray( m.elements, index * 3 );
  4453. }
  4454. /**
  4455. * Sets the vector components from the given Euler angles.
  4456. *
  4457. * @param {Euler} e - The Euler angles to set.
  4458. * @return {Vector3} A reference to this vector.
  4459. */
  4460. setFromEuler( e ) {
  4461. this.x = e._x;
  4462. this.y = e._y;
  4463. this.z = e._z;
  4464. return this;
  4465. }
  4466. /**
  4467. * Sets the vector components from the RGB components of the
  4468. * given color.
  4469. *
  4470. * @param {Color} c - The color to set.
  4471. * @return {Vector3} A reference to this vector.
  4472. */
  4473. setFromColor( c ) {
  4474. this.x = c.r;
  4475. this.y = c.g;
  4476. this.z = c.b;
  4477. return this;
  4478. }
  4479. /**
  4480. * Returns `true` if this vector is equal with the given one.
  4481. *
  4482. * @param {Vector3} v - The vector to test for equality.
  4483. * @return {boolean} Whether this vector is equal with the given one.
  4484. */
  4485. equals( v ) {
  4486. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4487. }
  4488. /**
  4489. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4490. * and z value to be `array[ offset + 2 ]`.
  4491. *
  4492. * @param {Array<number>} array - An array holding the vector component values.
  4493. * @param {number} [offset=0] - The offset into the array.
  4494. * @return {Vector3} A reference to this vector.
  4495. */
  4496. fromArray( array, offset = 0 ) {
  4497. this.x = array[ offset ];
  4498. this.y = array[ offset + 1 ];
  4499. this.z = array[ offset + 2 ];
  4500. return this;
  4501. }
  4502. /**
  4503. * Writes the components of this vector to the given array. If no array is provided,
  4504. * the method returns a new instance.
  4505. *
  4506. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4507. * @param {number} [offset=0] - Index of the first element in the array.
  4508. * @return {Array<number>} The vector components.
  4509. */
  4510. toArray( array = [], offset = 0 ) {
  4511. array[ offset ] = this.x;
  4512. array[ offset + 1 ] = this.y;
  4513. array[ offset + 2 ] = this.z;
  4514. return array;
  4515. }
  4516. /**
  4517. * Sets the components of this vector from the given buffer attribute.
  4518. *
  4519. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4520. * @param {number} index - The index into the attribute.
  4521. * @return {Vector3} A reference to this vector.
  4522. */
  4523. fromBufferAttribute( attribute, index ) {
  4524. this.x = attribute.getX( index );
  4525. this.y = attribute.getY( index );
  4526. this.z = attribute.getZ( index );
  4527. return this;
  4528. }
  4529. /**
  4530. * Sets each component of this vector to a pseudo-random value between `0` and
  4531. * `1`, excluding `1`.
  4532. *
  4533. * @return {Vector3} A reference to this vector.
  4534. */
  4535. random() {
  4536. this.x = Math.random();
  4537. this.y = Math.random();
  4538. this.z = Math.random();
  4539. return this;
  4540. }
  4541. /**
  4542. * Sets this vector to a uniformly random point on a unit sphere.
  4543. *
  4544. * @return {Vector3} A reference to this vector.
  4545. */
  4546. randomDirection() {
  4547. // https://mathworld.wolfram.com/SpherePointPicking.html
  4548. const theta = Math.random() * Math.PI * 2;
  4549. const u = Math.random() * 2 - 1;
  4550. const c = Math.sqrt( 1 - u * u );
  4551. this.x = c * Math.cos( theta );
  4552. this.y = u;
  4553. this.z = c * Math.sin( theta );
  4554. return this;
  4555. }
  4556. *[ Symbol.iterator ]() {
  4557. yield this.x;
  4558. yield this.y;
  4559. yield this.z;
  4560. }
  4561. }
  4562. const _vector$c = /*@__PURE__*/ new Vector3();
  4563. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4564. /**
  4565. * Represents a 3x3 matrix.
  4566. *
  4567. * A Note on Row-Major and Column-Major Ordering:
  4568. *
  4569. * The constructor and {@link Matrix3#set} method take arguments in
  4570. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4571. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4572. * This means that calling:
  4573. * ```js
  4574. * const m = new THREE.Matrix();
  4575. * m.set( 11, 12, 13,
  4576. * 21, 22, 23,
  4577. * 31, 32, 33 );
  4578. * ```
  4579. * will result in the elements array containing:
  4580. * ```js
  4581. * m.elements = [ 11, 21, 31,
  4582. * 12, 22, 32,
  4583. * 13, 23, 33 ];
  4584. * ```
  4585. * and internally all calculations are performed using column-major ordering.
  4586. * However, as the actual ordering makes no difference mathematically and
  4587. * most people are used to thinking about matrices in row-major order, the
  4588. * three.js documentation shows matrices in row-major order. Just bear in
  4589. * mind that if you are reading the source code, you'll have to take the
  4590. * transpose of any matrices outlined here to make sense of the calculations.
  4591. */
  4592. class Matrix3 {
  4593. /**
  4594. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4595. * in row-major order. If no arguments are provided, the constructor
  4596. * initializes the matrix as an identity matrix.
  4597. *
  4598. * @param {number} [n11] - 1-1 matrix element.
  4599. * @param {number} [n12] - 1-2 matrix element.
  4600. * @param {number} [n13] - 1-3 matrix element.
  4601. * @param {number} [n21] - 2-1 matrix element.
  4602. * @param {number} [n22] - 2-2 matrix element.
  4603. * @param {number} [n23] - 2-3 matrix element.
  4604. * @param {number} [n31] - 3-1 matrix element.
  4605. * @param {number} [n32] - 3-2 matrix element.
  4606. * @param {number} [n33] - 3-3 matrix element.
  4607. */
  4608. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4609. /**
  4610. * This flag can be used for type testing.
  4611. *
  4612. * @type {boolean}
  4613. * @readonly
  4614. * @default true
  4615. */
  4616. Matrix3.prototype.isMatrix3 = true;
  4617. /**
  4618. * A column-major list of matrix values.
  4619. *
  4620. * @type {Array<number>}
  4621. */
  4622. this.elements = [
  4623. 1, 0, 0,
  4624. 0, 1, 0,
  4625. 0, 0, 1
  4626. ];
  4627. if ( n11 !== undefined ) {
  4628. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4629. }
  4630. }
  4631. /**
  4632. * Sets the elements of the matrix.The arguments are supposed to be
  4633. * in row-major order.
  4634. *
  4635. * @param {number} [n11] - 1-1 matrix element.
  4636. * @param {number} [n12] - 1-2 matrix element.
  4637. * @param {number} [n13] - 1-3 matrix element.
  4638. * @param {number} [n21] - 2-1 matrix element.
  4639. * @param {number} [n22] - 2-2 matrix element.
  4640. * @param {number} [n23] - 2-3 matrix element.
  4641. * @param {number} [n31] - 3-1 matrix element.
  4642. * @param {number} [n32] - 3-2 matrix element.
  4643. * @param {number} [n33] - 3-3 matrix element.
  4644. * @return {Matrix3} A reference to this matrix.
  4645. */
  4646. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4647. const te = this.elements;
  4648. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4649. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4650. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4651. return this;
  4652. }
  4653. /**
  4654. * Sets this matrix to the 3x3 identity matrix.
  4655. *
  4656. * @return {Matrix3} A reference to this matrix.
  4657. */
  4658. identity() {
  4659. this.set(
  4660. 1, 0, 0,
  4661. 0, 1, 0,
  4662. 0, 0, 1
  4663. );
  4664. return this;
  4665. }
  4666. /**
  4667. * Copies the values of the given matrix to this instance.
  4668. *
  4669. * @param {Matrix3} m - The matrix to copy.
  4670. * @return {Matrix3} A reference to this matrix.
  4671. */
  4672. copy( m ) {
  4673. const te = this.elements;
  4674. const me = m.elements;
  4675. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4676. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4677. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4678. return this;
  4679. }
  4680. /**
  4681. * Extracts the basis of this matrix into the three axis vectors provided.
  4682. *
  4683. * @param {Vector3} xAxis - The basis's x axis.
  4684. * @param {Vector3} yAxis - The basis's y axis.
  4685. * @param {Vector3} zAxis - The basis's z axis.
  4686. * @return {Matrix3} A reference to this matrix.
  4687. */
  4688. extractBasis( xAxis, yAxis, zAxis ) {
  4689. xAxis.setFromMatrix3Column( this, 0 );
  4690. yAxis.setFromMatrix3Column( this, 1 );
  4691. zAxis.setFromMatrix3Column( this, 2 );
  4692. return this;
  4693. }
  4694. /**
  4695. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4696. *
  4697. * @param {Matrix4} m - The 4x4 matrix.
  4698. * @return {Matrix3} A reference to this matrix.
  4699. */
  4700. setFromMatrix4( m ) {
  4701. const me = m.elements;
  4702. this.set(
  4703. me[ 0 ], me[ 4 ], me[ 8 ],
  4704. me[ 1 ], me[ 5 ], me[ 9 ],
  4705. me[ 2 ], me[ 6 ], me[ 10 ]
  4706. );
  4707. return this;
  4708. }
  4709. /**
  4710. * Post-multiplies this matrix by the given 3x3 matrix.
  4711. *
  4712. * @param {Matrix3} m - The matrix to multiply with.
  4713. * @return {Matrix3} A reference to this matrix.
  4714. */
  4715. multiply( m ) {
  4716. return this.multiplyMatrices( this, m );
  4717. }
  4718. /**
  4719. * Pre-multiplies this matrix by the given 3x3 matrix.
  4720. *
  4721. * @param {Matrix3} m - The matrix to multiply with.
  4722. * @return {Matrix3} A reference to this matrix.
  4723. */
  4724. premultiply( m ) {
  4725. return this.multiplyMatrices( m, this );
  4726. }
  4727. /**
  4728. * Multiples the given 3x3 matrices and stores the result
  4729. * in this matrix.
  4730. *
  4731. * @param {Matrix3} a - The first matrix.
  4732. * @param {Matrix3} b - The second matrix.
  4733. * @return {Matrix3} A reference to this matrix.
  4734. */
  4735. multiplyMatrices( a, b ) {
  4736. const ae = a.elements;
  4737. const be = b.elements;
  4738. const te = this.elements;
  4739. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4740. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4741. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4742. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4743. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4744. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4745. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4746. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4747. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4748. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4749. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4750. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4751. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4752. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4753. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4754. return this;
  4755. }
  4756. /**
  4757. * Multiplies every component of the matrix by the given scalar.
  4758. *
  4759. * @param {number} s - The scalar.
  4760. * @return {Matrix3} A reference to this matrix.
  4761. */
  4762. multiplyScalar( s ) {
  4763. const te = this.elements;
  4764. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4765. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4766. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4767. return this;
  4768. }
  4769. /**
  4770. * Computes and returns the determinant of this matrix.
  4771. *
  4772. * @return {number} The determinant.
  4773. */
  4774. determinant() {
  4775. const te = this.elements;
  4776. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4777. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4778. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4779. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4780. }
  4781. /**
  4782. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4783. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4784. * a zero matrix instead.
  4785. *
  4786. * @return {Matrix3} A reference to this matrix.
  4787. */
  4788. invert() {
  4789. const te = this.elements,
  4790. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4791. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4792. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4793. t11 = n33 * n22 - n32 * n23,
  4794. t12 = n32 * n13 - n33 * n12,
  4795. t13 = n23 * n12 - n22 * n13,
  4796. det = n11 * t11 + n21 * t12 + n31 * t13;
  4797. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4798. const detInv = 1 / det;
  4799. te[ 0 ] = t11 * detInv;
  4800. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4801. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4802. te[ 3 ] = t12 * detInv;
  4803. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4804. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4805. te[ 6 ] = t13 * detInv;
  4806. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4807. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4808. return this;
  4809. }
  4810. /**
  4811. * Transposes this matrix in place.
  4812. *
  4813. * @return {Matrix3} A reference to this matrix.
  4814. */
  4815. transpose() {
  4816. let tmp;
  4817. const m = this.elements;
  4818. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4819. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4820. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4821. return this;
  4822. }
  4823. /**
  4824. * Computes the normal matrix which is the inverse transpose of the upper
  4825. * left 3x3 portion of the given 4x4 matrix.
  4826. *
  4827. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4828. * @return {Matrix3} A reference to this matrix.
  4829. */
  4830. getNormalMatrix( matrix4 ) {
  4831. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4832. }
  4833. /**
  4834. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4835. *
  4836. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4837. * @return {Matrix3} A reference to this matrix.
  4838. */
  4839. transposeIntoArray( r ) {
  4840. const m = this.elements;
  4841. r[ 0 ] = m[ 0 ];
  4842. r[ 1 ] = m[ 3 ];
  4843. r[ 2 ] = m[ 6 ];
  4844. r[ 3 ] = m[ 1 ];
  4845. r[ 4 ] = m[ 4 ];
  4846. r[ 5 ] = m[ 7 ];
  4847. r[ 6 ] = m[ 2 ];
  4848. r[ 7 ] = m[ 5 ];
  4849. r[ 8 ] = m[ 8 ];
  4850. return this;
  4851. }
  4852. /**
  4853. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4854. *
  4855. * @param {number} tx - Offset x.
  4856. * @param {number} ty - Offset y.
  4857. * @param {number} sx - Repeat x.
  4858. * @param {number} sy - Repeat y.
  4859. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4860. * @param {number} cx - Center x of rotation.
  4861. * @param {number} cy - Center y of rotation
  4862. * @return {Matrix3} A reference to this matrix.
  4863. */
  4864. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4865. const c = Math.cos( rotation );
  4866. const s = Math.sin( rotation );
  4867. this.set(
  4868. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4869. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4870. 0, 0, 1
  4871. );
  4872. return this;
  4873. }
  4874. /**
  4875. * Scales this matrix with the given scalar values.
  4876. *
  4877. * @param {number} sx - The amount to scale in the X axis.
  4878. * @param {number} sy - The amount to scale in the Y axis.
  4879. * @return {Matrix3} A reference to this matrix.
  4880. */
  4881. scale( sx, sy ) {
  4882. this.premultiply( _m3.makeScale( sx, sy ) );
  4883. return this;
  4884. }
  4885. /**
  4886. * Rotates this matrix by the given angle.
  4887. *
  4888. * @param {number} theta - The rotation in radians.
  4889. * @return {Matrix3} A reference to this matrix.
  4890. */
  4891. rotate( theta ) {
  4892. this.premultiply( _m3.makeRotation( - theta ) );
  4893. return this;
  4894. }
  4895. /**
  4896. * Translates this matrix by the given scalar values.
  4897. *
  4898. * @param {number} tx - The amount to translate in the X axis.
  4899. * @param {number} ty - The amount to translate in the Y axis.
  4900. * @return {Matrix3} A reference to this matrix.
  4901. */
  4902. translate( tx, ty ) {
  4903. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4904. return this;
  4905. }
  4906. // for 2D Transforms
  4907. /**
  4908. * Sets this matrix as a 2D translation transform.
  4909. *
  4910. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4911. * @param {number} y - The amount to translate in the Y axis.
  4912. * @return {Matrix3} A reference to this matrix.
  4913. */
  4914. makeTranslation( x, y ) {
  4915. if ( x.isVector2 ) {
  4916. this.set(
  4917. 1, 0, x.x,
  4918. 0, 1, x.y,
  4919. 0, 0, 1
  4920. );
  4921. } else {
  4922. this.set(
  4923. 1, 0, x,
  4924. 0, 1, y,
  4925. 0, 0, 1
  4926. );
  4927. }
  4928. return this;
  4929. }
  4930. /**
  4931. * Sets this matrix as a 2D rotational transformation.
  4932. *
  4933. * @param {number} theta - The rotation in radians.
  4934. * @return {Matrix3} A reference to this matrix.
  4935. */
  4936. makeRotation( theta ) {
  4937. // counterclockwise
  4938. const c = Math.cos( theta );
  4939. const s = Math.sin( theta );
  4940. this.set(
  4941. c, - s, 0,
  4942. s, c, 0,
  4943. 0, 0, 1
  4944. );
  4945. return this;
  4946. }
  4947. /**
  4948. * Sets this matrix as a 2D scale transform.
  4949. *
  4950. * @param {number} x - The amount to scale in the X axis.
  4951. * @param {number} y - The amount to scale in the Y axis.
  4952. * @return {Matrix3} A reference to this matrix.
  4953. */
  4954. makeScale( x, y ) {
  4955. this.set(
  4956. x, 0, 0,
  4957. 0, y, 0,
  4958. 0, 0, 1
  4959. );
  4960. return this;
  4961. }
  4962. /**
  4963. * Returns `true` if this matrix is equal with the given one.
  4964. *
  4965. * @param {Matrix3} matrix - The matrix to test for equality.
  4966. * @return {boolean} Whether this matrix is equal with the given one.
  4967. */
  4968. equals( matrix ) {
  4969. const te = this.elements;
  4970. const me = matrix.elements;
  4971. for ( let i = 0; i < 9; i ++ ) {
  4972. if ( te[ i ] !== me[ i ] ) return false;
  4973. }
  4974. return true;
  4975. }
  4976. /**
  4977. * Sets the elements of the matrix from the given array.
  4978. *
  4979. * @param {Array<number>} array - The matrix elements in column-major order.
  4980. * @param {number} [offset=0] - Index of the first element in the array.
  4981. * @return {Matrix3} A reference to this matrix.
  4982. */
  4983. fromArray( array, offset = 0 ) {
  4984. for ( let i = 0; i < 9; i ++ ) {
  4985. this.elements[ i ] = array[ i + offset ];
  4986. }
  4987. return this;
  4988. }
  4989. /**
  4990. * Writes the elements of this matrix to the given array. If no array is provided,
  4991. * the method returns a new instance.
  4992. *
  4993. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4994. * @param {number} [offset=0] - Index of the first element in the array.
  4995. * @return {Array<number>} The matrix elements in column-major order.
  4996. */
  4997. toArray( array = [], offset = 0 ) {
  4998. const te = this.elements;
  4999. array[ offset ] = te[ 0 ];
  5000. array[ offset + 1 ] = te[ 1 ];
  5001. array[ offset + 2 ] = te[ 2 ];
  5002. array[ offset + 3 ] = te[ 3 ];
  5003. array[ offset + 4 ] = te[ 4 ];
  5004. array[ offset + 5 ] = te[ 5 ];
  5005. array[ offset + 6 ] = te[ 6 ];
  5006. array[ offset + 7 ] = te[ 7 ];
  5007. array[ offset + 8 ] = te[ 8 ];
  5008. return array;
  5009. }
  5010. /**
  5011. * Returns a matrix with copied values from this instance.
  5012. *
  5013. * @return {Matrix3} A clone of this instance.
  5014. */
  5015. clone() {
  5016. return new this.constructor().fromArray( this.elements );
  5017. }
  5018. }
  5019. const _m3 = /*@__PURE__*/ new Matrix3();
  5020. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5021. 0.4123908, 0.3575843, 0.1804808,
  5022. 0.2126390, 0.7151687, 0.0721923,
  5023. 0.0193308, 0.1191948, 0.9505322
  5024. );
  5025. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5026. 3.2409699, -1.5373832, -0.4986108,
  5027. -0.9692436, 1.8759675, 0.0415551,
  5028. 0.0556301, -0.203977, 1.0569715
  5029. );
  5030. function createColorManagement() {
  5031. const ColorManagement = {
  5032. enabled: true,
  5033. workingColorSpace: LinearSRGBColorSpace,
  5034. /**
  5035. * Implementations of supported color spaces.
  5036. *
  5037. * Required:
  5038. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5039. * - whitePoint: reference white [ x y ]
  5040. * - transfer: transfer function (pre-defined)
  5041. * - toXYZ: Matrix3 RGB to XYZ transform
  5042. * - fromXYZ: Matrix3 XYZ to RGB transform
  5043. * - luminanceCoefficients: RGB luminance coefficients
  5044. *
  5045. * Optional:
  5046. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5047. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5048. *
  5049. * Reference:
  5050. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5051. */
  5052. spaces: {},
  5053. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5054. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5055. return color;
  5056. }
  5057. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5058. color.r = SRGBToLinear( color.r );
  5059. color.g = SRGBToLinear( color.g );
  5060. color.b = SRGBToLinear( color.b );
  5061. }
  5062. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5063. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5064. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5065. }
  5066. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5067. color.r = LinearToSRGB( color.r );
  5068. color.g = LinearToSRGB( color.g );
  5069. color.b = LinearToSRGB( color.b );
  5070. }
  5071. return color;
  5072. },
  5073. workingToColorSpace: function ( color, targetColorSpace ) {
  5074. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5075. },
  5076. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5077. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5078. },
  5079. getPrimaries: function ( colorSpace ) {
  5080. return this.spaces[ colorSpace ].primaries;
  5081. },
  5082. getTransfer: function ( colorSpace ) {
  5083. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5084. return this.spaces[ colorSpace ].transfer;
  5085. },
  5086. getToneMappingMode: function ( colorSpace ) {
  5087. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5088. },
  5089. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5090. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5091. },
  5092. define: function ( colorSpaces ) {
  5093. Object.assign( this.spaces, colorSpaces );
  5094. },
  5095. // Internal APIs
  5096. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5097. return targetMatrix
  5098. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5099. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5100. },
  5101. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5102. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5103. },
  5104. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5105. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5106. },
  5107. // Deprecated
  5108. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5109. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5110. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5111. },
  5112. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5113. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5114. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5115. },
  5116. };
  5117. /******************************************************************************
  5118. * sRGB definitions
  5119. */
  5120. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5121. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5122. const D65 = [ 0.3127, 0.3290 ];
  5123. ColorManagement.define( {
  5124. [ LinearSRGBColorSpace ]: {
  5125. primaries: REC709_PRIMARIES,
  5126. whitePoint: D65,
  5127. transfer: LinearTransfer,
  5128. toXYZ: LINEAR_REC709_TO_XYZ,
  5129. fromXYZ: XYZ_TO_LINEAR_REC709,
  5130. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5131. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5132. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5133. },
  5134. [ SRGBColorSpace ]: {
  5135. primaries: REC709_PRIMARIES,
  5136. whitePoint: D65,
  5137. transfer: SRGBTransfer,
  5138. toXYZ: LINEAR_REC709_TO_XYZ,
  5139. fromXYZ: XYZ_TO_LINEAR_REC709,
  5140. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5141. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5142. },
  5143. } );
  5144. return ColorManagement;
  5145. }
  5146. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5147. function SRGBToLinear( c ) {
  5148. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5149. }
  5150. function LinearToSRGB( c ) {
  5151. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5152. }
  5153. let _canvas;
  5154. /**
  5155. * A class containing utility functions for images.
  5156. *
  5157. * @hideconstructor
  5158. */
  5159. class ImageUtils {
  5160. /**
  5161. * Returns a data URI containing a representation of the given image.
  5162. *
  5163. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5164. * @param {string} [type='image/png'] - Indicates the image format.
  5165. * @return {string} The data URI.
  5166. */
  5167. static getDataURL( image, type = 'image/png' ) {
  5168. if ( /^data:/i.test( image.src ) ) {
  5169. return image.src;
  5170. }
  5171. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5172. return image.src;
  5173. }
  5174. let canvas;
  5175. if ( image instanceof HTMLCanvasElement ) {
  5176. canvas = image;
  5177. } else {
  5178. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5179. _canvas.width = image.width;
  5180. _canvas.height = image.height;
  5181. const context = _canvas.getContext( '2d' );
  5182. if ( image instanceof ImageData ) {
  5183. context.putImageData( image, 0, 0 );
  5184. } else {
  5185. context.drawImage( image, 0, 0, image.width, image.height );
  5186. }
  5187. canvas = _canvas;
  5188. }
  5189. return canvas.toDataURL( type );
  5190. }
  5191. /**
  5192. * Converts the given sRGB image data to linear color space.
  5193. *
  5194. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5195. * @return {HTMLCanvasElement|Object} The converted image.
  5196. */
  5197. static sRGBToLinear( image ) {
  5198. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5199. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5200. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5201. const canvas = createElementNS( 'canvas' );
  5202. canvas.width = image.width;
  5203. canvas.height = image.height;
  5204. const context = canvas.getContext( '2d' );
  5205. context.drawImage( image, 0, 0, image.width, image.height );
  5206. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5207. const data = imageData.data;
  5208. for ( let i = 0; i < data.length; i ++ ) {
  5209. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5210. }
  5211. context.putImageData( imageData, 0, 0 );
  5212. return canvas;
  5213. } else if ( image.data ) {
  5214. const data = image.data.slice( 0 );
  5215. for ( let i = 0; i < data.length; i ++ ) {
  5216. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5217. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5218. } else {
  5219. // assuming float
  5220. data[ i ] = SRGBToLinear( data[ i ] );
  5221. }
  5222. }
  5223. return {
  5224. data: data,
  5225. width: image.width,
  5226. height: image.height
  5227. };
  5228. } else {
  5229. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5230. return image;
  5231. }
  5232. }
  5233. }
  5234. let _sourceId = 0;
  5235. /**
  5236. * Represents the data source of a texture.
  5237. *
  5238. * The main purpose of this class is to decouple the data definition from the texture
  5239. * definition so the same data can be used with multiple texture instances.
  5240. */
  5241. class Source {
  5242. /**
  5243. * Constructs a new video texture.
  5244. *
  5245. * @param {any} [data=null] - The data definition of a texture.
  5246. */
  5247. constructor( data = null ) {
  5248. /**
  5249. * This flag can be used for type testing.
  5250. *
  5251. * @type {boolean}
  5252. * @readonly
  5253. * @default true
  5254. */
  5255. this.isSource = true;
  5256. /**
  5257. * The ID of the source.
  5258. *
  5259. * @name Source#id
  5260. * @type {number}
  5261. * @readonly
  5262. */
  5263. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5264. /**
  5265. * The UUID of the source.
  5266. *
  5267. * @type {string}
  5268. * @readonly
  5269. */
  5270. this.uuid = generateUUID();
  5271. /**
  5272. * The data definition of a texture.
  5273. *
  5274. * @type {any}
  5275. */
  5276. this.data = data;
  5277. /**
  5278. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5279. * provides more control on how texture data should be processed. When `dataReady` is set
  5280. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5281. * the data into the GPU memory.
  5282. *
  5283. * @type {boolean}
  5284. * @default true
  5285. */
  5286. this.dataReady = true;
  5287. /**
  5288. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5289. *
  5290. * @type {number}
  5291. * @readonly
  5292. * @default 0
  5293. */
  5294. this.version = 0;
  5295. }
  5296. /**
  5297. * Returns the dimensions of the source into the given target vector.
  5298. *
  5299. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5300. * @return {(Vector2|Vector3)} The dimensions of the source.
  5301. */
  5302. getSize( target ) {
  5303. const data = this.data;
  5304. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5305. target.set( data.videoWidth, data.videoHeight, 0 );
  5306. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5307. target.set( data.displayHeight, data.displayWidth, 0 );
  5308. } else if ( data !== null ) {
  5309. target.set( data.width, data.height, data.depth || 0 );
  5310. } else {
  5311. target.set( 0, 0, 0 );
  5312. }
  5313. return target;
  5314. }
  5315. /**
  5316. * When the property is set to `true`, the engine allocates the memory
  5317. * for the texture (if necessary) and triggers the actual texture upload
  5318. * to the GPU next time the source is used.
  5319. *
  5320. * @type {boolean}
  5321. * @default false
  5322. * @param {boolean} value
  5323. */
  5324. set needsUpdate( value ) {
  5325. if ( value === true ) this.version ++;
  5326. }
  5327. /**
  5328. * Serializes the source into JSON.
  5329. *
  5330. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5331. * @return {Object} A JSON object representing the serialized source.
  5332. * @see {@link ObjectLoader#parse}
  5333. */
  5334. toJSON( meta ) {
  5335. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5336. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5337. return meta.images[ this.uuid ];
  5338. }
  5339. const output = {
  5340. uuid: this.uuid,
  5341. url: ''
  5342. };
  5343. const data = this.data;
  5344. if ( data !== null ) {
  5345. let url;
  5346. if ( Array.isArray( data ) ) {
  5347. // cube texture
  5348. url = [];
  5349. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5350. if ( data[ i ].isDataTexture ) {
  5351. url.push( serializeImage( data[ i ].image ) );
  5352. } else {
  5353. url.push( serializeImage( data[ i ] ) );
  5354. }
  5355. }
  5356. } else {
  5357. // texture
  5358. url = serializeImage( data );
  5359. }
  5360. output.url = url;
  5361. }
  5362. if ( ! isRootObject ) {
  5363. meta.images[ this.uuid ] = output;
  5364. }
  5365. return output;
  5366. }
  5367. }
  5368. function serializeImage( image ) {
  5369. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5370. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5371. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5372. // default images
  5373. return ImageUtils.getDataURL( image );
  5374. } else {
  5375. if ( image.data ) {
  5376. // images of DataTexture
  5377. return {
  5378. data: Array.from( image.data ),
  5379. width: image.width,
  5380. height: image.height,
  5381. type: image.data.constructor.name
  5382. };
  5383. } else {
  5384. warn( 'Texture: Unable to serialize Texture.' );
  5385. return {};
  5386. }
  5387. }
  5388. }
  5389. let _textureId = 0;
  5390. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5391. /**
  5392. * Base class for all textures.
  5393. *
  5394. * Note: After the initial use of a texture, its dimensions, format, and type
  5395. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5396. *
  5397. * @augments EventDispatcher
  5398. */
  5399. class Texture extends EventDispatcher {
  5400. /**
  5401. * Constructs a new texture.
  5402. *
  5403. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5404. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5405. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5406. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5407. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5408. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5409. * @param {number} [format=RGBAFormat] - The texture format.
  5410. * @param {number} [type=UnsignedByteType] - The texture type.
  5411. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5412. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5413. */
  5414. 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 ) {
  5415. super();
  5416. /**
  5417. * This flag can be used for type testing.
  5418. *
  5419. * @type {boolean}
  5420. * @readonly
  5421. * @default true
  5422. */
  5423. this.isTexture = true;
  5424. /**
  5425. * The ID of the texture.
  5426. *
  5427. * @name Texture#id
  5428. * @type {number}
  5429. * @readonly
  5430. */
  5431. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5432. /**
  5433. * The UUID of the material.
  5434. *
  5435. * @type {string}
  5436. * @readonly
  5437. */
  5438. this.uuid = generateUUID();
  5439. /**
  5440. * The name of the material.
  5441. *
  5442. * @type {string}
  5443. */
  5444. this.name = '';
  5445. /**
  5446. * The data definition of a texture. A reference to the data source can be
  5447. * shared across textures. This is often useful in context of spritesheets
  5448. * where multiple textures render the same data but with different texture
  5449. * transformations.
  5450. *
  5451. * @type {Source}
  5452. */
  5453. this.source = new Source( image );
  5454. /**
  5455. * An array holding user-defined mipmaps.
  5456. *
  5457. * @type {Array<Object>}
  5458. */
  5459. this.mipmaps = [];
  5460. /**
  5461. * How the texture is applied to the object. The value `UVMapping`
  5462. * is the default, where texture or uv coordinates are used to apply the map.
  5463. *
  5464. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5465. * @default UVMapping
  5466. */
  5467. this.mapping = mapping;
  5468. /**
  5469. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5470. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5471. *
  5472. * @type {number}
  5473. * @default 0
  5474. */
  5475. this.channel = 0;
  5476. /**
  5477. * This defines how the texture is wrapped horizontally and corresponds to
  5478. * *U* in UV mapping.
  5479. *
  5480. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5481. * @default ClampToEdgeWrapping
  5482. */
  5483. this.wrapS = wrapS;
  5484. /**
  5485. * This defines how the texture is wrapped horizontally and corresponds to
  5486. * *V* in UV mapping.
  5487. *
  5488. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5489. * @default ClampToEdgeWrapping
  5490. */
  5491. this.wrapT = wrapT;
  5492. /**
  5493. * How the texture is sampled when a texel covers more than one pixel.
  5494. *
  5495. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5496. * @default LinearFilter
  5497. */
  5498. this.magFilter = magFilter;
  5499. /**
  5500. * How the texture is sampled when a texel covers less than one pixel.
  5501. *
  5502. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5503. * @default LinearMipmapLinearFilter
  5504. */
  5505. this.minFilter = minFilter;
  5506. /**
  5507. * The number of samples taken along the axis through the pixel that has the
  5508. * highest density of texels. By default, this value is `1`. A higher value
  5509. * gives a less blurry result than a basic mipmap, at the cost of more
  5510. * texture samples being used.
  5511. *
  5512. * @type {number}
  5513. * @default Texture.DEFAULT_ANISOTROPY
  5514. */
  5515. this.anisotropy = anisotropy;
  5516. /**
  5517. * The format of the texture.
  5518. *
  5519. * @type {number}
  5520. * @default RGBAFormat
  5521. */
  5522. this.format = format;
  5523. /**
  5524. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5525. * defines how the texture data is going to be stored on the GPU.
  5526. *
  5527. * This property allows to overwrite the default format.
  5528. *
  5529. * @type {?string}
  5530. * @default null
  5531. */
  5532. this.internalFormat = null;
  5533. /**
  5534. * The data type of the texture.
  5535. *
  5536. * @type {number}
  5537. * @default UnsignedByteType
  5538. */
  5539. this.type = type;
  5540. /**
  5541. * How much a single repetition of the texture is offset from the beginning,
  5542. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5543. *
  5544. * @type {Vector2}
  5545. * @default (0,0)
  5546. */
  5547. this.offset = new Vector2( 0, 0 );
  5548. /**
  5549. * How many times the texture is repeated across the surface, in each
  5550. * direction U and V. If repeat is set greater than `1` in either direction,
  5551. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5552. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5553. *
  5554. * @type {Vector2}
  5555. * @default (1,1)
  5556. */
  5557. this.repeat = new Vector2( 1, 1 );
  5558. /**
  5559. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5560. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5561. *
  5562. * @type {Vector2}
  5563. * @default (0,0)
  5564. */
  5565. this.center = new Vector2( 0, 0 );
  5566. /**
  5567. * How much the texture is rotated around the center point, in radians.
  5568. * Positive values are counter-clockwise.
  5569. *
  5570. * @type {number}
  5571. * @default 0
  5572. */
  5573. this.rotation = 0;
  5574. /**
  5575. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5576. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5577. * {@link Texture#rotation}, and {@link Texture#center}.
  5578. *
  5579. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5580. *
  5581. * @type {boolean}
  5582. * @default true
  5583. */
  5584. this.matrixAutoUpdate = true;
  5585. /**
  5586. * The uv-transformation matrix of the texture.
  5587. *
  5588. * @type {Matrix3}
  5589. */
  5590. this.matrix = new Matrix3();
  5591. /**
  5592. * Whether to generate mipmaps (if possible) for a texture.
  5593. *
  5594. * Set this to `false` if you are creating mipmaps manually.
  5595. *
  5596. * @type {boolean}
  5597. * @default true
  5598. */
  5599. this.generateMipmaps = true;
  5600. /**
  5601. * If set to `true`, the alpha channel, if present, is multiplied into the
  5602. * color channels when the texture is uploaded to the GPU.
  5603. *
  5604. * Note that this property has no effect when using `ImageBitmap`. You need to
  5605. * configure premultiply alpha on bitmap creation instead.
  5606. *
  5607. * @type {boolean}
  5608. * @default false
  5609. */
  5610. this.premultiplyAlpha = false;
  5611. /**
  5612. * If set to `true`, the texture is flipped along the vertical axis when
  5613. * uploaded to the GPU.
  5614. *
  5615. * Note that this property has no effect when using `ImageBitmap`. You need to
  5616. * configure the flip on bitmap creation instead.
  5617. *
  5618. * @type {boolean}
  5619. * @default true
  5620. */
  5621. this.flipY = true;
  5622. /**
  5623. * Specifies the alignment requirements for the start of each pixel row in memory.
  5624. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5625. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5626. *
  5627. * @type {number}
  5628. * @default 4
  5629. */
  5630. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5631. /**
  5632. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5633. *
  5634. * @type {string}
  5635. * @default NoColorSpace
  5636. */
  5637. this.colorSpace = colorSpace;
  5638. /**
  5639. * An object that can be used to store custom data about the texture. It
  5640. * should not hold references to functions as these will not be cloned.
  5641. *
  5642. * @type {Object}
  5643. */
  5644. this.userData = {};
  5645. /**
  5646. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5647. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5648. *
  5649. * @type {Array<Object>}
  5650. */
  5651. this.updateRanges = [];
  5652. /**
  5653. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5654. *
  5655. * @type {number}
  5656. * @readonly
  5657. * @default 0
  5658. */
  5659. this.version = 0;
  5660. /**
  5661. * A callback function, called when the texture is updated (e.g., when
  5662. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5663. *
  5664. * @type {?Function}
  5665. * @default null
  5666. */
  5667. this.onUpdate = null;
  5668. /**
  5669. * An optional back reference to the textures render target.
  5670. *
  5671. * @type {?(RenderTarget|WebGLRenderTarget)}
  5672. * @default null
  5673. */
  5674. this.renderTarget = null;
  5675. /**
  5676. * Indicates whether a texture belongs to a render target or not.
  5677. *
  5678. * @type {boolean}
  5679. * @readonly
  5680. * @default false
  5681. */
  5682. this.isRenderTargetTexture = false;
  5683. /**
  5684. * Indicates if a texture should be handled like a texture array.
  5685. *
  5686. * @type {boolean}
  5687. * @readonly
  5688. * @default false
  5689. */
  5690. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5691. /**
  5692. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5693. * (only relevant for render target textures).
  5694. *
  5695. * @type {number}
  5696. * @readonly
  5697. * @default 0
  5698. */
  5699. this.pmremVersion = 0;
  5700. }
  5701. /**
  5702. * The width of the texture in pixels.
  5703. */
  5704. get width() {
  5705. return this.source.getSize( _tempVec3 ).x;
  5706. }
  5707. /**
  5708. * The height of the texture in pixels.
  5709. */
  5710. get height() {
  5711. return this.source.getSize( _tempVec3 ).y;
  5712. }
  5713. /**
  5714. * The depth of the texture in pixels.
  5715. */
  5716. get depth() {
  5717. return this.source.getSize( _tempVec3 ).z;
  5718. }
  5719. /**
  5720. * The image object holding the texture data.
  5721. *
  5722. * @type {?Object}
  5723. */
  5724. get image() {
  5725. return this.source.data;
  5726. }
  5727. set image( value = null ) {
  5728. this.source.data = value;
  5729. }
  5730. /**
  5731. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5732. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5733. */
  5734. updateMatrix() {
  5735. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5736. }
  5737. /**
  5738. * Adds a range of data in the data texture to be updated on the GPU.
  5739. *
  5740. * @param {number} start - Position at which to start update.
  5741. * @param {number} count - The number of components to update.
  5742. */
  5743. addUpdateRange( start, count ) {
  5744. this.updateRanges.push( { start, count } );
  5745. }
  5746. /**
  5747. * Clears the update ranges.
  5748. */
  5749. clearUpdateRanges() {
  5750. this.updateRanges.length = 0;
  5751. }
  5752. /**
  5753. * Returns a new texture with copied values from this instance.
  5754. *
  5755. * @return {Texture} A clone of this instance.
  5756. */
  5757. clone() {
  5758. return new this.constructor().copy( this );
  5759. }
  5760. /**
  5761. * Copies the values of the given texture to this instance.
  5762. *
  5763. * @param {Texture} source - The texture to copy.
  5764. * @return {Texture} A reference to this instance.
  5765. */
  5766. copy( source ) {
  5767. this.name = source.name;
  5768. this.source = source.source;
  5769. this.mipmaps = source.mipmaps.slice( 0 );
  5770. this.mapping = source.mapping;
  5771. this.channel = source.channel;
  5772. this.wrapS = source.wrapS;
  5773. this.wrapT = source.wrapT;
  5774. this.magFilter = source.magFilter;
  5775. this.minFilter = source.minFilter;
  5776. this.anisotropy = source.anisotropy;
  5777. this.format = source.format;
  5778. this.internalFormat = source.internalFormat;
  5779. this.type = source.type;
  5780. this.offset.copy( source.offset );
  5781. this.repeat.copy( source.repeat );
  5782. this.center.copy( source.center );
  5783. this.rotation = source.rotation;
  5784. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5785. this.matrix.copy( source.matrix );
  5786. this.generateMipmaps = source.generateMipmaps;
  5787. this.premultiplyAlpha = source.premultiplyAlpha;
  5788. this.flipY = source.flipY;
  5789. this.unpackAlignment = source.unpackAlignment;
  5790. this.colorSpace = source.colorSpace;
  5791. this.renderTarget = source.renderTarget;
  5792. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5793. this.isArrayTexture = source.isArrayTexture;
  5794. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5795. this.needsUpdate = true;
  5796. return this;
  5797. }
  5798. /**
  5799. * Sets this texture's properties based on `values`.
  5800. * @param {Object} values - A container with texture parameters.
  5801. */
  5802. setValues( values ) {
  5803. for ( const key in values ) {
  5804. const newValue = values[ key ];
  5805. if ( newValue === undefined ) {
  5806. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5807. continue;
  5808. }
  5809. const currentValue = this[ key ];
  5810. if ( currentValue === undefined ) {
  5811. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5812. continue;
  5813. }
  5814. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5815. currentValue.copy( newValue );
  5816. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5817. currentValue.copy( newValue );
  5818. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5819. currentValue.copy( newValue );
  5820. } else {
  5821. this[ key ] = newValue;
  5822. }
  5823. }
  5824. }
  5825. /**
  5826. * Serializes the texture into JSON.
  5827. *
  5828. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5829. * @return {Object} A JSON object representing the serialized texture.
  5830. * @see {@link ObjectLoader#parse}
  5831. */
  5832. toJSON( meta ) {
  5833. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5834. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5835. return meta.textures[ this.uuid ];
  5836. }
  5837. const output = {
  5838. metadata: {
  5839. version: 4.7,
  5840. type: 'Texture',
  5841. generator: 'Texture.toJSON'
  5842. },
  5843. uuid: this.uuid,
  5844. name: this.name,
  5845. image: this.source.toJSON( meta ).uuid,
  5846. mapping: this.mapping,
  5847. channel: this.channel,
  5848. repeat: [ this.repeat.x, this.repeat.y ],
  5849. offset: [ this.offset.x, this.offset.y ],
  5850. center: [ this.center.x, this.center.y ],
  5851. rotation: this.rotation,
  5852. wrap: [ this.wrapS, this.wrapT ],
  5853. format: this.format,
  5854. internalFormat: this.internalFormat,
  5855. type: this.type,
  5856. colorSpace: this.colorSpace,
  5857. minFilter: this.minFilter,
  5858. magFilter: this.magFilter,
  5859. anisotropy: this.anisotropy,
  5860. flipY: this.flipY,
  5861. generateMipmaps: this.generateMipmaps,
  5862. premultiplyAlpha: this.premultiplyAlpha,
  5863. unpackAlignment: this.unpackAlignment
  5864. };
  5865. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5866. if ( ! isRootObject ) {
  5867. meta.textures[ this.uuid ] = output;
  5868. }
  5869. return output;
  5870. }
  5871. /**
  5872. * Frees the GPU-related resources allocated by this instance. Call this
  5873. * method whenever this instance is no longer used in your app.
  5874. *
  5875. * @fires Texture#dispose
  5876. */
  5877. dispose() {
  5878. /**
  5879. * Fires when the texture has been disposed of.
  5880. *
  5881. * @event Texture#dispose
  5882. * @type {Object}
  5883. */
  5884. this.dispatchEvent( { type: 'dispose' } );
  5885. }
  5886. /**
  5887. * Transforms the given uv vector with the textures uv transformation matrix.
  5888. *
  5889. * @param {Vector2} uv - The uv vector.
  5890. * @return {Vector2} The transformed uv vector.
  5891. */
  5892. transformUv( uv ) {
  5893. if ( this.mapping !== UVMapping ) return uv;
  5894. uv.applyMatrix3( this.matrix );
  5895. if ( uv.x < 0 || uv.x > 1 ) {
  5896. switch ( this.wrapS ) {
  5897. case RepeatWrapping:
  5898. uv.x = uv.x - Math.floor( uv.x );
  5899. break;
  5900. case ClampToEdgeWrapping:
  5901. uv.x = uv.x < 0 ? 0 : 1;
  5902. break;
  5903. case MirroredRepeatWrapping:
  5904. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5905. uv.x = Math.ceil( uv.x ) - uv.x;
  5906. } else {
  5907. uv.x = uv.x - Math.floor( uv.x );
  5908. }
  5909. break;
  5910. }
  5911. }
  5912. if ( uv.y < 0 || uv.y > 1 ) {
  5913. switch ( this.wrapT ) {
  5914. case RepeatWrapping:
  5915. uv.y = uv.y - Math.floor( uv.y );
  5916. break;
  5917. case ClampToEdgeWrapping:
  5918. uv.y = uv.y < 0 ? 0 : 1;
  5919. break;
  5920. case MirroredRepeatWrapping:
  5921. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5922. uv.y = Math.ceil( uv.y ) - uv.y;
  5923. } else {
  5924. uv.y = uv.y - Math.floor( uv.y );
  5925. }
  5926. break;
  5927. }
  5928. }
  5929. if ( this.flipY ) {
  5930. uv.y = 1 - uv.y;
  5931. }
  5932. return uv;
  5933. }
  5934. /**
  5935. * Setting this property to `true` indicates the engine the texture
  5936. * must be updated in the next render. This triggers a texture upload
  5937. * to the GPU and ensures correct texture parameter configuration.
  5938. *
  5939. * @type {boolean}
  5940. * @default false
  5941. * @param {boolean} value
  5942. */
  5943. set needsUpdate( value ) {
  5944. if ( value === true ) {
  5945. this.version ++;
  5946. this.source.needsUpdate = true;
  5947. }
  5948. }
  5949. /**
  5950. * Setting this property to `true` indicates the engine the PMREM
  5951. * must be regenerated.
  5952. *
  5953. * @type {boolean}
  5954. * @default false
  5955. * @param {boolean} value
  5956. */
  5957. set needsPMREMUpdate( value ) {
  5958. if ( value === true ) {
  5959. this.pmremVersion ++;
  5960. }
  5961. }
  5962. }
  5963. /**
  5964. * The default image for all textures.
  5965. *
  5966. * @static
  5967. * @type {?Image}
  5968. * @default null
  5969. */
  5970. Texture.DEFAULT_IMAGE = null;
  5971. /**
  5972. * The default mapping for all textures.
  5973. *
  5974. * @static
  5975. * @type {number}
  5976. * @default UVMapping
  5977. */
  5978. Texture.DEFAULT_MAPPING = UVMapping;
  5979. /**
  5980. * The default anisotropy value for all textures.
  5981. *
  5982. * @static
  5983. * @type {number}
  5984. * @default 1
  5985. */
  5986. Texture.DEFAULT_ANISOTROPY = 1;
  5987. /**
  5988. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5989. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5990. *
  5991. * - A point in 4D space.
  5992. * - A direction and length in 4D space. In three.js the length will
  5993. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5994. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5995. * - Any arbitrary ordered quadruplet of numbers.
  5996. *
  5997. * There are other things a 4D vector can be used to represent, however these
  5998. * are the most common uses in *three.js*.
  5999. *
  6000. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6001. * the corresponding order.
  6002. * ```js
  6003. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6004. *
  6005. * //no arguments; will be initialised to (0, 0, 0, 1)
  6006. * const b = new THREE.Vector4( );
  6007. *
  6008. * const d = a.dot( b );
  6009. * ```
  6010. */
  6011. class Vector4 {
  6012. /**
  6013. * Constructs a new 4D vector.
  6014. *
  6015. * @param {number} [x=0] - The x value of this vector.
  6016. * @param {number} [y=0] - The y value of this vector.
  6017. * @param {number} [z=0] - The z value of this vector.
  6018. * @param {number} [w=1] - The w value of this vector.
  6019. */
  6020. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6021. /**
  6022. * This flag can be used for type testing.
  6023. *
  6024. * @type {boolean}
  6025. * @readonly
  6026. * @default true
  6027. */
  6028. Vector4.prototype.isVector4 = true;
  6029. /**
  6030. * The x value of this vector.
  6031. *
  6032. * @type {number}
  6033. */
  6034. this.x = x;
  6035. /**
  6036. * The y value of this vector.
  6037. *
  6038. * @type {number}
  6039. */
  6040. this.y = y;
  6041. /**
  6042. * The z value of this vector.
  6043. *
  6044. * @type {number}
  6045. */
  6046. this.z = z;
  6047. /**
  6048. * The w value of this vector.
  6049. *
  6050. * @type {number}
  6051. */
  6052. this.w = w;
  6053. }
  6054. /**
  6055. * Alias for {@link Vector4#z}.
  6056. *
  6057. * @type {number}
  6058. */
  6059. get width() {
  6060. return this.z;
  6061. }
  6062. set width( value ) {
  6063. this.z = value;
  6064. }
  6065. /**
  6066. * Alias for {@link Vector4#w}.
  6067. *
  6068. * @type {number}
  6069. */
  6070. get height() {
  6071. return this.w;
  6072. }
  6073. set height( value ) {
  6074. this.w = value;
  6075. }
  6076. /**
  6077. * Sets the vector components.
  6078. *
  6079. * @param {number} x - The value of the x component.
  6080. * @param {number} y - The value of the y component.
  6081. * @param {number} z - The value of the z component.
  6082. * @param {number} w - The value of the w component.
  6083. * @return {Vector4} A reference to this vector.
  6084. */
  6085. set( x, y, z, w ) {
  6086. this.x = x;
  6087. this.y = y;
  6088. this.z = z;
  6089. this.w = w;
  6090. return this;
  6091. }
  6092. /**
  6093. * Sets the vector components to the same value.
  6094. *
  6095. * @param {number} scalar - The value to set for all vector components.
  6096. * @return {Vector4} A reference to this vector.
  6097. */
  6098. setScalar( scalar ) {
  6099. this.x = scalar;
  6100. this.y = scalar;
  6101. this.z = scalar;
  6102. this.w = scalar;
  6103. return this;
  6104. }
  6105. /**
  6106. * Sets the vector's x component to the given value
  6107. *
  6108. * @param {number} x - The value to set.
  6109. * @return {Vector4} A reference to this vector.
  6110. */
  6111. setX( x ) {
  6112. this.x = x;
  6113. return this;
  6114. }
  6115. /**
  6116. * Sets the vector's y component to the given value
  6117. *
  6118. * @param {number} y - The value to set.
  6119. * @return {Vector4} A reference to this vector.
  6120. */
  6121. setY( y ) {
  6122. this.y = y;
  6123. return this;
  6124. }
  6125. /**
  6126. * Sets the vector's z component to the given value
  6127. *
  6128. * @param {number} z - The value to set.
  6129. * @return {Vector4} A reference to this vector.
  6130. */
  6131. setZ( z ) {
  6132. this.z = z;
  6133. return this;
  6134. }
  6135. /**
  6136. * Sets the vector's w component to the given value
  6137. *
  6138. * @param {number} w - The value to set.
  6139. * @return {Vector4} A reference to this vector.
  6140. */
  6141. setW( w ) {
  6142. this.w = w;
  6143. return this;
  6144. }
  6145. /**
  6146. * Allows to set a vector component with an index.
  6147. *
  6148. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6149. * `2` equals to z, `3` equals to w.
  6150. * @param {number} value - The value to set.
  6151. * @return {Vector4} A reference to this vector.
  6152. */
  6153. setComponent( index, value ) {
  6154. switch ( index ) {
  6155. case 0: this.x = value; break;
  6156. case 1: this.y = value; break;
  6157. case 2: this.z = value; break;
  6158. case 3: this.w = value; break;
  6159. default: throw new Error( 'index is out of range: ' + index );
  6160. }
  6161. return this;
  6162. }
  6163. /**
  6164. * Returns the value of the vector component which matches the given index.
  6165. *
  6166. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6167. * `2` equals to z, `3` equals to w.
  6168. * @return {number} A vector component value.
  6169. */
  6170. getComponent( index ) {
  6171. switch ( index ) {
  6172. case 0: return this.x;
  6173. case 1: return this.y;
  6174. case 2: return this.z;
  6175. case 3: return this.w;
  6176. default: throw new Error( 'index is out of range: ' + index );
  6177. }
  6178. }
  6179. /**
  6180. * Returns a new vector with copied values from this instance.
  6181. *
  6182. * @return {Vector4} A clone of this instance.
  6183. */
  6184. clone() {
  6185. return new this.constructor( this.x, this.y, this.z, this.w );
  6186. }
  6187. /**
  6188. * Copies the values of the given vector to this instance.
  6189. *
  6190. * @param {Vector3|Vector4} v - The vector to copy.
  6191. * @return {Vector4} A reference to this vector.
  6192. */
  6193. copy( v ) {
  6194. this.x = v.x;
  6195. this.y = v.y;
  6196. this.z = v.z;
  6197. this.w = ( v.w !== undefined ) ? v.w : 1;
  6198. return this;
  6199. }
  6200. /**
  6201. * Adds the given vector to this instance.
  6202. *
  6203. * @param {Vector4} v - The vector to add.
  6204. * @return {Vector4} A reference to this vector.
  6205. */
  6206. add( v ) {
  6207. this.x += v.x;
  6208. this.y += v.y;
  6209. this.z += v.z;
  6210. this.w += v.w;
  6211. return this;
  6212. }
  6213. /**
  6214. * Adds the given scalar value to all components of this instance.
  6215. *
  6216. * @param {number} s - The scalar to add.
  6217. * @return {Vector4} A reference to this vector.
  6218. */
  6219. addScalar( s ) {
  6220. this.x += s;
  6221. this.y += s;
  6222. this.z += s;
  6223. this.w += s;
  6224. return this;
  6225. }
  6226. /**
  6227. * Adds the given vectors and stores the result in this instance.
  6228. *
  6229. * @param {Vector4} a - The first vector.
  6230. * @param {Vector4} b - The second vector.
  6231. * @return {Vector4} A reference to this vector.
  6232. */
  6233. addVectors( a, b ) {
  6234. this.x = a.x + b.x;
  6235. this.y = a.y + b.y;
  6236. this.z = a.z + b.z;
  6237. this.w = a.w + b.w;
  6238. return this;
  6239. }
  6240. /**
  6241. * Adds the given vector scaled by the given factor to this instance.
  6242. *
  6243. * @param {Vector4} v - The vector.
  6244. * @param {number} s - The factor that scales `v`.
  6245. * @return {Vector4} A reference to this vector.
  6246. */
  6247. addScaledVector( v, s ) {
  6248. this.x += v.x * s;
  6249. this.y += v.y * s;
  6250. this.z += v.z * s;
  6251. this.w += v.w * s;
  6252. return this;
  6253. }
  6254. /**
  6255. * Subtracts the given vector from this instance.
  6256. *
  6257. * @param {Vector4} v - The vector to subtract.
  6258. * @return {Vector4} A reference to this vector.
  6259. */
  6260. sub( v ) {
  6261. this.x -= v.x;
  6262. this.y -= v.y;
  6263. this.z -= v.z;
  6264. this.w -= v.w;
  6265. return this;
  6266. }
  6267. /**
  6268. * Subtracts the given scalar value from all components of this instance.
  6269. *
  6270. * @param {number} s - The scalar to subtract.
  6271. * @return {Vector4} A reference to this vector.
  6272. */
  6273. subScalar( s ) {
  6274. this.x -= s;
  6275. this.y -= s;
  6276. this.z -= s;
  6277. this.w -= s;
  6278. return this;
  6279. }
  6280. /**
  6281. * Subtracts the given vectors and stores the result in this instance.
  6282. *
  6283. * @param {Vector4} a - The first vector.
  6284. * @param {Vector4} b - The second vector.
  6285. * @return {Vector4} A reference to this vector.
  6286. */
  6287. subVectors( a, b ) {
  6288. this.x = a.x - b.x;
  6289. this.y = a.y - b.y;
  6290. this.z = a.z - b.z;
  6291. this.w = a.w - b.w;
  6292. return this;
  6293. }
  6294. /**
  6295. * Multiplies the given vector with this instance.
  6296. *
  6297. * @param {Vector4} v - The vector to multiply.
  6298. * @return {Vector4} A reference to this vector.
  6299. */
  6300. multiply( v ) {
  6301. this.x *= v.x;
  6302. this.y *= v.y;
  6303. this.z *= v.z;
  6304. this.w *= v.w;
  6305. return this;
  6306. }
  6307. /**
  6308. * Multiplies the given scalar value with all components of this instance.
  6309. *
  6310. * @param {number} scalar - The scalar to multiply.
  6311. * @return {Vector4} A reference to this vector.
  6312. */
  6313. multiplyScalar( scalar ) {
  6314. this.x *= scalar;
  6315. this.y *= scalar;
  6316. this.z *= scalar;
  6317. this.w *= scalar;
  6318. return this;
  6319. }
  6320. /**
  6321. * Multiplies this vector with the given 4x4 matrix.
  6322. *
  6323. * @param {Matrix4} m - The 4x4 matrix.
  6324. * @return {Vector4} A reference to this vector.
  6325. */
  6326. applyMatrix4( m ) {
  6327. const x = this.x, y = this.y, z = this.z, w = this.w;
  6328. const e = m.elements;
  6329. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6330. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6331. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6332. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6333. return this;
  6334. }
  6335. /**
  6336. * Divides this instance by the given vector.
  6337. *
  6338. * @param {Vector4} v - The vector to divide.
  6339. * @return {Vector4} A reference to this vector.
  6340. */
  6341. divide( v ) {
  6342. this.x /= v.x;
  6343. this.y /= v.y;
  6344. this.z /= v.z;
  6345. this.w /= v.w;
  6346. return this;
  6347. }
  6348. /**
  6349. * Divides this vector by the given scalar.
  6350. *
  6351. * @param {number} scalar - The scalar to divide.
  6352. * @return {Vector4} A reference to this vector.
  6353. */
  6354. divideScalar( scalar ) {
  6355. return this.multiplyScalar( 1 / scalar );
  6356. }
  6357. /**
  6358. * Sets the x, y and z components of this
  6359. * vector to the quaternion's axis and w to the angle.
  6360. *
  6361. * @param {Quaternion} q - The Quaternion to set.
  6362. * @return {Vector4} A reference to this vector.
  6363. */
  6364. setAxisAngleFromQuaternion( q ) {
  6365. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6366. // q is assumed to be normalized
  6367. this.w = 2 * Math.acos( q.w );
  6368. const s = Math.sqrt( 1 - q.w * q.w );
  6369. if ( s < 0.0001 ) {
  6370. this.x = 1;
  6371. this.y = 0;
  6372. this.z = 0;
  6373. } else {
  6374. this.x = q.x / s;
  6375. this.y = q.y / s;
  6376. this.z = q.z / s;
  6377. }
  6378. return this;
  6379. }
  6380. /**
  6381. * Sets the x, y and z components of this
  6382. * vector to the axis of rotation and w to the angle.
  6383. *
  6384. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6385. * @return {Vector4} A reference to this vector.
  6386. */
  6387. setAxisAngleFromRotationMatrix( m ) {
  6388. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6389. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6390. let angle, x, y, z; // variables for result
  6391. const epsilon = 0.01, // margin to allow for rounding errors
  6392. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6393. te = m.elements,
  6394. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6395. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6396. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6397. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6398. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6399. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6400. // singularity found
  6401. // first check for identity matrix which must have +1 for all terms
  6402. // in leading diagonal and zero in other terms
  6403. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6404. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6405. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6406. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6407. // this singularity is identity matrix so angle = 0
  6408. this.set( 1, 0, 0, 0 );
  6409. return this; // zero angle, arbitrary axis
  6410. }
  6411. // otherwise this singularity is angle = 180
  6412. angle = Math.PI;
  6413. const xx = ( m11 + 1 ) / 2;
  6414. const yy = ( m22 + 1 ) / 2;
  6415. const zz = ( m33 + 1 ) / 2;
  6416. const xy = ( m12 + m21 ) / 4;
  6417. const xz = ( m13 + m31 ) / 4;
  6418. const yz = ( m23 + m32 ) / 4;
  6419. if ( ( xx > yy ) && ( xx > zz ) ) {
  6420. // m11 is the largest diagonal term
  6421. if ( xx < epsilon ) {
  6422. x = 0;
  6423. y = 0.707106781;
  6424. z = 0.707106781;
  6425. } else {
  6426. x = Math.sqrt( xx );
  6427. y = xy / x;
  6428. z = xz / x;
  6429. }
  6430. } else if ( yy > zz ) {
  6431. // m22 is the largest diagonal term
  6432. if ( yy < epsilon ) {
  6433. x = 0.707106781;
  6434. y = 0;
  6435. z = 0.707106781;
  6436. } else {
  6437. y = Math.sqrt( yy );
  6438. x = xy / y;
  6439. z = yz / y;
  6440. }
  6441. } else {
  6442. // m33 is the largest diagonal term so base result on this
  6443. if ( zz < epsilon ) {
  6444. x = 0.707106781;
  6445. y = 0.707106781;
  6446. z = 0;
  6447. } else {
  6448. z = Math.sqrt( zz );
  6449. x = xz / z;
  6450. y = yz / z;
  6451. }
  6452. }
  6453. this.set( x, y, z, angle );
  6454. return this; // return 180 deg rotation
  6455. }
  6456. // as we have reached here there are no singularities so we can handle normally
  6457. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6458. ( m13 - m31 ) * ( m13 - m31 ) +
  6459. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6460. if ( Math.abs( s ) < 0.001 ) s = 1;
  6461. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6462. // caught by singularity test above, but I've left it in just in case
  6463. this.x = ( m32 - m23 ) / s;
  6464. this.y = ( m13 - m31 ) / s;
  6465. this.z = ( m21 - m12 ) / s;
  6466. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6467. return this;
  6468. }
  6469. /**
  6470. * Sets the vector components to the position elements of the
  6471. * given transformation matrix.
  6472. *
  6473. * @param {Matrix4} m - The 4x4 matrix.
  6474. * @return {Vector4} A reference to this vector.
  6475. */
  6476. setFromMatrixPosition( m ) {
  6477. const e = m.elements;
  6478. this.x = e[ 12 ];
  6479. this.y = e[ 13 ];
  6480. this.z = e[ 14 ];
  6481. this.w = e[ 15 ];
  6482. return this;
  6483. }
  6484. /**
  6485. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6486. * value, replace that value with the corresponding min value.
  6487. *
  6488. * @param {Vector4} v - The vector.
  6489. * @return {Vector4} A reference to this vector.
  6490. */
  6491. min( v ) {
  6492. this.x = Math.min( this.x, v.x );
  6493. this.y = Math.min( this.y, v.y );
  6494. this.z = Math.min( this.z, v.z );
  6495. this.w = Math.min( this.w, v.w );
  6496. return this;
  6497. }
  6498. /**
  6499. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6500. * value, replace that value with the corresponding max value.
  6501. *
  6502. * @param {Vector4} v - The vector.
  6503. * @return {Vector4} A reference to this vector.
  6504. */
  6505. max( v ) {
  6506. this.x = Math.max( this.x, v.x );
  6507. this.y = Math.max( this.y, v.y );
  6508. this.z = Math.max( this.z, v.z );
  6509. this.w = Math.max( this.w, v.w );
  6510. return this;
  6511. }
  6512. /**
  6513. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6514. * value, it is replaced by the corresponding value.
  6515. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6516. * it is replaced by the corresponding value.
  6517. *
  6518. * @param {Vector4} min - The minimum x, y and z values.
  6519. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6520. * @return {Vector4} A reference to this vector.
  6521. */
  6522. clamp( min, max ) {
  6523. // assumes min < max, componentwise
  6524. this.x = clamp( this.x, min.x, max.x );
  6525. this.y = clamp( this.y, min.y, max.y );
  6526. this.z = clamp( this.z, min.z, max.z );
  6527. this.w = clamp( this.w, min.w, max.w );
  6528. return this;
  6529. }
  6530. /**
  6531. * If this vector's x, y, z or w values are greater than the max value, they are
  6532. * replaced by the max value.
  6533. * If this vector's x, y, z or w values are less than the min value, they are
  6534. * replaced by the min value.
  6535. *
  6536. * @param {number} minVal - The minimum value the components will be clamped to.
  6537. * @param {number} maxVal - The maximum value the components will be clamped to.
  6538. * @return {Vector4} A reference to this vector.
  6539. */
  6540. clampScalar( minVal, maxVal ) {
  6541. this.x = clamp( this.x, minVal, maxVal );
  6542. this.y = clamp( this.y, minVal, maxVal );
  6543. this.z = clamp( this.z, minVal, maxVal );
  6544. this.w = clamp( this.w, minVal, maxVal );
  6545. return this;
  6546. }
  6547. /**
  6548. * If this vector's length is greater than the max value, it is replaced by
  6549. * the max value.
  6550. * If this vector's length is less than the min value, it is replaced by the
  6551. * min value.
  6552. *
  6553. * @param {number} min - The minimum value the vector length will be clamped to.
  6554. * @param {number} max - The maximum value the vector length will be clamped to.
  6555. * @return {Vector4} A reference to this vector.
  6556. */
  6557. clampLength( min, max ) {
  6558. const length = this.length();
  6559. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6560. }
  6561. /**
  6562. * The components of this vector are rounded down to the nearest integer value.
  6563. *
  6564. * @return {Vector4} A reference to this vector.
  6565. */
  6566. floor() {
  6567. this.x = Math.floor( this.x );
  6568. this.y = Math.floor( this.y );
  6569. this.z = Math.floor( this.z );
  6570. this.w = Math.floor( this.w );
  6571. return this;
  6572. }
  6573. /**
  6574. * The components of this vector are rounded up to the nearest integer value.
  6575. *
  6576. * @return {Vector4} A reference to this vector.
  6577. */
  6578. ceil() {
  6579. this.x = Math.ceil( this.x );
  6580. this.y = Math.ceil( this.y );
  6581. this.z = Math.ceil( this.z );
  6582. this.w = Math.ceil( this.w );
  6583. return this;
  6584. }
  6585. /**
  6586. * The components of this vector are rounded to the nearest integer value
  6587. *
  6588. * @return {Vector4} A reference to this vector.
  6589. */
  6590. round() {
  6591. this.x = Math.round( this.x );
  6592. this.y = Math.round( this.y );
  6593. this.z = Math.round( this.z );
  6594. this.w = Math.round( this.w );
  6595. return this;
  6596. }
  6597. /**
  6598. * The components of this vector are rounded towards zero (up if negative,
  6599. * down if positive) to an integer value.
  6600. *
  6601. * @return {Vector4} A reference to this vector.
  6602. */
  6603. roundToZero() {
  6604. this.x = Math.trunc( this.x );
  6605. this.y = Math.trunc( this.y );
  6606. this.z = Math.trunc( this.z );
  6607. this.w = Math.trunc( this.w );
  6608. return this;
  6609. }
  6610. /**
  6611. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6612. *
  6613. * @return {Vector4} A reference to this vector.
  6614. */
  6615. negate() {
  6616. this.x = - this.x;
  6617. this.y = - this.y;
  6618. this.z = - this.z;
  6619. this.w = - this.w;
  6620. return this;
  6621. }
  6622. /**
  6623. * Calculates the dot product of the given vector with this instance.
  6624. *
  6625. * @param {Vector4} v - The vector to compute the dot product with.
  6626. * @return {number} The result of the dot product.
  6627. */
  6628. dot( v ) {
  6629. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6630. }
  6631. /**
  6632. * Computes the square of the Euclidean length (straight-line length) from
  6633. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6634. * compare the length squared instead as it is slightly more efficient to calculate.
  6635. *
  6636. * @return {number} The square length of this vector.
  6637. */
  6638. lengthSq() {
  6639. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6640. }
  6641. /**
  6642. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6643. *
  6644. * @return {number} The length of this vector.
  6645. */
  6646. length() {
  6647. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6648. }
  6649. /**
  6650. * Computes the Manhattan length of this vector.
  6651. *
  6652. * @return {number} The length of this vector.
  6653. */
  6654. manhattanLength() {
  6655. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6656. }
  6657. /**
  6658. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6659. * with the same direction as this one, but with a vector length of `1`.
  6660. *
  6661. * @return {Vector4} A reference to this vector.
  6662. */
  6663. normalize() {
  6664. return this.divideScalar( this.length() || 1 );
  6665. }
  6666. /**
  6667. * Sets this vector to a vector with the same direction as this one, but
  6668. * with the specified length.
  6669. *
  6670. * @param {number} length - The new length of this vector.
  6671. * @return {Vector4} A reference to this vector.
  6672. */
  6673. setLength( length ) {
  6674. return this.normalize().multiplyScalar( length );
  6675. }
  6676. /**
  6677. * Linearly interpolates between the given vector and this instance, where
  6678. * alpha is the percent distance along the line - alpha = 0 will be this
  6679. * vector, and alpha = 1 will be the given one.
  6680. *
  6681. * @param {Vector4} v - The vector to interpolate towards.
  6682. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6683. * @return {Vector4} A reference to this vector.
  6684. */
  6685. lerp( v, alpha ) {
  6686. this.x += ( v.x - this.x ) * alpha;
  6687. this.y += ( v.y - this.y ) * alpha;
  6688. this.z += ( v.z - this.z ) * alpha;
  6689. this.w += ( v.w - this.w ) * alpha;
  6690. return this;
  6691. }
  6692. /**
  6693. * Linearly interpolates between the given vectors, where alpha is the percent
  6694. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6695. * be the second one. The result is stored in this instance.
  6696. *
  6697. * @param {Vector4} v1 - The first vector.
  6698. * @param {Vector4} v2 - The second vector.
  6699. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6700. * @return {Vector4} A reference to this vector.
  6701. */
  6702. lerpVectors( v1, v2, alpha ) {
  6703. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6704. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6705. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6706. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6707. return this;
  6708. }
  6709. /**
  6710. * Returns `true` if this vector is equal with the given one.
  6711. *
  6712. * @param {Vector4} v - The vector to test for equality.
  6713. * @return {boolean} Whether this vector is equal with the given one.
  6714. */
  6715. equals( v ) {
  6716. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6717. }
  6718. /**
  6719. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6720. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6721. *
  6722. * @param {Array<number>} array - An array holding the vector component values.
  6723. * @param {number} [offset=0] - The offset into the array.
  6724. * @return {Vector4} A reference to this vector.
  6725. */
  6726. fromArray( array, offset = 0 ) {
  6727. this.x = array[ offset ];
  6728. this.y = array[ offset + 1 ];
  6729. this.z = array[ offset + 2 ];
  6730. this.w = array[ offset + 3 ];
  6731. return this;
  6732. }
  6733. /**
  6734. * Writes the components of this vector to the given array. If no array is provided,
  6735. * the method returns a new instance.
  6736. *
  6737. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6738. * @param {number} [offset=0] - Index of the first element in the array.
  6739. * @return {Array<number>} The vector components.
  6740. */
  6741. toArray( array = [], offset = 0 ) {
  6742. array[ offset ] = this.x;
  6743. array[ offset + 1 ] = this.y;
  6744. array[ offset + 2 ] = this.z;
  6745. array[ offset + 3 ] = this.w;
  6746. return array;
  6747. }
  6748. /**
  6749. * Sets the components of this vector from the given buffer attribute.
  6750. *
  6751. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6752. * @param {number} index - The index into the attribute.
  6753. * @return {Vector4} A reference to this vector.
  6754. */
  6755. fromBufferAttribute( attribute, index ) {
  6756. this.x = attribute.getX( index );
  6757. this.y = attribute.getY( index );
  6758. this.z = attribute.getZ( index );
  6759. this.w = attribute.getW( index );
  6760. return this;
  6761. }
  6762. /**
  6763. * Sets each component of this vector to a pseudo-random value between `0` and
  6764. * `1`, excluding `1`.
  6765. *
  6766. * @return {Vector4} A reference to this vector.
  6767. */
  6768. random() {
  6769. this.x = Math.random();
  6770. this.y = Math.random();
  6771. this.z = Math.random();
  6772. this.w = Math.random();
  6773. return this;
  6774. }
  6775. *[ Symbol.iterator ]() {
  6776. yield this.x;
  6777. yield this.y;
  6778. yield this.z;
  6779. yield this.w;
  6780. }
  6781. }
  6782. /**
  6783. * A render target is a buffer where the video card draws pixels for a scene
  6784. * that is being rendered in the background. It is used in different effects,
  6785. * such as applying postprocessing to a rendered image before displaying it
  6786. * on the screen.
  6787. *
  6788. * @augments EventDispatcher
  6789. */
  6790. class RenderTarget extends EventDispatcher {
  6791. /**
  6792. * Render target options.
  6793. *
  6794. * @typedef {Object} RenderTarget~Options
  6795. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6796. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6797. * @property {number} [minFilter=LinearFilter] - The min filter.
  6798. * @property {number} [format=RGBAFormat] - The texture format.
  6799. * @property {number} [type=UnsignedByteType] - The texture type.
  6800. * @property {?string} [internalFormat=null] - The texture's internal format.
  6801. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6802. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6803. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6804. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6805. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6806. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6807. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6808. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6809. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6810. * @property {number} [samples=0] - The MSAA samples count.
  6811. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6812. * @property {number} [depth=1] - The texture depth.
  6813. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6814. */
  6815. /**
  6816. * Constructs a new render target.
  6817. *
  6818. * @param {number} [width=1] - The width of the render target.
  6819. * @param {number} [height=1] - The height of the render target.
  6820. * @param {RenderTarget~Options} [options] - The configuration object.
  6821. */
  6822. constructor( width = 1, height = 1, options = {} ) {
  6823. super();
  6824. options = Object.assign( {
  6825. generateMipmaps: false,
  6826. internalFormat: null,
  6827. minFilter: LinearFilter,
  6828. depthBuffer: true,
  6829. stencilBuffer: false,
  6830. resolveDepthBuffer: true,
  6831. resolveStencilBuffer: true,
  6832. depthTexture: null,
  6833. samples: 0,
  6834. count: 1,
  6835. depth: 1,
  6836. multiview: false
  6837. }, options );
  6838. /**
  6839. * This flag can be used for type testing.
  6840. *
  6841. * @type {boolean}
  6842. * @readonly
  6843. * @default true
  6844. */
  6845. this.isRenderTarget = true;
  6846. /**
  6847. * The width of the render target.
  6848. *
  6849. * @type {number}
  6850. * @default 1
  6851. */
  6852. this.width = width;
  6853. /**
  6854. * The height of the render target.
  6855. *
  6856. * @type {number}
  6857. * @default 1
  6858. */
  6859. this.height = height;
  6860. /**
  6861. * The depth of the render target.
  6862. *
  6863. * @type {number}
  6864. * @default 1
  6865. */
  6866. this.depth = options.depth;
  6867. /**
  6868. * A rectangular area inside the render target's viewport. Fragments that are
  6869. * outside the area will be discarded.
  6870. *
  6871. * @type {Vector4}
  6872. * @default (0,0,width,height)
  6873. */
  6874. this.scissor = new Vector4( 0, 0, width, height );
  6875. /**
  6876. * Indicates whether the scissor test should be enabled when rendering into
  6877. * this render target or not.
  6878. *
  6879. * @type {boolean}
  6880. * @default false
  6881. */
  6882. this.scissorTest = false;
  6883. /**
  6884. * A rectangular area representing the render target's viewport.
  6885. *
  6886. * @type {Vector4}
  6887. * @default (0,0,width,height)
  6888. */
  6889. this.viewport = new Vector4( 0, 0, width, height );
  6890. const image = { width: width, height: height, depth: options.depth };
  6891. const texture = new Texture( image );
  6892. /**
  6893. * An array of textures. Each color attachment is represented as a separate texture.
  6894. * Has at least a single entry for the default color attachment.
  6895. *
  6896. * @type {Array<Texture>}
  6897. */
  6898. this.textures = [];
  6899. const count = options.count;
  6900. for ( let i = 0; i < count; i ++ ) {
  6901. this.textures[ i ] = texture.clone();
  6902. this.textures[ i ].isRenderTargetTexture = true;
  6903. this.textures[ i ].renderTarget = this;
  6904. }
  6905. this._setTextureOptions( options );
  6906. /**
  6907. * Whether to allocate a depth buffer or not.
  6908. *
  6909. * @type {boolean}
  6910. * @default true
  6911. */
  6912. this.depthBuffer = options.depthBuffer;
  6913. /**
  6914. * Whether to allocate a stencil buffer or not.
  6915. *
  6916. * @type {boolean}
  6917. * @default false
  6918. */
  6919. this.stencilBuffer = options.stencilBuffer;
  6920. /**
  6921. * Whether to resolve the depth buffer or not.
  6922. *
  6923. * @type {boolean}
  6924. * @default true
  6925. */
  6926. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6927. /**
  6928. * Whether to resolve the stencil buffer or not.
  6929. *
  6930. * @type {boolean}
  6931. * @default true
  6932. */
  6933. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6934. this._depthTexture = null;
  6935. this.depthTexture = options.depthTexture;
  6936. /**
  6937. * The number of MSAA samples.
  6938. *
  6939. * A value of `0` disables MSAA.
  6940. *
  6941. * @type {number}
  6942. * @default 0
  6943. */
  6944. this.samples = options.samples;
  6945. /**
  6946. * Whether to this target is used in multiview rendering.
  6947. *
  6948. * @type {boolean}
  6949. * @default false
  6950. */
  6951. this.multiview = options.multiview;
  6952. }
  6953. _setTextureOptions( options = {} ) {
  6954. const values = {
  6955. minFilter: LinearFilter,
  6956. generateMipmaps: false,
  6957. flipY: false,
  6958. internalFormat: null
  6959. };
  6960. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6961. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6962. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6963. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6964. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6965. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6966. if ( options.format !== undefined ) values.format = options.format;
  6967. if ( options.type !== undefined ) values.type = options.type;
  6968. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6969. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6970. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6971. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6972. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6973. for ( let i = 0; i < this.textures.length; i ++ ) {
  6974. const texture = this.textures[ i ];
  6975. texture.setValues( values );
  6976. }
  6977. }
  6978. /**
  6979. * The texture representing the default color attachment.
  6980. *
  6981. * @type {Texture}
  6982. */
  6983. get texture() {
  6984. return this.textures[ 0 ];
  6985. }
  6986. set texture( value ) {
  6987. this.textures[ 0 ] = value;
  6988. }
  6989. set depthTexture( current ) {
  6990. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6991. if ( current !== null ) current.renderTarget = this;
  6992. this._depthTexture = current;
  6993. }
  6994. /**
  6995. * Instead of saving the depth in a renderbuffer, a texture
  6996. * can be used instead which is useful for further processing
  6997. * e.g. in context of post-processing.
  6998. *
  6999. * @type {?DepthTexture}
  7000. * @default null
  7001. */
  7002. get depthTexture() {
  7003. return this._depthTexture;
  7004. }
  7005. /**
  7006. * Sets the size of this render target.
  7007. *
  7008. * @param {number} width - The width.
  7009. * @param {number} height - The height.
  7010. * @param {number} [depth=1] - The depth.
  7011. */
  7012. setSize( width, height, depth = 1 ) {
  7013. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7014. this.width = width;
  7015. this.height = height;
  7016. this.depth = depth;
  7017. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7018. this.textures[ i ].image.width = width;
  7019. this.textures[ i ].image.height = height;
  7020. this.textures[ i ].image.depth = depth;
  7021. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7022. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7023. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7024. // both are evaluated on each call?
  7025. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7026. }
  7027. }
  7028. this.dispose();
  7029. }
  7030. this.viewport.set( 0, 0, width, height );
  7031. this.scissor.set( 0, 0, width, height );
  7032. }
  7033. /**
  7034. * Returns a new render target with copied values from this instance.
  7035. *
  7036. * @return {RenderTarget} A clone of this instance.
  7037. */
  7038. clone() {
  7039. return new this.constructor().copy( this );
  7040. }
  7041. /**
  7042. * Copies the settings of the given render target. This is a structural copy so
  7043. * no resources are shared between render targets after the copy. That includes
  7044. * all MRT textures and the depth texture.
  7045. *
  7046. * @param {RenderTarget} source - The render target to copy.
  7047. * @return {RenderTarget} A reference to this instance.
  7048. */
  7049. copy( source ) {
  7050. this.width = source.width;
  7051. this.height = source.height;
  7052. this.depth = source.depth;
  7053. this.scissor.copy( source.scissor );
  7054. this.scissorTest = source.scissorTest;
  7055. this.viewport.copy( source.viewport );
  7056. this.textures.length = 0;
  7057. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7058. this.textures[ i ] = source.textures[ i ].clone();
  7059. this.textures[ i ].isRenderTargetTexture = true;
  7060. this.textures[ i ].renderTarget = this;
  7061. // ensure image object is not shared, see #20328
  7062. const image = Object.assign( {}, source.textures[ i ].image );
  7063. this.textures[ i ].source = new Source( image );
  7064. }
  7065. this.depthBuffer = source.depthBuffer;
  7066. this.stencilBuffer = source.stencilBuffer;
  7067. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7068. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7069. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7070. this.samples = source.samples;
  7071. return this;
  7072. }
  7073. /**
  7074. * Frees the GPU-related resources allocated by this instance. Call this
  7075. * method whenever this instance is no longer used in your app.
  7076. *
  7077. * @fires RenderTarget#dispose
  7078. */
  7079. dispose() {
  7080. this.dispatchEvent( { type: 'dispose' } );
  7081. }
  7082. }
  7083. /**
  7084. * A render target used in context of {@link WebGLRenderer}.
  7085. *
  7086. * @augments RenderTarget
  7087. */
  7088. class WebGLRenderTarget extends RenderTarget {
  7089. /**
  7090. * Constructs a new 3D render target.
  7091. *
  7092. * @param {number} [width=1] - The width of the render target.
  7093. * @param {number} [height=1] - The height of the render target.
  7094. * @param {RenderTarget~Options} [options] - The configuration object.
  7095. */
  7096. constructor( width = 1, height = 1, options = {} ) {
  7097. super( width, height, options );
  7098. /**
  7099. * This flag can be used for type testing.
  7100. *
  7101. * @type {boolean}
  7102. * @readonly
  7103. * @default true
  7104. */
  7105. this.isWebGLRenderTarget = true;
  7106. }
  7107. }
  7108. /**
  7109. * Creates an array of textures directly from raw buffer data.
  7110. *
  7111. * @augments Texture
  7112. */
  7113. class DataArrayTexture extends Texture {
  7114. /**
  7115. * Constructs a new data array texture.
  7116. *
  7117. * @param {?TypedArray} [data=null] - The buffer data.
  7118. * @param {number} [width=1] - The width of the texture.
  7119. * @param {number} [height=1] - The height of the texture.
  7120. * @param {number} [depth=1] - The depth of the texture.
  7121. */
  7122. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7123. super( null );
  7124. /**
  7125. * This flag can be used for type testing.
  7126. *
  7127. * @type {boolean}
  7128. * @readonly
  7129. * @default true
  7130. */
  7131. this.isDataArrayTexture = true;
  7132. /**
  7133. * The image definition of a data texture.
  7134. *
  7135. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7136. */
  7137. this.image = { data, width, height, depth };
  7138. /**
  7139. * How the texture is sampled when a texel covers more than one pixel.
  7140. *
  7141. * Overwritten and set to `NearestFilter` by default.
  7142. *
  7143. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7144. * @default NearestFilter
  7145. */
  7146. this.magFilter = NearestFilter;
  7147. /**
  7148. * How the texture is sampled when a texel covers less than one pixel.
  7149. *
  7150. * Overwritten and set to `NearestFilter` by default.
  7151. *
  7152. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7153. * @default NearestFilter
  7154. */
  7155. this.minFilter = NearestFilter;
  7156. /**
  7157. * This defines how the texture is wrapped in the depth and corresponds to
  7158. * *W* in UVW mapping.
  7159. *
  7160. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7161. * @default ClampToEdgeWrapping
  7162. */
  7163. this.wrapR = ClampToEdgeWrapping;
  7164. /**
  7165. * Whether to generate mipmaps (if possible) for a texture.
  7166. *
  7167. * Overwritten and set to `false` by default.
  7168. *
  7169. * @type {boolean}
  7170. * @default false
  7171. */
  7172. this.generateMipmaps = false;
  7173. /**
  7174. * If set to `true`, the texture is flipped along the vertical axis when
  7175. * uploaded to the GPU.
  7176. *
  7177. * Overwritten and set to `false` by default.
  7178. *
  7179. * @type {boolean}
  7180. * @default false
  7181. */
  7182. this.flipY = false;
  7183. /**
  7184. * Specifies the alignment requirements for the start of each pixel row in memory.
  7185. *
  7186. * Overwritten and set to `1` by default.
  7187. *
  7188. * @type {boolean}
  7189. * @default 1
  7190. */
  7191. this.unpackAlignment = 1;
  7192. /**
  7193. * A set of all layers which need to be updated in the texture.
  7194. *
  7195. * @type {Set<number>}
  7196. */
  7197. this.layerUpdates = new Set();
  7198. }
  7199. /**
  7200. * Describes that a specific layer of the texture needs to be updated.
  7201. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7202. * entire data texture array is sent to the GPU. Marking specific
  7203. * layers will only transmit subsets of all mipmaps associated with a
  7204. * specific depth in the array which is often much more performant.
  7205. *
  7206. * @param {number} layerIndex - The layer index that should be updated.
  7207. */
  7208. addLayerUpdate( layerIndex ) {
  7209. this.layerUpdates.add( layerIndex );
  7210. }
  7211. /**
  7212. * Resets the layer updates registry.
  7213. */
  7214. clearLayerUpdates() {
  7215. this.layerUpdates.clear();
  7216. }
  7217. }
  7218. /**
  7219. * An array render target used in context of {@link WebGLRenderer}.
  7220. *
  7221. * @augments WebGLRenderTarget
  7222. */
  7223. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7224. /**
  7225. * Constructs a new array render target.
  7226. *
  7227. * @param {number} [width=1] - The width of the render target.
  7228. * @param {number} [height=1] - The height of the render target.
  7229. * @param {number} [depth=1] - The height of the render target.
  7230. * @param {RenderTarget~Options} [options] - The configuration object.
  7231. */
  7232. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7233. super( width, height, options );
  7234. /**
  7235. * This flag can be used for type testing.
  7236. *
  7237. * @type {boolean}
  7238. * @readonly
  7239. * @default true
  7240. */
  7241. this.isWebGLArrayRenderTarget = true;
  7242. this.depth = depth;
  7243. /**
  7244. * Overwritten with a different texture type.
  7245. *
  7246. * @type {DataArrayTexture}
  7247. */
  7248. this.texture = new DataArrayTexture( null, width, height, depth );
  7249. this._setTextureOptions( options );
  7250. this.texture.isRenderTargetTexture = true;
  7251. }
  7252. }
  7253. /**
  7254. * Creates a three-dimensional texture from raw data, with parameters to
  7255. * divide it into width, height, and depth.
  7256. *
  7257. * @augments Texture
  7258. */
  7259. class Data3DTexture extends Texture {
  7260. /**
  7261. * Constructs a new data array texture.
  7262. *
  7263. * @param {?TypedArray} [data=null] - The buffer data.
  7264. * @param {number} [width=1] - The width of the texture.
  7265. * @param {number} [height=1] - The height of the texture.
  7266. * @param {number} [depth=1] - The depth of the texture.
  7267. */
  7268. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7269. // We're going to add .setXXX() methods for setting properties later.
  7270. // Users can still set in Data3DTexture directly.
  7271. //
  7272. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7273. // texture.anisotropy = 16;
  7274. //
  7275. // See #14839
  7276. super( null );
  7277. /**
  7278. * This flag can be used for type testing.
  7279. *
  7280. * @type {boolean}
  7281. * @readonly
  7282. * @default true
  7283. */
  7284. this.isData3DTexture = true;
  7285. /**
  7286. * The image definition of a data texture.
  7287. *
  7288. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7289. */
  7290. this.image = { data, width, height, depth };
  7291. /**
  7292. * How the texture is sampled when a texel covers more than one pixel.
  7293. *
  7294. * Overwritten and set to `NearestFilter` by default.
  7295. *
  7296. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7297. * @default NearestFilter
  7298. */
  7299. this.magFilter = NearestFilter;
  7300. /**
  7301. * How the texture is sampled when a texel covers less than one pixel.
  7302. *
  7303. * Overwritten and set to `NearestFilter` by default.
  7304. *
  7305. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7306. * @default NearestFilter
  7307. */
  7308. this.minFilter = NearestFilter;
  7309. /**
  7310. * This defines how the texture is wrapped in the depth and corresponds to
  7311. * *W* in UVW mapping.
  7312. *
  7313. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7314. * @default ClampToEdgeWrapping
  7315. */
  7316. this.wrapR = ClampToEdgeWrapping;
  7317. /**
  7318. * Whether to generate mipmaps (if possible) for a texture.
  7319. *
  7320. * Overwritten and set to `false` by default.
  7321. *
  7322. * @type {boolean}
  7323. * @default false
  7324. */
  7325. this.generateMipmaps = false;
  7326. /**
  7327. * If set to `true`, the texture is flipped along the vertical axis when
  7328. * uploaded to the GPU.
  7329. *
  7330. * Overwritten and set to `false` by default.
  7331. *
  7332. * @type {boolean}
  7333. * @default false
  7334. */
  7335. this.flipY = false;
  7336. /**
  7337. * Specifies the alignment requirements for the start of each pixel row in memory.
  7338. *
  7339. * Overwritten and set to `1` by default.
  7340. *
  7341. * @type {boolean}
  7342. * @default 1
  7343. */
  7344. this.unpackAlignment = 1;
  7345. }
  7346. }
  7347. /**
  7348. * A 3D render target used in context of {@link WebGLRenderer}.
  7349. *
  7350. * @augments WebGLRenderTarget
  7351. */
  7352. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7353. /**
  7354. * Constructs a new 3D render target.
  7355. *
  7356. * @param {number} [width=1] - The width of the render target.
  7357. * @param {number} [height=1] - The height of the render target.
  7358. * @param {number} [depth=1] - The height of the render target.
  7359. * @param {RenderTarget~Options} [options] - The configuration object.
  7360. */
  7361. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7362. super( width, height, options );
  7363. /**
  7364. * This flag can be used for type testing.
  7365. *
  7366. * @type {boolean}
  7367. * @readonly
  7368. * @default true
  7369. */
  7370. this.isWebGL3DRenderTarget = true;
  7371. this.depth = depth;
  7372. /**
  7373. * Overwritten with a different texture type.
  7374. *
  7375. * @type {Data3DTexture}
  7376. */
  7377. this.texture = new Data3DTexture( null, width, height, depth );
  7378. this._setTextureOptions( options );
  7379. this.texture.isRenderTargetTexture = true;
  7380. }
  7381. }
  7382. /**
  7383. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7384. */
  7385. class Box3 {
  7386. /**
  7387. * Constructs a new bounding box.
  7388. *
  7389. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7390. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7391. */
  7392. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7393. /**
  7394. * This flag can be used for type testing.
  7395. *
  7396. * @type {boolean}
  7397. * @readonly
  7398. * @default true
  7399. */
  7400. this.isBox3 = true;
  7401. /**
  7402. * The lower boundary of the box.
  7403. *
  7404. * @type {Vector3}
  7405. */
  7406. this.min = min;
  7407. /**
  7408. * The upper boundary of the box.
  7409. *
  7410. * @type {Vector3}
  7411. */
  7412. this.max = max;
  7413. }
  7414. /**
  7415. * Sets the lower and upper boundaries of this box.
  7416. * Please note that this method only copies the values from the given objects.
  7417. *
  7418. * @param {Vector3} min - The lower boundary of the box.
  7419. * @param {Vector3} max - The upper boundary of the box.
  7420. * @return {Box3} A reference to this bounding box.
  7421. */
  7422. set( min, max ) {
  7423. this.min.copy( min );
  7424. this.max.copy( max );
  7425. return this;
  7426. }
  7427. /**
  7428. * Sets the upper and lower bounds of this box so it encloses the position data
  7429. * in the given array.
  7430. *
  7431. * @param {Array<number>} array - An array holding 3D position data.
  7432. * @return {Box3} A reference to this bounding box.
  7433. */
  7434. setFromArray( array ) {
  7435. this.makeEmpty();
  7436. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7437. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7438. }
  7439. return this;
  7440. }
  7441. /**
  7442. * Sets the upper and lower bounds of this box so it encloses the position data
  7443. * in the given buffer attribute.
  7444. *
  7445. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7446. * @return {Box3} A reference to this bounding box.
  7447. */
  7448. setFromBufferAttribute( attribute ) {
  7449. this.makeEmpty();
  7450. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7451. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7452. }
  7453. return this;
  7454. }
  7455. /**
  7456. * Sets the upper and lower bounds of this box so it encloses the position data
  7457. * in the given array.
  7458. *
  7459. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7460. * @return {Box3} A reference to this bounding box.
  7461. */
  7462. setFromPoints( points ) {
  7463. this.makeEmpty();
  7464. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7465. this.expandByPoint( points[ i ] );
  7466. }
  7467. return this;
  7468. }
  7469. /**
  7470. * Centers this box on the given center vector and sets this box's width, height and
  7471. * depth to the given size values.
  7472. *
  7473. * @param {Vector3} center - The center of the box.
  7474. * @param {Vector3} size - The x, y and z dimensions of the box.
  7475. * @return {Box3} A reference to this bounding box.
  7476. */
  7477. setFromCenterAndSize( center, size ) {
  7478. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7479. this.min.copy( center ).sub( halfSize );
  7480. this.max.copy( center ).add( halfSize );
  7481. return this;
  7482. }
  7483. /**
  7484. * Computes the world-axis-aligned bounding box for the given 3D object
  7485. * (including its children), accounting for the object's, and children's,
  7486. * world transforms. The function may result in a larger box than strictly necessary.
  7487. *
  7488. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7489. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7490. * world-axis-aligned bounding box at the expense of more computation.
  7491. * @return {Box3} A reference to this bounding box.
  7492. */
  7493. setFromObject( object, precise = false ) {
  7494. this.makeEmpty();
  7495. return this.expandByObject( object, precise );
  7496. }
  7497. /**
  7498. * Returns a new box with copied values from this instance.
  7499. *
  7500. * @return {Box3} A clone of this instance.
  7501. */
  7502. clone() {
  7503. return new this.constructor().copy( this );
  7504. }
  7505. /**
  7506. * Copies the values of the given box to this instance.
  7507. *
  7508. * @param {Box3} box - The box to copy.
  7509. * @return {Box3} A reference to this bounding box.
  7510. */
  7511. copy( box ) {
  7512. this.min.copy( box.min );
  7513. this.max.copy( box.max );
  7514. return this;
  7515. }
  7516. /**
  7517. * Makes this box empty which means in encloses a zero space in 3D.
  7518. *
  7519. * @return {Box3} A reference to this bounding box.
  7520. */
  7521. makeEmpty() {
  7522. this.min.x = this.min.y = this.min.z = + Infinity;
  7523. this.max.x = this.max.y = this.max.z = - Infinity;
  7524. return this;
  7525. }
  7526. /**
  7527. * Returns true if this box includes zero points within its bounds.
  7528. * Note that a box with equal lower and upper bounds still includes one
  7529. * point, the one both bounds share.
  7530. *
  7531. * @return {boolean} Whether this box is empty or not.
  7532. */
  7533. isEmpty() {
  7534. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7535. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7536. }
  7537. /**
  7538. * Returns the center point of this box.
  7539. *
  7540. * @param {Vector3} target - The target vector that is used to store the method's result.
  7541. * @return {Vector3} The center point.
  7542. */
  7543. getCenter( target ) {
  7544. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7545. }
  7546. /**
  7547. * Returns the dimensions of this box.
  7548. *
  7549. * @param {Vector3} target - The target vector that is used to store the method's result.
  7550. * @return {Vector3} The size.
  7551. */
  7552. getSize( target ) {
  7553. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7554. }
  7555. /**
  7556. * Expands the boundaries of this box to include the given point.
  7557. *
  7558. * @param {Vector3} point - The point that should be included by the bounding box.
  7559. * @return {Box3} A reference to this bounding box.
  7560. */
  7561. expandByPoint( point ) {
  7562. this.min.min( point );
  7563. this.max.max( point );
  7564. return this;
  7565. }
  7566. /**
  7567. * Expands this box equilaterally by the given vector. The width of this
  7568. * box will be expanded by the x component of the vector in both
  7569. * directions. The height of this box will be expanded by the y component of
  7570. * the vector in both directions. The depth of this box will be
  7571. * expanded by the z component of the vector in both directions.
  7572. *
  7573. * @param {Vector3} vector - The vector that should expand the bounding box.
  7574. * @return {Box3} A reference to this bounding box.
  7575. */
  7576. expandByVector( vector ) {
  7577. this.min.sub( vector );
  7578. this.max.add( vector );
  7579. return this;
  7580. }
  7581. /**
  7582. * Expands each dimension of the box by the given scalar. If negative, the
  7583. * dimensions of the box will be contracted.
  7584. *
  7585. * @param {number} scalar - The scalar value that should expand the bounding box.
  7586. * @return {Box3} A reference to this bounding box.
  7587. */
  7588. expandByScalar( scalar ) {
  7589. this.min.addScalar( - scalar );
  7590. this.max.addScalar( scalar );
  7591. return this;
  7592. }
  7593. /**
  7594. * Expands the boundaries of this box to include the given 3D object and
  7595. * its children, accounting for the object's, and children's, world
  7596. * transforms. The function may result in a larger box than strictly
  7597. * necessary (unless the precise parameter is set to true).
  7598. *
  7599. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7600. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7601. * as little as necessary at the expense of more computation.
  7602. * @return {Box3} A reference to this bounding box.
  7603. */
  7604. expandByObject( object, precise = false ) {
  7605. // Computes the world-axis-aligned bounding box of an object (including its children),
  7606. // accounting for both the object's, and children's, world transforms
  7607. object.updateWorldMatrix( false, false );
  7608. const geometry = object.geometry;
  7609. if ( geometry !== undefined ) {
  7610. const positionAttribute = geometry.getAttribute( 'position' );
  7611. // precise AABB computation based on vertex data requires at least a position attribute.
  7612. // instancing isn't supported so far and uses the normal (conservative) code path.
  7613. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7614. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7615. if ( object.isMesh === true ) {
  7616. object.getVertexPosition( i, _vector$b );
  7617. } else {
  7618. _vector$b.fromBufferAttribute( positionAttribute, i );
  7619. }
  7620. _vector$b.applyMatrix4( object.matrixWorld );
  7621. this.expandByPoint( _vector$b );
  7622. }
  7623. } else {
  7624. if ( object.boundingBox !== undefined ) {
  7625. // object-level bounding box
  7626. if ( object.boundingBox === null ) {
  7627. object.computeBoundingBox();
  7628. }
  7629. _box$4.copy( object.boundingBox );
  7630. } else {
  7631. // geometry-level bounding box
  7632. if ( geometry.boundingBox === null ) {
  7633. geometry.computeBoundingBox();
  7634. }
  7635. _box$4.copy( geometry.boundingBox );
  7636. }
  7637. _box$4.applyMatrix4( object.matrixWorld );
  7638. this.union( _box$4 );
  7639. }
  7640. }
  7641. const children = object.children;
  7642. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7643. this.expandByObject( children[ i ], precise );
  7644. }
  7645. return this;
  7646. }
  7647. /**
  7648. * Returns `true` if the given point lies within or on the boundaries of this box.
  7649. *
  7650. * @param {Vector3} point - The point to test.
  7651. * @return {boolean} Whether the bounding box contains the given point or not.
  7652. */
  7653. containsPoint( point ) {
  7654. return point.x >= this.min.x && point.x <= this.max.x &&
  7655. point.y >= this.min.y && point.y <= this.max.y &&
  7656. point.z >= this.min.z && point.z <= this.max.z;
  7657. }
  7658. /**
  7659. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7660. * If this box and the given one are identical, this function also returns `true`.
  7661. *
  7662. * @param {Box3} box - The bounding box to test.
  7663. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7664. */
  7665. containsBox( box ) {
  7666. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7667. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7668. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7669. }
  7670. /**
  7671. * Returns a point as a proportion of this box's width, height and depth.
  7672. *
  7673. * @param {Vector3} point - A point in 3D space.
  7674. * @param {Vector3} target - The target vector that is used to store the method's result.
  7675. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7676. */
  7677. getParameter( point, target ) {
  7678. // This can potentially have a divide by zero if the box
  7679. // has a size dimension of 0.
  7680. return target.set(
  7681. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7682. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7683. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7684. );
  7685. }
  7686. /**
  7687. * Returns `true` if the given bounding box intersects with this bounding box.
  7688. *
  7689. * @param {Box3} box - The bounding box to test.
  7690. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7691. */
  7692. intersectsBox( box ) {
  7693. // using 6 splitting planes to rule out intersections.
  7694. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7695. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7696. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7697. }
  7698. /**
  7699. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7700. *
  7701. * @param {Sphere} sphere - The bounding sphere to test.
  7702. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7703. */
  7704. intersectsSphere( sphere ) {
  7705. // Find the point on the AABB closest to the sphere center.
  7706. this.clampPoint( sphere.center, _vector$b );
  7707. // If that point is inside the sphere, the AABB and sphere intersect.
  7708. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7709. }
  7710. /**
  7711. * Returns `true` if the given plane intersects with this bounding box.
  7712. *
  7713. * @param {Plane} plane - The plane to test.
  7714. * @return {boolean} Whether the given plane intersects with this bounding box.
  7715. */
  7716. intersectsPlane( plane ) {
  7717. // We compute the minimum and maximum dot product values. If those values
  7718. // are on the same side (back or front) of the plane, then there is no intersection.
  7719. let min, max;
  7720. if ( plane.normal.x > 0 ) {
  7721. min = plane.normal.x * this.min.x;
  7722. max = plane.normal.x * this.max.x;
  7723. } else {
  7724. min = plane.normal.x * this.max.x;
  7725. max = plane.normal.x * this.min.x;
  7726. }
  7727. if ( plane.normal.y > 0 ) {
  7728. min += plane.normal.y * this.min.y;
  7729. max += plane.normal.y * this.max.y;
  7730. } else {
  7731. min += plane.normal.y * this.max.y;
  7732. max += plane.normal.y * this.min.y;
  7733. }
  7734. if ( plane.normal.z > 0 ) {
  7735. min += plane.normal.z * this.min.z;
  7736. max += plane.normal.z * this.max.z;
  7737. } else {
  7738. min += plane.normal.z * this.max.z;
  7739. max += plane.normal.z * this.min.z;
  7740. }
  7741. return ( min <= - plane.constant && max >= - plane.constant );
  7742. }
  7743. /**
  7744. * Returns `true` if the given triangle intersects with this bounding box.
  7745. *
  7746. * @param {Triangle} triangle - The triangle to test.
  7747. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7748. */
  7749. intersectsTriangle( triangle ) {
  7750. if ( this.isEmpty() ) {
  7751. return false;
  7752. }
  7753. // compute box center and extents
  7754. this.getCenter( _center );
  7755. _extents.subVectors( this.max, _center );
  7756. // translate triangle to aabb origin
  7757. _v0$3.subVectors( triangle.a, _center );
  7758. _v1$7.subVectors( triangle.b, _center );
  7759. _v2$4.subVectors( triangle.c, _center );
  7760. // compute edge vectors for triangle
  7761. _f0.subVectors( _v1$7, _v0$3 );
  7762. _f1.subVectors( _v2$4, _v1$7 );
  7763. _f2.subVectors( _v0$3, _v2$4 );
  7764. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7765. // 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
  7766. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7767. let axes = [
  7768. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7769. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7770. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7771. ];
  7772. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7773. return false;
  7774. }
  7775. // test 3 face normals from the aabb
  7776. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7777. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7778. return false;
  7779. }
  7780. // finally testing the face normal of the triangle
  7781. // use already existing triangle edge vectors here
  7782. _triangleNormal.crossVectors( _f0, _f1 );
  7783. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7784. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7785. }
  7786. /**
  7787. * Clamps the given point within the bounds of this box.
  7788. *
  7789. * @param {Vector3} point - The point to clamp.
  7790. * @param {Vector3} target - The target vector that is used to store the method's result.
  7791. * @return {Vector3} The clamped point.
  7792. */
  7793. clampPoint( point, target ) {
  7794. return target.copy( point ).clamp( this.min, this.max );
  7795. }
  7796. /**
  7797. * Returns the euclidean distance from any edge of this box to the specified point. If
  7798. * the given point lies inside of this box, the distance will be `0`.
  7799. *
  7800. * @param {Vector3} point - The point to compute the distance to.
  7801. * @return {number} The euclidean distance.
  7802. */
  7803. distanceToPoint( point ) {
  7804. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7805. }
  7806. /**
  7807. * Returns a bounding sphere that encloses this bounding box.
  7808. *
  7809. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7810. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7811. */
  7812. getBoundingSphere( target ) {
  7813. if ( this.isEmpty() ) {
  7814. target.makeEmpty();
  7815. } else {
  7816. this.getCenter( target.center );
  7817. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7818. }
  7819. return target;
  7820. }
  7821. /**
  7822. * Computes the intersection of this bounding box and the given one, setting the upper
  7823. * bound of this box to the lesser of the two boxes' upper bounds and the
  7824. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7825. * there's no overlap, makes this box empty.
  7826. *
  7827. * @param {Box3} box - The bounding box to intersect with.
  7828. * @return {Box3} A reference to this bounding box.
  7829. */
  7830. intersect( box ) {
  7831. this.min.max( box.min );
  7832. this.max.min( box.max );
  7833. // 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.
  7834. if ( this.isEmpty() ) this.makeEmpty();
  7835. return this;
  7836. }
  7837. /**
  7838. * Computes the union of this box and another and the given one, setting the upper
  7839. * bound of this box to the greater of the two boxes' upper bounds and the
  7840. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7841. *
  7842. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7843. * @return {Box3} A reference to this bounding box.
  7844. */
  7845. union( box ) {
  7846. this.min.min( box.min );
  7847. this.max.max( box.max );
  7848. return this;
  7849. }
  7850. /**
  7851. * Transforms this bounding box by the given 4x4 transformation matrix.
  7852. *
  7853. * @param {Matrix4} matrix - The transformation matrix.
  7854. * @return {Box3} A reference to this bounding box.
  7855. */
  7856. applyMatrix4( matrix ) {
  7857. // transform of empty box is an empty box.
  7858. if ( this.isEmpty() ) return this;
  7859. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7860. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7861. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7862. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7863. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7864. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7865. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7866. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7867. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7868. this.setFromPoints( _points );
  7869. return this;
  7870. }
  7871. /**
  7872. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7873. * effectively moving it in 3D space.
  7874. *
  7875. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7876. * @return {Box3} A reference to this bounding box.
  7877. */
  7878. translate( offset ) {
  7879. this.min.add( offset );
  7880. this.max.add( offset );
  7881. return this;
  7882. }
  7883. /**
  7884. * Returns `true` if this bounding box is equal with the given one.
  7885. *
  7886. * @param {Box3} box - The box to test for equality.
  7887. * @return {boolean} Whether this bounding box is equal with the given one.
  7888. */
  7889. equals( box ) {
  7890. return box.min.equals( this.min ) && box.max.equals( this.max );
  7891. }
  7892. /**
  7893. * Returns a serialized structure of the bounding box.
  7894. *
  7895. * @return {Object} Serialized structure with fields representing the object state.
  7896. */
  7897. toJSON() {
  7898. return {
  7899. min: this.min.toArray(),
  7900. max: this.max.toArray()
  7901. };
  7902. }
  7903. /**
  7904. * Returns a serialized structure of the bounding box.
  7905. *
  7906. * @param {Object} json - The serialized json to set the box from.
  7907. * @return {Box3} A reference to this bounding box.
  7908. */
  7909. fromJSON( json ) {
  7910. this.min.fromArray( json.min );
  7911. this.max.fromArray( json.max );
  7912. return this;
  7913. }
  7914. }
  7915. const _points = [
  7916. /*@__PURE__*/ new Vector3(),
  7917. /*@__PURE__*/ new Vector3(),
  7918. /*@__PURE__*/ new Vector3(),
  7919. /*@__PURE__*/ new Vector3(),
  7920. /*@__PURE__*/ new Vector3(),
  7921. /*@__PURE__*/ new Vector3(),
  7922. /*@__PURE__*/ new Vector3(),
  7923. /*@__PURE__*/ new Vector3()
  7924. ];
  7925. const _vector$b = /*@__PURE__*/ new Vector3();
  7926. const _box$4 = /*@__PURE__*/ new Box3();
  7927. // triangle centered vertices
  7928. const _v0$3 = /*@__PURE__*/ new Vector3();
  7929. const _v1$7 = /*@__PURE__*/ new Vector3();
  7930. const _v2$4 = /*@__PURE__*/ new Vector3();
  7931. // triangle edge vectors
  7932. const _f0 = /*@__PURE__*/ new Vector3();
  7933. const _f1 = /*@__PURE__*/ new Vector3();
  7934. const _f2 = /*@__PURE__*/ new Vector3();
  7935. const _center = /*@__PURE__*/ new Vector3();
  7936. const _extents = /*@__PURE__*/ new Vector3();
  7937. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7938. const _testAxis = /*@__PURE__*/ new Vector3();
  7939. function satForAxes( axes, v0, v1, v2, extents ) {
  7940. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7941. _testAxis.fromArray( axes, i );
  7942. // project the aabb onto the separating axis
  7943. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7944. // project all 3 vertices of the triangle onto the separating axis
  7945. const p0 = v0.dot( _testAxis );
  7946. const p1 = v1.dot( _testAxis );
  7947. const p2 = v2.dot( _testAxis );
  7948. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7949. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7950. // points of the projected triangle are outside the projected half-length of the aabb
  7951. // the axis is separating and we can exit
  7952. return false;
  7953. }
  7954. }
  7955. return true;
  7956. }
  7957. const _box$3 = /*@__PURE__*/ new Box3();
  7958. const _v1$6 = /*@__PURE__*/ new Vector3();
  7959. const _v2$3 = /*@__PURE__*/ new Vector3();
  7960. /**
  7961. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7962. * used as a Bounding Sphere for 3D objects.
  7963. */
  7964. class Sphere {
  7965. /**
  7966. * Constructs a new sphere.
  7967. *
  7968. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7969. * @param {number} [radius=-1] - The radius of the sphere.
  7970. */
  7971. constructor( center = new Vector3(), radius = -1 ) {
  7972. /**
  7973. * This flag can be used for type testing.
  7974. *
  7975. * @type {boolean}
  7976. * @readonly
  7977. * @default true
  7978. */
  7979. this.isSphere = true;
  7980. /**
  7981. * The center of the sphere
  7982. *
  7983. * @type {Vector3}
  7984. */
  7985. this.center = center;
  7986. /**
  7987. * The radius of the sphere.
  7988. *
  7989. * @type {number}
  7990. */
  7991. this.radius = radius;
  7992. }
  7993. /**
  7994. * Sets the sphere's components by copying the given values.
  7995. *
  7996. * @param {Vector3} center - The center.
  7997. * @param {number} radius - The radius.
  7998. * @return {Sphere} A reference to this sphere.
  7999. */
  8000. set( center, radius ) {
  8001. this.center.copy( center );
  8002. this.radius = radius;
  8003. return this;
  8004. }
  8005. /**
  8006. * Computes the minimum bounding sphere for list of points.
  8007. * If the optional center point is given, it is used as the sphere's
  8008. * center. Otherwise, the center of the axis-aligned bounding box
  8009. * encompassing the points is calculated.
  8010. *
  8011. * @param {Array<Vector3>} points - A list of points in 3D space.
  8012. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8013. * @return {Sphere} A reference to this sphere.
  8014. */
  8015. setFromPoints( points, optionalCenter ) {
  8016. const center = this.center;
  8017. if ( optionalCenter !== undefined ) {
  8018. center.copy( optionalCenter );
  8019. } else {
  8020. _box$3.setFromPoints( points ).getCenter( center );
  8021. }
  8022. let maxRadiusSq = 0;
  8023. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8024. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8025. }
  8026. this.radius = Math.sqrt( maxRadiusSq );
  8027. return this;
  8028. }
  8029. /**
  8030. * Copies the values of the given sphere to this instance.
  8031. *
  8032. * @param {Sphere} sphere - The sphere to copy.
  8033. * @return {Sphere} A reference to this sphere.
  8034. */
  8035. copy( sphere ) {
  8036. this.center.copy( sphere.center );
  8037. this.radius = sphere.radius;
  8038. return this;
  8039. }
  8040. /**
  8041. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8042. *
  8043. * Spheres with a radius of `0` contain only their center point and are not
  8044. * considered to be empty.
  8045. *
  8046. * @return {boolean} Whether this sphere is empty or not.
  8047. */
  8048. isEmpty() {
  8049. return ( this.radius < 0 );
  8050. }
  8051. /**
  8052. * Makes this sphere empty which means in encloses a zero space in 3D.
  8053. *
  8054. * @return {Sphere} A reference to this sphere.
  8055. */
  8056. makeEmpty() {
  8057. this.center.set( 0, 0, 0 );
  8058. this.radius = -1;
  8059. return this;
  8060. }
  8061. /**
  8062. * Returns `true` if this sphere contains the given point inclusive of
  8063. * the surface of the sphere.
  8064. *
  8065. * @param {Vector3} point - The point to check.
  8066. * @return {boolean} Whether this sphere contains the given point or not.
  8067. */
  8068. containsPoint( point ) {
  8069. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8070. }
  8071. /**
  8072. * Returns the closest distance from the boundary of the sphere to the
  8073. * given point. If the sphere contains the point, the distance will
  8074. * be negative.
  8075. *
  8076. * @param {Vector3} point - The point to compute the distance to.
  8077. * @return {number} The distance to the point.
  8078. */
  8079. distanceToPoint( point ) {
  8080. return ( point.distanceTo( this.center ) - this.radius );
  8081. }
  8082. /**
  8083. * Returns `true` if this sphere intersects with the given one.
  8084. *
  8085. * @param {Sphere} sphere - The sphere to test.
  8086. * @return {boolean} Whether this sphere intersects with the given one or not.
  8087. */
  8088. intersectsSphere( sphere ) {
  8089. const radiusSum = this.radius + sphere.radius;
  8090. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8091. }
  8092. /**
  8093. * Returns `true` if this sphere intersects with the given box.
  8094. *
  8095. * @param {Box3} box - The box to test.
  8096. * @return {boolean} Whether this sphere intersects with the given box or not.
  8097. */
  8098. intersectsBox( box ) {
  8099. return box.intersectsSphere( this );
  8100. }
  8101. /**
  8102. * Returns `true` if this sphere intersects with the given plane.
  8103. *
  8104. * @param {Plane} plane - The plane to test.
  8105. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8106. */
  8107. intersectsPlane( plane ) {
  8108. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8109. }
  8110. /**
  8111. * Clamps a point within the sphere. If the point is outside the sphere, it
  8112. * will clamp it to the closest point on the edge of the sphere. Points
  8113. * already inside the sphere will not be affected.
  8114. *
  8115. * @param {Vector3} point - The plane to clamp.
  8116. * @param {Vector3} target - The target vector that is used to store the method's result.
  8117. * @return {Vector3} The clamped point.
  8118. */
  8119. clampPoint( point, target ) {
  8120. const deltaLengthSq = this.center.distanceToSquared( point );
  8121. target.copy( point );
  8122. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8123. target.sub( this.center ).normalize();
  8124. target.multiplyScalar( this.radius ).add( this.center );
  8125. }
  8126. return target;
  8127. }
  8128. /**
  8129. * Returns a bounding box that encloses this sphere.
  8130. *
  8131. * @param {Box3} target - The target box that is used to store the method's result.
  8132. * @return {Box3} The bounding box that encloses this sphere.
  8133. */
  8134. getBoundingBox( target ) {
  8135. if ( this.isEmpty() ) {
  8136. // Empty sphere produces empty bounding box
  8137. target.makeEmpty();
  8138. return target;
  8139. }
  8140. target.set( this.center, this.center );
  8141. target.expandByScalar( this.radius );
  8142. return target;
  8143. }
  8144. /**
  8145. * Transforms this sphere with the given 4x4 transformation matrix.
  8146. *
  8147. * @param {Matrix4} matrix - The transformation matrix.
  8148. * @return {Sphere} A reference to this sphere.
  8149. */
  8150. applyMatrix4( matrix ) {
  8151. this.center.applyMatrix4( matrix );
  8152. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8153. return this;
  8154. }
  8155. /**
  8156. * Translates the sphere's center by the given offset.
  8157. *
  8158. * @param {Vector3} offset - The offset.
  8159. * @return {Sphere} A reference to this sphere.
  8160. */
  8161. translate( offset ) {
  8162. this.center.add( offset );
  8163. return this;
  8164. }
  8165. /**
  8166. * Expands the boundaries of this sphere to include the given point.
  8167. *
  8168. * @param {Vector3} point - The point to include.
  8169. * @return {Sphere} A reference to this sphere.
  8170. */
  8171. expandByPoint( point ) {
  8172. if ( this.isEmpty() ) {
  8173. this.center.copy( point );
  8174. this.radius = 0;
  8175. return this;
  8176. }
  8177. _v1$6.subVectors( point, this.center );
  8178. const lengthSq = _v1$6.lengthSq();
  8179. if ( lengthSq > ( this.radius * this.radius ) ) {
  8180. // calculate the minimal sphere
  8181. const length = Math.sqrt( lengthSq );
  8182. const delta = ( length - this.radius ) * 0.5;
  8183. this.center.addScaledVector( _v1$6, delta / length );
  8184. this.radius += delta;
  8185. }
  8186. return this;
  8187. }
  8188. /**
  8189. * Expands this sphere to enclose both the original sphere and the given sphere.
  8190. *
  8191. * @param {Sphere} sphere - The sphere to include.
  8192. * @return {Sphere} A reference to this sphere.
  8193. */
  8194. union( sphere ) {
  8195. if ( sphere.isEmpty() ) {
  8196. return this;
  8197. }
  8198. if ( this.isEmpty() ) {
  8199. this.copy( sphere );
  8200. return this;
  8201. }
  8202. if ( this.center.equals( sphere.center ) === true ) {
  8203. this.radius = Math.max( this.radius, sphere.radius );
  8204. } else {
  8205. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8206. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8207. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8208. }
  8209. return this;
  8210. }
  8211. /**
  8212. * Returns `true` if this sphere is equal with the given one.
  8213. *
  8214. * @param {Sphere} sphere - The sphere to test for equality.
  8215. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8216. */
  8217. equals( sphere ) {
  8218. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8219. }
  8220. /**
  8221. * Returns a new sphere with copied values from this instance.
  8222. *
  8223. * @return {Sphere} A clone of this instance.
  8224. */
  8225. clone() {
  8226. return new this.constructor().copy( this );
  8227. }
  8228. /**
  8229. * Returns a serialized structure of the bounding sphere.
  8230. *
  8231. * @return {Object} Serialized structure with fields representing the object state.
  8232. */
  8233. toJSON() {
  8234. return {
  8235. radius: this.radius,
  8236. center: this.center.toArray()
  8237. };
  8238. }
  8239. /**
  8240. * Returns a serialized structure of the bounding sphere.
  8241. *
  8242. * @param {Object} json - The serialized json to set the sphere from.
  8243. * @return {Sphere} A reference to this bounding sphere.
  8244. */
  8245. fromJSON( json ) {
  8246. this.radius = json.radius;
  8247. this.center.fromArray( json.center );
  8248. return this;
  8249. }
  8250. }
  8251. const _vector$a = /*@__PURE__*/ new Vector3();
  8252. const _segCenter = /*@__PURE__*/ new Vector3();
  8253. const _segDir = /*@__PURE__*/ new Vector3();
  8254. const _diff = /*@__PURE__*/ new Vector3();
  8255. const _edge1 = /*@__PURE__*/ new Vector3();
  8256. const _edge2 = /*@__PURE__*/ new Vector3();
  8257. const _normal$1 = /*@__PURE__*/ new Vector3();
  8258. /**
  8259. * A ray that emits from an origin in a certain direction. The class is used by
  8260. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8261. * mouse picking (working out what objects in the 3D space the mouse is over)
  8262. * amongst other things.
  8263. */
  8264. class Ray {
  8265. /**
  8266. * Constructs a new ray.
  8267. *
  8268. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8269. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8270. */
  8271. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8272. /**
  8273. * The origin of the ray.
  8274. *
  8275. * @type {Vector3}
  8276. */
  8277. this.origin = origin;
  8278. /**
  8279. * The (normalized) direction of the ray.
  8280. *
  8281. * @type {Vector3}
  8282. */
  8283. this.direction = direction;
  8284. }
  8285. /**
  8286. * Sets the ray's components by copying the given values.
  8287. *
  8288. * @param {Vector3} origin - The origin.
  8289. * @param {Vector3} direction - The direction.
  8290. * @return {Ray} A reference to this ray.
  8291. */
  8292. set( origin, direction ) {
  8293. this.origin.copy( origin );
  8294. this.direction.copy( direction );
  8295. return this;
  8296. }
  8297. /**
  8298. * Copies the values of the given ray to this instance.
  8299. *
  8300. * @param {Ray} ray - The ray to copy.
  8301. * @return {Ray} A reference to this ray.
  8302. */
  8303. copy( ray ) {
  8304. this.origin.copy( ray.origin );
  8305. this.direction.copy( ray.direction );
  8306. return this;
  8307. }
  8308. /**
  8309. * Returns a vector that is located at a given distance along this ray.
  8310. *
  8311. * @param {number} t - The distance along the ray to retrieve a position for.
  8312. * @param {Vector3} target - The target vector that is used to store the method's result.
  8313. * @return {Vector3} A position on the ray.
  8314. */
  8315. at( t, target ) {
  8316. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8317. }
  8318. /**
  8319. * Adjusts the direction of the ray to point at the given vector in world space.
  8320. *
  8321. * @param {Vector3} v - The target position.
  8322. * @return {Ray} A reference to this ray.
  8323. */
  8324. lookAt( v ) {
  8325. this.direction.copy( v ).sub( this.origin ).normalize();
  8326. return this;
  8327. }
  8328. /**
  8329. * Shift the origin of this ray along its direction by the given distance.
  8330. *
  8331. * @param {number} t - The distance along the ray to interpolate.
  8332. * @return {Ray} A reference to this ray.
  8333. */
  8334. recast( t ) {
  8335. this.origin.copy( this.at( t, _vector$a ) );
  8336. return this;
  8337. }
  8338. /**
  8339. * Returns the point along this ray that is closest to the given point.
  8340. *
  8341. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8342. * @param {Vector3} target - The target vector that is used to store the method's result.
  8343. * @return {Vector3} The closest point on this ray.
  8344. */
  8345. closestPointToPoint( point, target ) {
  8346. target.subVectors( point, this.origin );
  8347. const directionDistance = target.dot( this.direction );
  8348. if ( directionDistance < 0 ) {
  8349. return target.copy( this.origin );
  8350. }
  8351. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8352. }
  8353. /**
  8354. * Returns the distance of the closest approach between this ray and the given point.
  8355. *
  8356. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8357. * @return {number} The distance.
  8358. */
  8359. distanceToPoint( point ) {
  8360. return Math.sqrt( this.distanceSqToPoint( point ) );
  8361. }
  8362. /**
  8363. * Returns the squared distance of the closest approach between this ray and the given point.
  8364. *
  8365. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8366. * @return {number} The squared distance.
  8367. */
  8368. distanceSqToPoint( point ) {
  8369. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8370. // point behind the ray
  8371. if ( directionDistance < 0 ) {
  8372. return this.origin.distanceToSquared( point );
  8373. }
  8374. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8375. return _vector$a.distanceToSquared( point );
  8376. }
  8377. /**
  8378. * Returns the squared distance between this ray and the given line segment.
  8379. *
  8380. * @param {Vector3} v0 - The start point of the line segment.
  8381. * @param {Vector3} v1 - The end point of the line segment.
  8382. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8383. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8384. * @return {number} The squared distance.
  8385. */
  8386. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8387. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8388. // It returns the min distance between the ray and the segment
  8389. // defined by v0 and v1
  8390. // It can also set two optional targets :
  8391. // - The closest point on the ray
  8392. // - The closest point on the segment
  8393. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8394. _segDir.copy( v1 ).sub( v0 ).normalize();
  8395. _diff.copy( this.origin ).sub( _segCenter );
  8396. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8397. const a01 = - this.direction.dot( _segDir );
  8398. const b0 = _diff.dot( this.direction );
  8399. const b1 = - _diff.dot( _segDir );
  8400. const c = _diff.lengthSq();
  8401. const det = Math.abs( 1 - a01 * a01 );
  8402. let s0, s1, sqrDist, extDet;
  8403. if ( det > 0 ) {
  8404. // The ray and segment are not parallel.
  8405. s0 = a01 * b1 - b0;
  8406. s1 = a01 * b0 - b1;
  8407. extDet = segExtent * det;
  8408. if ( s0 >= 0 ) {
  8409. if ( s1 >= - extDet ) {
  8410. if ( s1 <= extDet ) {
  8411. // region 0
  8412. // Minimum at interior points of ray and segment.
  8413. const invDet = 1 / det;
  8414. s0 *= invDet;
  8415. s1 *= invDet;
  8416. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8417. } else {
  8418. // region 1
  8419. s1 = segExtent;
  8420. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8421. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8422. }
  8423. } else {
  8424. // region 5
  8425. s1 = - segExtent;
  8426. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8427. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8428. }
  8429. } else {
  8430. if ( s1 <= - extDet ) {
  8431. // region 4
  8432. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8433. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8434. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8435. } else if ( s1 <= extDet ) {
  8436. // region 3
  8437. s0 = 0;
  8438. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8439. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8440. } else {
  8441. // region 2
  8442. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8443. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8444. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8445. }
  8446. }
  8447. } else {
  8448. // Ray and segment are parallel.
  8449. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8450. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8451. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8452. }
  8453. if ( optionalPointOnRay ) {
  8454. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8455. }
  8456. if ( optionalPointOnSegment ) {
  8457. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8458. }
  8459. return sqrDist;
  8460. }
  8461. /**
  8462. * Intersects this ray with the given sphere, returning the intersection
  8463. * point or `null` if there is no intersection.
  8464. *
  8465. * @param {Sphere} sphere - The sphere to intersect.
  8466. * @param {Vector3} target - The target vector that is used to store the method's result.
  8467. * @return {?Vector3} The intersection point.
  8468. */
  8469. intersectSphere( sphere, target ) {
  8470. _vector$a.subVectors( sphere.center, this.origin );
  8471. const tca = _vector$a.dot( this.direction );
  8472. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8473. const radius2 = sphere.radius * sphere.radius;
  8474. if ( d2 > radius2 ) return null;
  8475. const thc = Math.sqrt( radius2 - d2 );
  8476. // t0 = first intersect point - entrance on front of sphere
  8477. const t0 = tca - thc;
  8478. // t1 = second intersect point - exit point on back of sphere
  8479. const t1 = tca + thc;
  8480. // test to see if t1 is behind the ray - if so, return null
  8481. if ( t1 < 0 ) return null;
  8482. // test to see if t0 is behind the ray:
  8483. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8484. // in order to always return an intersect point that is in front of the ray.
  8485. if ( t0 < 0 ) return this.at( t1, target );
  8486. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8487. return this.at( t0, target );
  8488. }
  8489. /**
  8490. * Returns `true` if this ray intersects with the given sphere.
  8491. *
  8492. * @param {Sphere} sphere - The sphere to intersect.
  8493. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8494. */
  8495. intersectsSphere( sphere ) {
  8496. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8497. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8498. }
  8499. /**
  8500. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8501. * does not intersect with the plane.
  8502. *
  8503. * @param {Plane} plane - The plane to compute the distance to.
  8504. * @return {?number} Whether this ray intersects with the given sphere or not.
  8505. */
  8506. distanceToPlane( plane ) {
  8507. const denominator = plane.normal.dot( this.direction );
  8508. if ( denominator === 0 ) {
  8509. // line is coplanar, return origin
  8510. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8511. return 0;
  8512. }
  8513. // Null is preferable to undefined since undefined means.... it is undefined
  8514. return null;
  8515. }
  8516. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8517. // Return if the ray never intersects the plane
  8518. return t >= 0 ? t : null;
  8519. }
  8520. /**
  8521. * Intersects this ray with the given plane, returning the intersection
  8522. * point or `null` if there is no intersection.
  8523. *
  8524. * @param {Plane} plane - The plane to intersect.
  8525. * @param {Vector3} target - The target vector that is used to store the method's result.
  8526. * @return {?Vector3} The intersection point.
  8527. */
  8528. intersectPlane( plane, target ) {
  8529. const t = this.distanceToPlane( plane );
  8530. if ( t === null ) {
  8531. return null;
  8532. }
  8533. return this.at( t, target );
  8534. }
  8535. /**
  8536. * Returns `true` if this ray intersects with the given plane.
  8537. *
  8538. * @param {Plane} plane - The plane to intersect.
  8539. * @return {boolean} Whether this ray intersects with the given plane or not.
  8540. */
  8541. intersectsPlane( plane ) {
  8542. // check if the ray lies on the plane first
  8543. const distToPoint = plane.distanceToPoint( this.origin );
  8544. if ( distToPoint === 0 ) {
  8545. return true;
  8546. }
  8547. const denominator = plane.normal.dot( this.direction );
  8548. if ( denominator * distToPoint < 0 ) {
  8549. return true;
  8550. }
  8551. // ray origin is behind the plane (and is pointing behind it)
  8552. return false;
  8553. }
  8554. /**
  8555. * Intersects this ray with the given bounding box, returning the intersection
  8556. * point or `null` if there is no intersection.
  8557. *
  8558. * @param {Box3} box - The box to intersect.
  8559. * @param {Vector3} target - The target vector that is used to store the method's result.
  8560. * @return {?Vector3} The intersection point.
  8561. */
  8562. intersectBox( box, target ) {
  8563. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8564. const invdirx = 1 / this.direction.x,
  8565. invdiry = 1 / this.direction.y,
  8566. invdirz = 1 / this.direction.z;
  8567. const origin = this.origin;
  8568. if ( invdirx >= 0 ) {
  8569. tmin = ( box.min.x - origin.x ) * invdirx;
  8570. tmax = ( box.max.x - origin.x ) * invdirx;
  8571. } else {
  8572. tmin = ( box.max.x - origin.x ) * invdirx;
  8573. tmax = ( box.min.x - origin.x ) * invdirx;
  8574. }
  8575. if ( invdiry >= 0 ) {
  8576. tymin = ( box.min.y - origin.y ) * invdiry;
  8577. tymax = ( box.max.y - origin.y ) * invdiry;
  8578. } else {
  8579. tymin = ( box.max.y - origin.y ) * invdiry;
  8580. tymax = ( box.min.y - origin.y ) * invdiry;
  8581. }
  8582. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8583. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8584. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8585. if ( invdirz >= 0 ) {
  8586. tzmin = ( box.min.z - origin.z ) * invdirz;
  8587. tzmax = ( box.max.z - origin.z ) * invdirz;
  8588. } else {
  8589. tzmin = ( box.max.z - origin.z ) * invdirz;
  8590. tzmax = ( box.min.z - origin.z ) * invdirz;
  8591. }
  8592. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8593. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8594. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8595. //return point closest to the ray (positive side)
  8596. if ( tmax < 0 ) return null;
  8597. return this.at( tmin >= 0 ? tmin : tmax, target );
  8598. }
  8599. /**
  8600. * Returns `true` if this ray intersects with the given box.
  8601. *
  8602. * @param {Box3} box - The box to intersect.
  8603. * @return {boolean} Whether this ray intersects with the given box or not.
  8604. */
  8605. intersectsBox( box ) {
  8606. return this.intersectBox( box, _vector$a ) !== null;
  8607. }
  8608. /**
  8609. * Intersects this ray with the given triangle, returning the intersection
  8610. * point or `null` if there is no intersection.
  8611. *
  8612. * @param {Vector3} a - The first vertex of the triangle.
  8613. * @param {Vector3} b - The second vertex of the triangle.
  8614. * @param {Vector3} c - The third vertex of the triangle.
  8615. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8616. * @param {Vector3} target - The target vector that is used to store the method's result.
  8617. * @return {?Vector3} The intersection point.
  8618. */
  8619. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8620. // Compute the offset origin, edges, and normal.
  8621. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8622. _edge1.subVectors( b, a );
  8623. _edge2.subVectors( c, a );
  8624. _normal$1.crossVectors( _edge1, _edge2 );
  8625. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8626. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8627. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8628. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8629. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8630. let DdN = this.direction.dot( _normal$1 );
  8631. let sign;
  8632. if ( DdN > 0 ) {
  8633. if ( backfaceCulling ) return null;
  8634. sign = 1;
  8635. } else if ( DdN < 0 ) {
  8636. sign = -1;
  8637. DdN = - DdN;
  8638. } else {
  8639. return null;
  8640. }
  8641. _diff.subVectors( this.origin, a );
  8642. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8643. // b1 < 0, no intersection
  8644. if ( DdQxE2 < 0 ) {
  8645. return null;
  8646. }
  8647. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8648. // b2 < 0, no intersection
  8649. if ( DdE1xQ < 0 ) {
  8650. return null;
  8651. }
  8652. // b1+b2 > 1, no intersection
  8653. if ( DdQxE2 + DdE1xQ > DdN ) {
  8654. return null;
  8655. }
  8656. // Line intersects triangle, check if ray does.
  8657. const QdN = - sign * _diff.dot( _normal$1 );
  8658. // t < 0, no intersection
  8659. if ( QdN < 0 ) {
  8660. return null;
  8661. }
  8662. // Ray intersects triangle.
  8663. return this.at( QdN / DdN, target );
  8664. }
  8665. /**
  8666. * Transforms this ray with the given 4x4 transformation matrix.
  8667. *
  8668. * @param {Matrix4} matrix4 - The transformation matrix.
  8669. * @return {Ray} A reference to this ray.
  8670. */
  8671. applyMatrix4( matrix4 ) {
  8672. this.origin.applyMatrix4( matrix4 );
  8673. this.direction.transformDirection( matrix4 );
  8674. return this;
  8675. }
  8676. /**
  8677. * Returns `true` if this ray is equal with the given one.
  8678. *
  8679. * @param {Ray} ray - The ray to test for equality.
  8680. * @return {boolean} Whether this ray is equal with the given one.
  8681. */
  8682. equals( ray ) {
  8683. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8684. }
  8685. /**
  8686. * Returns a new ray with copied values from this instance.
  8687. *
  8688. * @return {Ray} A clone of this instance.
  8689. */
  8690. clone() {
  8691. return new this.constructor().copy( this );
  8692. }
  8693. }
  8694. /**
  8695. * Represents a 4x4 matrix.
  8696. *
  8697. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8698. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8699. *
  8700. * This allows a 3D vector representing a point in 3D space to undergo
  8701. * transformations such as translation, rotation, shear, scale, reflection,
  8702. * orthogonal or perspective projection and so on, by being multiplied by the
  8703. * matrix. This is known as `applying` the matrix to the vector.
  8704. *
  8705. * A Note on Row-Major and Column-Major Ordering:
  8706. *
  8707. * The constructor and {@link Matrix3#set} method take arguments in
  8708. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8709. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8710. * This means that calling:
  8711. * ```js
  8712. * const m = new THREE.Matrix4();
  8713. * m.set( 11, 12, 13, 14,
  8714. * 21, 22, 23, 24,
  8715. * 31, 32, 33, 34,
  8716. * 41, 42, 43, 44 );
  8717. * ```
  8718. * will result in the elements array containing:
  8719. * ```js
  8720. * m.elements = [ 11, 21, 31, 41,
  8721. * 12, 22, 32, 42,
  8722. * 13, 23, 33, 43,
  8723. * 14, 24, 34, 44 ];
  8724. * ```
  8725. * and internally all calculations are performed using column-major ordering.
  8726. * However, as the actual ordering makes no difference mathematically and
  8727. * most people are used to thinking about matrices in row-major order, the
  8728. * three.js documentation shows matrices in row-major order. Just bear in
  8729. * mind that if you are reading the source code, you'll have to take the
  8730. * transpose of any matrices outlined here to make sense of the calculations.
  8731. */
  8732. class Matrix4 {
  8733. /**
  8734. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8735. * in row-major order. If no arguments are provided, the constructor
  8736. * initializes the matrix as an identity matrix.
  8737. *
  8738. * @param {number} [n11] - 1-1 matrix element.
  8739. * @param {number} [n12] - 1-2 matrix element.
  8740. * @param {number} [n13] - 1-3 matrix element.
  8741. * @param {number} [n14] - 1-4 matrix element.
  8742. * @param {number} [n21] - 2-1 matrix element.
  8743. * @param {number} [n22] - 2-2 matrix element.
  8744. * @param {number} [n23] - 2-3 matrix element.
  8745. * @param {number} [n24] - 2-4 matrix element.
  8746. * @param {number} [n31] - 3-1 matrix element.
  8747. * @param {number} [n32] - 3-2 matrix element.
  8748. * @param {number} [n33] - 3-3 matrix element.
  8749. * @param {number} [n34] - 3-4 matrix element.
  8750. * @param {number} [n41] - 4-1 matrix element.
  8751. * @param {number} [n42] - 4-2 matrix element.
  8752. * @param {number} [n43] - 4-3 matrix element.
  8753. * @param {number} [n44] - 4-4 matrix element.
  8754. */
  8755. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8756. /**
  8757. * This flag can be used for type testing.
  8758. *
  8759. * @type {boolean}
  8760. * @readonly
  8761. * @default true
  8762. */
  8763. Matrix4.prototype.isMatrix4 = true;
  8764. /**
  8765. * A column-major list of matrix values.
  8766. *
  8767. * @type {Array<number>}
  8768. */
  8769. this.elements = [
  8770. 1, 0, 0, 0,
  8771. 0, 1, 0, 0,
  8772. 0, 0, 1, 0,
  8773. 0, 0, 0, 1
  8774. ];
  8775. if ( n11 !== undefined ) {
  8776. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8777. }
  8778. }
  8779. /**
  8780. * Sets the elements of the matrix.The arguments are supposed to be
  8781. * in row-major order.
  8782. *
  8783. * @param {number} [n11] - 1-1 matrix element.
  8784. * @param {number} [n12] - 1-2 matrix element.
  8785. * @param {number} [n13] - 1-3 matrix element.
  8786. * @param {number} [n14] - 1-4 matrix element.
  8787. * @param {number} [n21] - 2-1 matrix element.
  8788. * @param {number} [n22] - 2-2 matrix element.
  8789. * @param {number} [n23] - 2-3 matrix element.
  8790. * @param {number} [n24] - 2-4 matrix element.
  8791. * @param {number} [n31] - 3-1 matrix element.
  8792. * @param {number} [n32] - 3-2 matrix element.
  8793. * @param {number} [n33] - 3-3 matrix element.
  8794. * @param {number} [n34] - 3-4 matrix element.
  8795. * @param {number} [n41] - 4-1 matrix element.
  8796. * @param {number} [n42] - 4-2 matrix element.
  8797. * @param {number} [n43] - 4-3 matrix element.
  8798. * @param {number} [n44] - 4-4 matrix element.
  8799. * @return {Matrix4} A reference to this matrix.
  8800. */
  8801. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8802. const te = this.elements;
  8803. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8804. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8805. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8806. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8807. return this;
  8808. }
  8809. /**
  8810. * Sets this matrix to the 4x4 identity matrix.
  8811. *
  8812. * @return {Matrix4} A reference to this matrix.
  8813. */
  8814. identity() {
  8815. this.set(
  8816. 1, 0, 0, 0,
  8817. 0, 1, 0, 0,
  8818. 0, 0, 1, 0,
  8819. 0, 0, 0, 1
  8820. );
  8821. return this;
  8822. }
  8823. /**
  8824. * Returns a matrix with copied values from this instance.
  8825. *
  8826. * @return {Matrix4} A clone of this instance.
  8827. */
  8828. clone() {
  8829. return new Matrix4().fromArray( this.elements );
  8830. }
  8831. /**
  8832. * Copies the values of the given matrix to this instance.
  8833. *
  8834. * @param {Matrix4} m - The matrix to copy.
  8835. * @return {Matrix4} A reference to this matrix.
  8836. */
  8837. copy( m ) {
  8838. const te = this.elements;
  8839. const me = m.elements;
  8840. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8841. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8842. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8843. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8844. return this;
  8845. }
  8846. /**
  8847. * Copies the translation component of the given matrix
  8848. * into this matrix's translation component.
  8849. *
  8850. * @param {Matrix4} m - The matrix to copy the translation component.
  8851. * @return {Matrix4} A reference to this matrix.
  8852. */
  8853. copyPosition( m ) {
  8854. const te = this.elements, me = m.elements;
  8855. te[ 12 ] = me[ 12 ];
  8856. te[ 13 ] = me[ 13 ];
  8857. te[ 14 ] = me[ 14 ];
  8858. return this;
  8859. }
  8860. /**
  8861. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8862. *
  8863. * @param {Matrix3} m - The 3x3 matrix.
  8864. * @return {Matrix4} A reference to this matrix.
  8865. */
  8866. setFromMatrix3( m ) {
  8867. const me = m.elements;
  8868. this.set(
  8869. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8870. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8871. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8872. 0, 0, 0, 1
  8873. );
  8874. return this;
  8875. }
  8876. /**
  8877. * Extracts the basis of this matrix into the three axis vectors provided.
  8878. *
  8879. * @param {Vector3} xAxis - The basis's x axis.
  8880. * @param {Vector3} yAxis - The basis's y axis.
  8881. * @param {Vector3} zAxis - The basis's z axis.
  8882. * @return {Matrix4} A reference to this matrix.
  8883. */
  8884. extractBasis( xAxis, yAxis, zAxis ) {
  8885. if ( this.determinant() === 0 ) {
  8886. xAxis.set( 1, 0, 0 );
  8887. yAxis.set( 0, 1, 0 );
  8888. zAxis.set( 0, 0, 1 );
  8889. return this;
  8890. }
  8891. xAxis.setFromMatrixColumn( this, 0 );
  8892. yAxis.setFromMatrixColumn( this, 1 );
  8893. zAxis.setFromMatrixColumn( this, 2 );
  8894. return this;
  8895. }
  8896. /**
  8897. * Sets the given basis vectors to this matrix.
  8898. *
  8899. * @param {Vector3} xAxis - The basis's x axis.
  8900. * @param {Vector3} yAxis - The basis's y axis.
  8901. * @param {Vector3} zAxis - The basis's z axis.
  8902. * @return {Matrix4} A reference to this matrix.
  8903. */
  8904. makeBasis( xAxis, yAxis, zAxis ) {
  8905. this.set(
  8906. xAxis.x, yAxis.x, zAxis.x, 0,
  8907. xAxis.y, yAxis.y, zAxis.y, 0,
  8908. xAxis.z, yAxis.z, zAxis.z, 0,
  8909. 0, 0, 0, 1
  8910. );
  8911. return this;
  8912. }
  8913. /**
  8914. * Extracts the rotation component of the given matrix
  8915. * into this matrix's rotation component.
  8916. *
  8917. * Note: This method does not support reflection matrices.
  8918. *
  8919. * @param {Matrix4} m - The matrix.
  8920. * @return {Matrix4} A reference to this matrix.
  8921. */
  8922. extractRotation( m ) {
  8923. if ( m.determinant() === 0 ) {
  8924. return this.identity();
  8925. }
  8926. const te = this.elements;
  8927. const me = m.elements;
  8928. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8929. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8930. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8931. te[ 0 ] = me[ 0 ] * scaleX;
  8932. te[ 1 ] = me[ 1 ] * scaleX;
  8933. te[ 2 ] = me[ 2 ] * scaleX;
  8934. te[ 3 ] = 0;
  8935. te[ 4 ] = me[ 4 ] * scaleY;
  8936. te[ 5 ] = me[ 5 ] * scaleY;
  8937. te[ 6 ] = me[ 6 ] * scaleY;
  8938. te[ 7 ] = 0;
  8939. te[ 8 ] = me[ 8 ] * scaleZ;
  8940. te[ 9 ] = me[ 9 ] * scaleZ;
  8941. te[ 10 ] = me[ 10 ] * scaleZ;
  8942. te[ 11 ] = 0;
  8943. te[ 12 ] = 0;
  8944. te[ 13 ] = 0;
  8945. te[ 14 ] = 0;
  8946. te[ 15 ] = 1;
  8947. return this;
  8948. }
  8949. /**
  8950. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8951. * the rotation specified by the given Euler angles. The rest of
  8952. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8953. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  8954. * for a complete list.
  8955. *
  8956. * @param {Euler} euler - The Euler angles.
  8957. * @return {Matrix4} A reference to this matrix.
  8958. */
  8959. makeRotationFromEuler( euler ) {
  8960. const te = this.elements;
  8961. const x = euler.x, y = euler.y, z = euler.z;
  8962. const a = Math.cos( x ), b = Math.sin( x );
  8963. const c = Math.cos( y ), d = Math.sin( y );
  8964. const e = Math.cos( z ), f = Math.sin( z );
  8965. if ( euler.order === 'XYZ' ) {
  8966. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8967. te[ 0 ] = c * e;
  8968. te[ 4 ] = - c * f;
  8969. te[ 8 ] = d;
  8970. te[ 1 ] = af + be * d;
  8971. te[ 5 ] = ae - bf * d;
  8972. te[ 9 ] = - b * c;
  8973. te[ 2 ] = bf - ae * d;
  8974. te[ 6 ] = be + af * d;
  8975. te[ 10 ] = a * c;
  8976. } else if ( euler.order === 'YXZ' ) {
  8977. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8978. te[ 0 ] = ce + df * b;
  8979. te[ 4 ] = de * b - cf;
  8980. te[ 8 ] = a * d;
  8981. te[ 1 ] = a * f;
  8982. te[ 5 ] = a * e;
  8983. te[ 9 ] = - b;
  8984. te[ 2 ] = cf * b - de;
  8985. te[ 6 ] = df + ce * b;
  8986. te[ 10 ] = a * c;
  8987. } else if ( euler.order === 'ZXY' ) {
  8988. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8989. te[ 0 ] = ce - df * b;
  8990. te[ 4 ] = - a * f;
  8991. te[ 8 ] = de + cf * b;
  8992. te[ 1 ] = cf + de * b;
  8993. te[ 5 ] = a * e;
  8994. te[ 9 ] = df - ce * b;
  8995. te[ 2 ] = - a * d;
  8996. te[ 6 ] = b;
  8997. te[ 10 ] = a * c;
  8998. } else if ( euler.order === 'ZYX' ) {
  8999. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9000. te[ 0 ] = c * e;
  9001. te[ 4 ] = be * d - af;
  9002. te[ 8 ] = ae * d + bf;
  9003. te[ 1 ] = c * f;
  9004. te[ 5 ] = bf * d + ae;
  9005. te[ 9 ] = af * d - be;
  9006. te[ 2 ] = - d;
  9007. te[ 6 ] = b * c;
  9008. te[ 10 ] = a * c;
  9009. } else if ( euler.order === 'YZX' ) {
  9010. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9011. te[ 0 ] = c * e;
  9012. te[ 4 ] = bd - ac * f;
  9013. te[ 8 ] = bc * f + ad;
  9014. te[ 1 ] = f;
  9015. te[ 5 ] = a * e;
  9016. te[ 9 ] = - b * e;
  9017. te[ 2 ] = - d * e;
  9018. te[ 6 ] = ad * f + bc;
  9019. te[ 10 ] = ac - bd * f;
  9020. } else if ( euler.order === 'XZY' ) {
  9021. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9022. te[ 0 ] = c * e;
  9023. te[ 4 ] = - f;
  9024. te[ 8 ] = d * e;
  9025. te[ 1 ] = ac * f + bd;
  9026. te[ 5 ] = a * e;
  9027. te[ 9 ] = ad * f - bc;
  9028. te[ 2 ] = bc * f - ad;
  9029. te[ 6 ] = b * e;
  9030. te[ 10 ] = bd * f + ac;
  9031. }
  9032. // bottom row
  9033. te[ 3 ] = 0;
  9034. te[ 7 ] = 0;
  9035. te[ 11 ] = 0;
  9036. // last column
  9037. te[ 12 ] = 0;
  9038. te[ 13 ] = 0;
  9039. te[ 14 ] = 0;
  9040. te[ 15 ] = 1;
  9041. return this;
  9042. }
  9043. /**
  9044. * Sets the rotation component of this matrix to the rotation specified by
  9045. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9046. * The rest of the matrix is set to the identity.
  9047. *
  9048. * @param {Quaternion} q - The Quaternion.
  9049. * @return {Matrix4} A reference to this matrix.
  9050. */
  9051. makeRotationFromQuaternion( q ) {
  9052. return this.compose( _zero, q, _one );
  9053. }
  9054. /**
  9055. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9056. * `target`, and oriented by the up-direction.
  9057. *
  9058. * @param {Vector3} eye - The eye vector.
  9059. * @param {Vector3} target - The target vector.
  9060. * @param {Vector3} up - The up vector.
  9061. * @return {Matrix4} A reference to this matrix.
  9062. */
  9063. lookAt( eye, target, up ) {
  9064. const te = this.elements;
  9065. _z.subVectors( eye, target );
  9066. if ( _z.lengthSq() === 0 ) {
  9067. // eye and target are in the same position
  9068. _z.z = 1;
  9069. }
  9070. _z.normalize();
  9071. _x.crossVectors( up, _z );
  9072. if ( _x.lengthSq() === 0 ) {
  9073. // up and z are parallel
  9074. if ( Math.abs( up.z ) === 1 ) {
  9075. _z.x += 0.0001;
  9076. } else {
  9077. _z.z += 0.0001;
  9078. }
  9079. _z.normalize();
  9080. _x.crossVectors( up, _z );
  9081. }
  9082. _x.normalize();
  9083. _y.crossVectors( _z, _x );
  9084. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9085. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9086. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9087. return this;
  9088. }
  9089. /**
  9090. * Post-multiplies this matrix by the given 4x4 matrix.
  9091. *
  9092. * @param {Matrix4} m - The matrix to multiply with.
  9093. * @return {Matrix4} A reference to this matrix.
  9094. */
  9095. multiply( m ) {
  9096. return this.multiplyMatrices( this, m );
  9097. }
  9098. /**
  9099. * Pre-multiplies this matrix by the given 4x4 matrix.
  9100. *
  9101. * @param {Matrix4} m - The matrix to multiply with.
  9102. * @return {Matrix4} A reference to this matrix.
  9103. */
  9104. premultiply( m ) {
  9105. return this.multiplyMatrices( m, this );
  9106. }
  9107. /**
  9108. * Multiples the given 4x4 matrices and stores the result
  9109. * in this matrix.
  9110. *
  9111. * @param {Matrix4} a - The first matrix.
  9112. * @param {Matrix4} b - The second matrix.
  9113. * @return {Matrix4} A reference to this matrix.
  9114. */
  9115. multiplyMatrices( a, b ) {
  9116. const ae = a.elements;
  9117. const be = b.elements;
  9118. const te = this.elements;
  9119. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9120. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9121. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9122. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9123. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9124. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9125. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9126. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9127. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9128. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9129. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9130. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9131. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9132. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9133. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9134. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9135. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9136. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9137. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9138. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9139. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9140. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9141. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9142. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9143. return this;
  9144. }
  9145. /**
  9146. * Multiplies every component of the matrix by the given scalar.
  9147. *
  9148. * @param {number} s - The scalar.
  9149. * @return {Matrix4} A reference to this matrix.
  9150. */
  9151. multiplyScalar( s ) {
  9152. const te = this.elements;
  9153. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9154. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9155. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9156. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9157. return this;
  9158. }
  9159. /**
  9160. * Computes and returns the determinant of this matrix.
  9161. *
  9162. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9163. *
  9164. * @return {number} The determinant.
  9165. */
  9166. determinant() {
  9167. const te = this.elements;
  9168. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9169. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9170. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9171. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9172. const t11 = n23 * n34 - n24 * n33;
  9173. const t12 = n22 * n34 - n24 * n32;
  9174. const t13 = n22 * n33 - n23 * n32;
  9175. const t21 = n21 * n34 - n24 * n31;
  9176. const t22 = n21 * n33 - n23 * n31;
  9177. const t23 = n21 * n32 - n22 * n31;
  9178. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9179. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9180. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9181. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9182. }
  9183. /**
  9184. * Transposes this matrix in place.
  9185. *
  9186. * @return {Matrix4} A reference to this matrix.
  9187. */
  9188. transpose() {
  9189. const te = this.elements;
  9190. let tmp;
  9191. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9192. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9193. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9194. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9195. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9196. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9197. return this;
  9198. }
  9199. /**
  9200. * Sets the position component for this matrix from the given vector,
  9201. * without affecting the rest of the matrix.
  9202. *
  9203. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9204. * @param {number} y - The y component of the vector.
  9205. * @param {number} z - The z component of the vector.
  9206. * @return {Matrix4} A reference to this matrix.
  9207. */
  9208. setPosition( x, y, z ) {
  9209. const te = this.elements;
  9210. if ( x.isVector3 ) {
  9211. te[ 12 ] = x.x;
  9212. te[ 13 ] = x.y;
  9213. te[ 14 ] = x.z;
  9214. } else {
  9215. te[ 12 ] = x;
  9216. te[ 13 ] = y;
  9217. te[ 14 ] = z;
  9218. }
  9219. return this;
  9220. }
  9221. /**
  9222. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9223. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9224. * a zero matrix instead.
  9225. *
  9226. * @return {Matrix4} A reference to this matrix.
  9227. */
  9228. invert() {
  9229. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9230. const te = this.elements,
  9231. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9232. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9233. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9234. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9235. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9236. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9237. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9238. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9239. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9240. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9241. const detInv = 1 / det;
  9242. te[ 0 ] = t11 * detInv;
  9243. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9244. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9245. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9246. te[ 4 ] = t12 * detInv;
  9247. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9248. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9249. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9250. te[ 8 ] = t13 * detInv;
  9251. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9252. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9253. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9254. te[ 12 ] = t14 * detInv;
  9255. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9256. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9257. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9258. return this;
  9259. }
  9260. /**
  9261. * Multiplies the columns of this matrix by the given vector.
  9262. *
  9263. * @param {Vector3} v - The scale vector.
  9264. * @return {Matrix4} A reference to this matrix.
  9265. */
  9266. scale( v ) {
  9267. const te = this.elements;
  9268. const x = v.x, y = v.y, z = v.z;
  9269. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9270. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9271. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9272. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9273. return this;
  9274. }
  9275. /**
  9276. * Gets the maximum scale value of the three axes.
  9277. *
  9278. * @return {number} The maximum scale.
  9279. */
  9280. getMaxScaleOnAxis() {
  9281. const te = this.elements;
  9282. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9283. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9284. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9285. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9286. }
  9287. /**
  9288. * Sets this matrix as a translation transform from the given vector.
  9289. *
  9290. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9291. * @param {number} y - The amount to translate in the Y axis.
  9292. * @param {number} z - The amount to translate in the z axis.
  9293. * @return {Matrix4} A reference to this matrix.
  9294. */
  9295. makeTranslation( x, y, z ) {
  9296. if ( x.isVector3 ) {
  9297. this.set(
  9298. 1, 0, 0, x.x,
  9299. 0, 1, 0, x.y,
  9300. 0, 0, 1, x.z,
  9301. 0, 0, 0, 1
  9302. );
  9303. } else {
  9304. this.set(
  9305. 1, 0, 0, x,
  9306. 0, 1, 0, y,
  9307. 0, 0, 1, z,
  9308. 0, 0, 0, 1
  9309. );
  9310. }
  9311. return this;
  9312. }
  9313. /**
  9314. * Sets this matrix as a rotational transformation around the X axis by
  9315. * the given angle.
  9316. *
  9317. * @param {number} theta - The rotation in radians.
  9318. * @return {Matrix4} A reference to this matrix.
  9319. */
  9320. makeRotationX( theta ) {
  9321. const c = Math.cos( theta ), s = Math.sin( theta );
  9322. this.set(
  9323. 1, 0, 0, 0,
  9324. 0, c, - s, 0,
  9325. 0, s, c, 0,
  9326. 0, 0, 0, 1
  9327. );
  9328. return this;
  9329. }
  9330. /**
  9331. * Sets this matrix as a rotational transformation around the Y axis by
  9332. * the given angle.
  9333. *
  9334. * @param {number} theta - The rotation in radians.
  9335. * @return {Matrix4} A reference to this matrix.
  9336. */
  9337. makeRotationY( theta ) {
  9338. const c = Math.cos( theta ), s = Math.sin( theta );
  9339. this.set(
  9340. c, 0, s, 0,
  9341. 0, 1, 0, 0,
  9342. - s, 0, c, 0,
  9343. 0, 0, 0, 1
  9344. );
  9345. return this;
  9346. }
  9347. /**
  9348. * Sets this matrix as a rotational transformation around the Z axis by
  9349. * the given angle.
  9350. *
  9351. * @param {number} theta - The rotation in radians.
  9352. * @return {Matrix4} A reference to this matrix.
  9353. */
  9354. makeRotationZ( theta ) {
  9355. const c = Math.cos( theta ), s = Math.sin( theta );
  9356. this.set(
  9357. c, - s, 0, 0,
  9358. s, c, 0, 0,
  9359. 0, 0, 1, 0,
  9360. 0, 0, 0, 1
  9361. );
  9362. return this;
  9363. }
  9364. /**
  9365. * Sets this matrix as a rotational transformation around the given axis by
  9366. * the given angle.
  9367. *
  9368. * This is a somewhat controversial but mathematically sound alternative to
  9369. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9370. *
  9371. * @param {Vector3} axis - The normalized rotation axis.
  9372. * @param {number} angle - The rotation in radians.
  9373. * @return {Matrix4} A reference to this matrix.
  9374. */
  9375. makeRotationAxis( axis, angle ) {
  9376. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9377. const c = Math.cos( angle );
  9378. const s = Math.sin( angle );
  9379. const t = 1 - c;
  9380. const x = axis.x, y = axis.y, z = axis.z;
  9381. const tx = t * x, ty = t * y;
  9382. this.set(
  9383. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9384. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9385. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9386. 0, 0, 0, 1
  9387. );
  9388. return this;
  9389. }
  9390. /**
  9391. * Sets this matrix as a scale transformation.
  9392. *
  9393. * @param {number} x - The amount to scale in the X axis.
  9394. * @param {number} y - The amount to scale in the Y axis.
  9395. * @param {number} z - The amount to scale in the Z axis.
  9396. * @return {Matrix4} A reference to this matrix.
  9397. */
  9398. makeScale( x, y, z ) {
  9399. this.set(
  9400. x, 0, 0, 0,
  9401. 0, y, 0, 0,
  9402. 0, 0, z, 0,
  9403. 0, 0, 0, 1
  9404. );
  9405. return this;
  9406. }
  9407. /**
  9408. * Sets this matrix as a shear transformation.
  9409. *
  9410. * @param {number} xy - The amount to shear X by Y.
  9411. * @param {number} xz - The amount to shear X by Z.
  9412. * @param {number} yx - The amount to shear Y by X.
  9413. * @param {number} yz - The amount to shear Y by Z.
  9414. * @param {number} zx - The amount to shear Z by X.
  9415. * @param {number} zy - The amount to shear Z by Y.
  9416. * @return {Matrix4} A reference to this matrix.
  9417. */
  9418. makeShear( xy, xz, yx, yz, zx, zy ) {
  9419. this.set(
  9420. 1, yx, zx, 0,
  9421. xy, 1, zy, 0,
  9422. xz, yz, 1, 0,
  9423. 0, 0, 0, 1
  9424. );
  9425. return this;
  9426. }
  9427. /**
  9428. * Sets this matrix to the transformation composed of the given position,
  9429. * rotation (Quaternion) and scale.
  9430. *
  9431. * @param {Vector3} position - The position vector.
  9432. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9433. * @param {Vector3} scale - The scale vector.
  9434. * @return {Matrix4} A reference to this matrix.
  9435. */
  9436. compose( position, quaternion, scale ) {
  9437. const te = this.elements;
  9438. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9439. const x2 = x + x, y2 = y + y, z2 = z + z;
  9440. const xx = x * x2, xy = x * y2, xz = x * z2;
  9441. const yy = y * y2, yz = y * z2, zz = z * z2;
  9442. const wx = w * x2, wy = w * y2, wz = w * z2;
  9443. const sx = scale.x, sy = scale.y, sz = scale.z;
  9444. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9445. te[ 1 ] = ( xy + wz ) * sx;
  9446. te[ 2 ] = ( xz - wy ) * sx;
  9447. te[ 3 ] = 0;
  9448. te[ 4 ] = ( xy - wz ) * sy;
  9449. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9450. te[ 6 ] = ( yz + wx ) * sy;
  9451. te[ 7 ] = 0;
  9452. te[ 8 ] = ( xz + wy ) * sz;
  9453. te[ 9 ] = ( yz - wx ) * sz;
  9454. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9455. te[ 11 ] = 0;
  9456. te[ 12 ] = position.x;
  9457. te[ 13 ] = position.y;
  9458. te[ 14 ] = position.z;
  9459. te[ 15 ] = 1;
  9460. return this;
  9461. }
  9462. /**
  9463. * Decomposes this matrix into its position, rotation and scale components
  9464. * and provides the result in the given objects.
  9465. *
  9466. * Note: Not all matrices are decomposable in this way. For example, if an
  9467. * object has a non-uniformly scaled parent, then the object's world matrix
  9468. * may not be decomposable, and this method may not be appropriate.
  9469. *
  9470. * @param {Vector3} position - The position vector.
  9471. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9472. * @param {Vector3} scale - The scale vector.
  9473. * @return {Matrix4} A reference to this matrix.
  9474. */
  9475. decompose( position, quaternion, scale ) {
  9476. const te = this.elements;
  9477. position.x = te[ 12 ];
  9478. position.y = te[ 13 ];
  9479. position.z = te[ 14 ];
  9480. if ( this.determinant() === 0 ) {
  9481. scale.set( 1, 1, 1 );
  9482. quaternion.identity();
  9483. return this;
  9484. }
  9485. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9486. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9487. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9488. // if determine is negative, we need to invert one scale
  9489. const det = this.determinant();
  9490. if ( det < 0 ) sx = - sx;
  9491. // scale the rotation part
  9492. _m1$4.copy( this );
  9493. const invSX = 1 / sx;
  9494. const invSY = 1 / sy;
  9495. const invSZ = 1 / sz;
  9496. _m1$4.elements[ 0 ] *= invSX;
  9497. _m1$4.elements[ 1 ] *= invSX;
  9498. _m1$4.elements[ 2 ] *= invSX;
  9499. _m1$4.elements[ 4 ] *= invSY;
  9500. _m1$4.elements[ 5 ] *= invSY;
  9501. _m1$4.elements[ 6 ] *= invSY;
  9502. _m1$4.elements[ 8 ] *= invSZ;
  9503. _m1$4.elements[ 9 ] *= invSZ;
  9504. _m1$4.elements[ 10 ] *= invSZ;
  9505. quaternion.setFromRotationMatrix( _m1$4 );
  9506. scale.x = sx;
  9507. scale.y = sy;
  9508. scale.z = sz;
  9509. return this;
  9510. }
  9511. /**
  9512. * Creates a perspective projection matrix. This is used internally by
  9513. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9514. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9515. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9516. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9517. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9518. * @param {number} near - The distance from the camera to the near plane.
  9519. * @param {number} far - The distance from the camera to the far plane.
  9520. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9521. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9522. * @return {Matrix4} A reference to this matrix.
  9523. */
  9524. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9525. const te = this.elements;
  9526. const x = 2 * near / ( right - left );
  9527. const y = 2 * near / ( top - bottom );
  9528. const a = ( right + left ) / ( right - left );
  9529. const b = ( top + bottom ) / ( top - bottom );
  9530. let c, d;
  9531. if ( reversedDepth ) {
  9532. c = near / ( far - near );
  9533. d = ( far * near ) / ( far - near );
  9534. } else {
  9535. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9536. c = - ( far + near ) / ( far - near );
  9537. d = ( -2 * far * near ) / ( far - near );
  9538. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9539. c = - far / ( far - near );
  9540. d = ( - far * near ) / ( far - near );
  9541. } else {
  9542. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9543. }
  9544. }
  9545. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9546. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9547. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9548. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9549. return this;
  9550. }
  9551. /**
  9552. * Creates a orthographic projection matrix. This is used internally by
  9553. * {@link OrthographicCamera#updateProjectionMatrix}.
  9554. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9555. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9556. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9557. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9558. * @param {number} near - The distance from the camera to the near plane.
  9559. * @param {number} far - The distance from the camera to the far plane.
  9560. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9561. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9562. * @return {Matrix4} A reference to this matrix.
  9563. */
  9564. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9565. const te = this.elements;
  9566. const x = 2 / ( right - left );
  9567. const y = 2 / ( top - bottom );
  9568. const a = - ( right + left ) / ( right - left );
  9569. const b = - ( top + bottom ) / ( top - bottom );
  9570. let c, d;
  9571. if ( reversedDepth ) {
  9572. c = 1 / ( far - near );
  9573. d = far / ( far - near );
  9574. } else {
  9575. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9576. c = -2 / ( far - near );
  9577. d = - ( far + near ) / ( far - near );
  9578. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9579. c = -1 / ( far - near );
  9580. d = - near / ( far - near );
  9581. } else {
  9582. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9583. }
  9584. }
  9585. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9586. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9587. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9588. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9589. return this;
  9590. }
  9591. /**
  9592. * Returns `true` if this matrix is equal with the given one.
  9593. *
  9594. * @param {Matrix4} matrix - The matrix to test for equality.
  9595. * @return {boolean} Whether this matrix is equal with the given one.
  9596. */
  9597. equals( matrix ) {
  9598. const te = this.elements;
  9599. const me = matrix.elements;
  9600. for ( let i = 0; i < 16; i ++ ) {
  9601. if ( te[ i ] !== me[ i ] ) return false;
  9602. }
  9603. return true;
  9604. }
  9605. /**
  9606. * Sets the elements of the matrix from the given array.
  9607. *
  9608. * @param {Array<number>} array - The matrix elements in column-major order.
  9609. * @param {number} [offset=0] - Index of the first element in the array.
  9610. * @return {Matrix4} A reference to this matrix.
  9611. */
  9612. fromArray( array, offset = 0 ) {
  9613. for ( let i = 0; i < 16; i ++ ) {
  9614. this.elements[ i ] = array[ i + offset ];
  9615. }
  9616. return this;
  9617. }
  9618. /**
  9619. * Writes the elements of this matrix to the given array. If no array is provided,
  9620. * the method returns a new instance.
  9621. *
  9622. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9623. * @param {number} [offset=0] - Index of the first element in the array.
  9624. * @return {Array<number>} The matrix elements in column-major order.
  9625. */
  9626. toArray( array = [], offset = 0 ) {
  9627. const te = this.elements;
  9628. array[ offset ] = te[ 0 ];
  9629. array[ offset + 1 ] = te[ 1 ];
  9630. array[ offset + 2 ] = te[ 2 ];
  9631. array[ offset + 3 ] = te[ 3 ];
  9632. array[ offset + 4 ] = te[ 4 ];
  9633. array[ offset + 5 ] = te[ 5 ];
  9634. array[ offset + 6 ] = te[ 6 ];
  9635. array[ offset + 7 ] = te[ 7 ];
  9636. array[ offset + 8 ] = te[ 8 ];
  9637. array[ offset + 9 ] = te[ 9 ];
  9638. array[ offset + 10 ] = te[ 10 ];
  9639. array[ offset + 11 ] = te[ 11 ];
  9640. array[ offset + 12 ] = te[ 12 ];
  9641. array[ offset + 13 ] = te[ 13 ];
  9642. array[ offset + 14 ] = te[ 14 ];
  9643. array[ offset + 15 ] = te[ 15 ];
  9644. return array;
  9645. }
  9646. }
  9647. const _v1$5 = /*@__PURE__*/ new Vector3();
  9648. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9649. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9650. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9651. const _x = /*@__PURE__*/ new Vector3();
  9652. const _y = /*@__PURE__*/ new Vector3();
  9653. const _z = /*@__PURE__*/ new Vector3();
  9654. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9655. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9656. /**
  9657. * A class representing Euler angles.
  9658. *
  9659. * Euler angles describe a rotational transformation by rotating an object on
  9660. * its various axes in specified amounts per axis, and a specified axis
  9661. * order.
  9662. *
  9663. * Iterating through an instance will yield its components (x, y, z,
  9664. * order) in the corresponding order.
  9665. *
  9666. * ```js
  9667. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9668. * const b = new THREE.Vector3( 1, 0, 1 );
  9669. * b.applyEuler(a);
  9670. * ```
  9671. */
  9672. class Euler {
  9673. /**
  9674. * Constructs a new euler instance.
  9675. *
  9676. * @param {number} [x=0] - The angle of the x axis in radians.
  9677. * @param {number} [y=0] - The angle of the y axis in radians.
  9678. * @param {number} [z=0] - The angle of the z axis in radians.
  9679. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9680. */
  9681. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9682. /**
  9683. * This flag can be used for type testing.
  9684. *
  9685. * @type {boolean}
  9686. * @readonly
  9687. * @default true
  9688. */
  9689. this.isEuler = true;
  9690. this._x = x;
  9691. this._y = y;
  9692. this._z = z;
  9693. this._order = order;
  9694. }
  9695. /**
  9696. * The angle of the x axis in radians.
  9697. *
  9698. * @type {number}
  9699. * @default 0
  9700. */
  9701. get x() {
  9702. return this._x;
  9703. }
  9704. set x( value ) {
  9705. this._x = value;
  9706. this._onChangeCallback();
  9707. }
  9708. /**
  9709. * The angle of the y axis in radians.
  9710. *
  9711. * @type {number}
  9712. * @default 0
  9713. */
  9714. get y() {
  9715. return this._y;
  9716. }
  9717. set y( value ) {
  9718. this._y = value;
  9719. this._onChangeCallback();
  9720. }
  9721. /**
  9722. * The angle of the z axis in radians.
  9723. *
  9724. * @type {number}
  9725. * @default 0
  9726. */
  9727. get z() {
  9728. return this._z;
  9729. }
  9730. set z( value ) {
  9731. this._z = value;
  9732. this._onChangeCallback();
  9733. }
  9734. /**
  9735. * A string representing the order that the rotations are applied.
  9736. *
  9737. * @type {string}
  9738. * @default 'XYZ'
  9739. */
  9740. get order() {
  9741. return this._order;
  9742. }
  9743. set order( value ) {
  9744. this._order = value;
  9745. this._onChangeCallback();
  9746. }
  9747. /**
  9748. * Sets the Euler components.
  9749. *
  9750. * @param {number} x - The angle of the x axis in radians.
  9751. * @param {number} y - The angle of the y axis in radians.
  9752. * @param {number} z - The angle of the z axis in radians.
  9753. * @param {string} [order] - A string representing the order that the rotations are applied.
  9754. * @return {Euler} A reference to this Euler instance.
  9755. */
  9756. set( x, y, z, order = this._order ) {
  9757. this._x = x;
  9758. this._y = y;
  9759. this._z = z;
  9760. this._order = order;
  9761. this._onChangeCallback();
  9762. return this;
  9763. }
  9764. /**
  9765. * Returns a new Euler instance with copied values from this instance.
  9766. *
  9767. * @return {Euler} A clone of this instance.
  9768. */
  9769. clone() {
  9770. return new this.constructor( this._x, this._y, this._z, this._order );
  9771. }
  9772. /**
  9773. * Copies the values of the given Euler instance to this instance.
  9774. *
  9775. * @param {Euler} euler - The Euler instance to copy.
  9776. * @return {Euler} A reference to this Euler instance.
  9777. */
  9778. copy( euler ) {
  9779. this._x = euler._x;
  9780. this._y = euler._y;
  9781. this._z = euler._z;
  9782. this._order = euler._order;
  9783. this._onChangeCallback();
  9784. return this;
  9785. }
  9786. /**
  9787. * Sets the angles of this Euler instance from a pure rotation matrix.
  9788. *
  9789. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9790. * @param {string} [order] - A string representing the order that the rotations are applied.
  9791. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9792. * @return {Euler} A reference to this Euler instance.
  9793. */
  9794. setFromRotationMatrix( m, order = this._order, update = true ) {
  9795. const te = m.elements;
  9796. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9797. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9798. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9799. switch ( order ) {
  9800. case 'XYZ':
  9801. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9802. if ( Math.abs( m13 ) < 0.9999999 ) {
  9803. this._x = Math.atan2( - m23, m33 );
  9804. this._z = Math.atan2( - m12, m11 );
  9805. } else {
  9806. this._x = Math.atan2( m32, m22 );
  9807. this._z = 0;
  9808. }
  9809. break;
  9810. case 'YXZ':
  9811. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9812. if ( Math.abs( m23 ) < 0.9999999 ) {
  9813. this._y = Math.atan2( m13, m33 );
  9814. this._z = Math.atan2( m21, m22 );
  9815. } else {
  9816. this._y = Math.atan2( - m31, m11 );
  9817. this._z = 0;
  9818. }
  9819. break;
  9820. case 'ZXY':
  9821. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9822. if ( Math.abs( m32 ) < 0.9999999 ) {
  9823. this._y = Math.atan2( - m31, m33 );
  9824. this._z = Math.atan2( - m12, m22 );
  9825. } else {
  9826. this._y = 0;
  9827. this._z = Math.atan2( m21, m11 );
  9828. }
  9829. break;
  9830. case 'ZYX':
  9831. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9832. if ( Math.abs( m31 ) < 0.9999999 ) {
  9833. this._x = Math.atan2( m32, m33 );
  9834. this._z = Math.atan2( m21, m11 );
  9835. } else {
  9836. this._x = 0;
  9837. this._z = Math.atan2( - m12, m22 );
  9838. }
  9839. break;
  9840. case 'YZX':
  9841. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9842. if ( Math.abs( m21 ) < 0.9999999 ) {
  9843. this._x = Math.atan2( - m23, m22 );
  9844. this._y = Math.atan2( - m31, m11 );
  9845. } else {
  9846. this._x = 0;
  9847. this._y = Math.atan2( m13, m33 );
  9848. }
  9849. break;
  9850. case 'XZY':
  9851. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9852. if ( Math.abs( m12 ) < 0.9999999 ) {
  9853. this._x = Math.atan2( m32, m22 );
  9854. this._y = Math.atan2( m13, m11 );
  9855. } else {
  9856. this._x = Math.atan2( - m23, m33 );
  9857. this._y = 0;
  9858. }
  9859. break;
  9860. default:
  9861. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9862. }
  9863. this._order = order;
  9864. if ( update === true ) this._onChangeCallback();
  9865. return this;
  9866. }
  9867. /**
  9868. * Sets the angles of this Euler instance from a normalized quaternion.
  9869. *
  9870. * @param {Quaternion} q - A normalized Quaternion.
  9871. * @param {string} [order] - A string representing the order that the rotations are applied.
  9872. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9873. * @return {Euler} A reference to this Euler instance.
  9874. */
  9875. setFromQuaternion( q, order, update ) {
  9876. _matrix$2.makeRotationFromQuaternion( q );
  9877. return this.setFromRotationMatrix( _matrix$2, order, update );
  9878. }
  9879. /**
  9880. * Sets the angles of this Euler instance from the given vector.
  9881. *
  9882. * @param {Vector3} v - The vector.
  9883. * @param {string} [order] - A string representing the order that the rotations are applied.
  9884. * @return {Euler} A reference to this Euler instance.
  9885. */
  9886. setFromVector3( v, order = this._order ) {
  9887. return this.set( v.x, v.y, v.z, order );
  9888. }
  9889. /**
  9890. * Resets the euler angle with a new order by creating a quaternion from this
  9891. * euler angle and then setting this euler angle with the quaternion and the
  9892. * new order.
  9893. *
  9894. * Warning: This discards revolution information.
  9895. *
  9896. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9897. * @return {Euler} A reference to this Euler instance.
  9898. */
  9899. reorder( newOrder ) {
  9900. _quaternion$3.setFromEuler( this );
  9901. return this.setFromQuaternion( _quaternion$3, newOrder );
  9902. }
  9903. /**
  9904. * Returns `true` if this Euler instance is equal with the given one.
  9905. *
  9906. * @param {Euler} euler - The Euler instance to test for equality.
  9907. * @return {boolean} Whether this Euler instance is equal with the given one.
  9908. */
  9909. equals( euler ) {
  9910. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9911. }
  9912. /**
  9913. * Sets this Euler instance's components to values from the given array. The first three
  9914. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9915. * defines the Euler order.
  9916. *
  9917. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9918. * @return {Euler} A reference to this Euler instance.
  9919. */
  9920. fromArray( array ) {
  9921. this._x = array[ 0 ];
  9922. this._y = array[ 1 ];
  9923. this._z = array[ 2 ];
  9924. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9925. this._onChangeCallback();
  9926. return this;
  9927. }
  9928. /**
  9929. * Writes the components of this Euler instance to the given array. If no array is provided,
  9930. * the method returns a new instance.
  9931. *
  9932. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9933. * @param {number} [offset=0] - Index of the first element in the array.
  9934. * @return {Array<number,number,number,string>} The Euler components.
  9935. */
  9936. toArray( array = [], offset = 0 ) {
  9937. array[ offset ] = this._x;
  9938. array[ offset + 1 ] = this._y;
  9939. array[ offset + 2 ] = this._z;
  9940. array[ offset + 3 ] = this._order;
  9941. return array;
  9942. }
  9943. _onChange( callback ) {
  9944. this._onChangeCallback = callback;
  9945. return this;
  9946. }
  9947. _onChangeCallback() {}
  9948. *[ Symbol.iterator ]() {
  9949. yield this._x;
  9950. yield this._y;
  9951. yield this._z;
  9952. yield this._order;
  9953. }
  9954. }
  9955. /**
  9956. * The default Euler angle order.
  9957. *
  9958. * @static
  9959. * @type {string}
  9960. * @default 'XYZ'
  9961. */
  9962. Euler.DEFAULT_ORDER = 'XYZ';
  9963. /**
  9964. * A layers object assigns an 3D object to 1 or more of 32
  9965. * layers numbered `0` to `31` - internally the layers are stored as a
  9966. * bit mask], and by default all 3D objects are a member of layer `0`.
  9967. *
  9968. * This can be used to control visibility - an object must share a layer with
  9969. * a camera to be visible when that camera's view is
  9970. * rendered.
  9971. *
  9972. * All classes that inherit from {@link Object3D} have an `layers` property which
  9973. * is an instance of this class.
  9974. */
  9975. class Layers {
  9976. /**
  9977. * Constructs a new layers instance, with membership
  9978. * initially set to layer `0`.
  9979. */
  9980. constructor() {
  9981. /**
  9982. * A bit mask storing which of the 32 layers this layers object is currently
  9983. * a member of.
  9984. *
  9985. * @type {number}
  9986. */
  9987. this.mask = 1 | 0;
  9988. }
  9989. /**
  9990. * Sets membership to the given layer, and remove membership all other layers.
  9991. *
  9992. * @param {number} layer - The layer to set.
  9993. */
  9994. set( layer ) {
  9995. this.mask = ( 1 << layer | 0 ) >>> 0;
  9996. }
  9997. /**
  9998. * Adds membership of the given layer.
  9999. *
  10000. * @param {number} layer - The layer to enable.
  10001. */
  10002. enable( layer ) {
  10003. this.mask |= 1 << layer | 0;
  10004. }
  10005. /**
  10006. * Adds membership to all layers.
  10007. */
  10008. enableAll() {
  10009. this.mask = 0xffffffff | 0;
  10010. }
  10011. /**
  10012. * Toggles the membership of the given layer.
  10013. *
  10014. * @param {number} layer - The layer to toggle.
  10015. */
  10016. toggle( layer ) {
  10017. this.mask ^= 1 << layer | 0;
  10018. }
  10019. /**
  10020. * Removes membership of the given layer.
  10021. *
  10022. * @param {number} layer - The layer to enable.
  10023. */
  10024. disable( layer ) {
  10025. this.mask &= ~ ( 1 << layer | 0 );
  10026. }
  10027. /**
  10028. * Removes the membership from all layers.
  10029. */
  10030. disableAll() {
  10031. this.mask = 0;
  10032. }
  10033. /**
  10034. * Returns `true` if this and the given layers object have at least one
  10035. * layer in common.
  10036. *
  10037. * @param {Layers} layers - The layers to test.
  10038. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10039. */
  10040. test( layers ) {
  10041. return ( this.mask & layers.mask ) !== 0;
  10042. }
  10043. /**
  10044. * Returns `true` if the given layer is enabled.
  10045. *
  10046. * @param {number} layer - The layer to test.
  10047. * @return {boolean } Whether the given layer is enabled or not.
  10048. */
  10049. isEnabled( layer ) {
  10050. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10051. }
  10052. }
  10053. let _object3DId = 0;
  10054. const _v1$4 = /*@__PURE__*/ new Vector3();
  10055. const _q1 = /*@__PURE__*/ new Quaternion();
  10056. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10057. const _target = /*@__PURE__*/ new Vector3();
  10058. const _position$3 = /*@__PURE__*/ new Vector3();
  10059. const _scale$2 = /*@__PURE__*/ new Vector3();
  10060. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10061. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10062. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10063. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10064. /**
  10065. * Fires when the object has been added to its parent object.
  10066. *
  10067. * @event Object3D#added
  10068. * @type {Object}
  10069. */
  10070. const _addedEvent = { type: 'added' };
  10071. /**
  10072. * Fires when the object has been removed from its parent object.
  10073. *
  10074. * @event Object3D#removed
  10075. * @type {Object}
  10076. */
  10077. const _removedEvent = { type: 'removed' };
  10078. /**
  10079. * Fires when a new child object has been added.
  10080. *
  10081. * @event Object3D#childadded
  10082. * @type {Object}
  10083. */
  10084. const _childaddedEvent = { type: 'childadded', child: null };
  10085. /**
  10086. * Fires when a child object has been removed.
  10087. *
  10088. * @event Object3D#childremoved
  10089. * @type {Object}
  10090. */
  10091. const _childremovedEvent = { type: 'childremoved', child: null };
  10092. /**
  10093. * This is the base class for most objects in three.js and provides a set of
  10094. * properties and methods for manipulating objects in 3D space.
  10095. *
  10096. * @augments EventDispatcher
  10097. */
  10098. class Object3D extends EventDispatcher {
  10099. /**
  10100. * Constructs a new 3D object.
  10101. */
  10102. constructor() {
  10103. super();
  10104. /**
  10105. * This flag can be used for type testing.
  10106. *
  10107. * @type {boolean}
  10108. * @readonly
  10109. * @default true
  10110. */
  10111. this.isObject3D = true;
  10112. /**
  10113. * The ID of the 3D object.
  10114. *
  10115. * @name Object3D#id
  10116. * @type {number}
  10117. * @readonly
  10118. */
  10119. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10120. /**
  10121. * The UUID of the 3D object.
  10122. *
  10123. * @type {string}
  10124. * @readonly
  10125. */
  10126. this.uuid = generateUUID();
  10127. /**
  10128. * The name of the 3D object.
  10129. *
  10130. * @type {string}
  10131. */
  10132. this.name = '';
  10133. /**
  10134. * The type property is used for detecting the object type
  10135. * in context of serialization/deserialization.
  10136. *
  10137. * @type {string}
  10138. * @readonly
  10139. */
  10140. this.type = 'Object3D';
  10141. /**
  10142. * A reference to the parent object.
  10143. *
  10144. * @type {?Object3D}
  10145. * @default null
  10146. */
  10147. this.parent = null;
  10148. /**
  10149. * An array holding the child 3D objects of this instance.
  10150. *
  10151. * @type {Array<Object3D>}
  10152. */
  10153. this.children = [];
  10154. /**
  10155. * Defines the `up` direction of the 3D object which influences
  10156. * the orientation via methods like {@link Object3D#lookAt}.
  10157. *
  10158. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10159. *
  10160. * @type {Vector3}
  10161. */
  10162. this.up = Object3D.DEFAULT_UP.clone();
  10163. const position = new Vector3();
  10164. const rotation = new Euler();
  10165. const quaternion = new Quaternion();
  10166. const scale = new Vector3( 1, 1, 1 );
  10167. function onRotationChange() {
  10168. quaternion.setFromEuler( rotation, false );
  10169. }
  10170. function onQuaternionChange() {
  10171. rotation.setFromQuaternion( quaternion, undefined, false );
  10172. }
  10173. rotation._onChange( onRotationChange );
  10174. quaternion._onChange( onQuaternionChange );
  10175. Object.defineProperties( this, {
  10176. /**
  10177. * Represents the object's local position.
  10178. *
  10179. * @name Object3D#position
  10180. * @type {Vector3}
  10181. * @default (0,0,0)
  10182. */
  10183. position: {
  10184. configurable: true,
  10185. enumerable: true,
  10186. value: position
  10187. },
  10188. /**
  10189. * Represents the object's local rotation as Euler angles, in radians.
  10190. *
  10191. * @name Object3D#rotation
  10192. * @type {Euler}
  10193. * @default (0,0,0)
  10194. */
  10195. rotation: {
  10196. configurable: true,
  10197. enumerable: true,
  10198. value: rotation
  10199. },
  10200. /**
  10201. * Represents the object's local rotation as Quaternions.
  10202. *
  10203. * @name Object3D#quaternion
  10204. * @type {Quaternion}
  10205. */
  10206. quaternion: {
  10207. configurable: true,
  10208. enumerable: true,
  10209. value: quaternion
  10210. },
  10211. /**
  10212. * Represents the object's local scale.
  10213. *
  10214. * @name Object3D#scale
  10215. * @type {Vector3}
  10216. * @default (1,1,1)
  10217. */
  10218. scale: {
  10219. configurable: true,
  10220. enumerable: true,
  10221. value: scale
  10222. },
  10223. /**
  10224. * Represents the object's model-view matrix.
  10225. *
  10226. * @name Object3D#modelViewMatrix
  10227. * @type {Matrix4}
  10228. */
  10229. modelViewMatrix: {
  10230. value: new Matrix4()
  10231. },
  10232. /**
  10233. * Represents the object's normal matrix.
  10234. *
  10235. * @name Object3D#normalMatrix
  10236. * @type {Matrix3}
  10237. */
  10238. normalMatrix: {
  10239. value: new Matrix3()
  10240. }
  10241. } );
  10242. /**
  10243. * Represents the object's transformation matrix in local space.
  10244. *
  10245. * @type {Matrix4}
  10246. */
  10247. this.matrix = new Matrix4();
  10248. /**
  10249. * Represents the object's transformation matrix in world space.
  10250. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10251. *
  10252. * @type {Matrix4}
  10253. */
  10254. this.matrixWorld = new Matrix4();
  10255. /**
  10256. * When set to `true`, the engine automatically computes the local matrix from position,
  10257. * rotation and scale every frame.
  10258. *
  10259. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10260. *
  10261. * @type {boolean}
  10262. * @default true
  10263. */
  10264. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10265. /**
  10266. * When set to `true`, the engine automatically computes the world matrix from the current local
  10267. * matrix and the object's transformation hierarchy.
  10268. *
  10269. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10270. *
  10271. * @type {boolean}
  10272. * @default true
  10273. */
  10274. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10275. /**
  10276. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10277. * to `false`.
  10278. *
  10279. * @type {boolean}
  10280. * @default false
  10281. */
  10282. this.matrixWorldNeedsUpdate = false;
  10283. /**
  10284. * The layer membership of the 3D object. The 3D object is only visible if it has
  10285. * at least one layer in common with the camera in use. This property can also be
  10286. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10287. *
  10288. * @type {Layers}
  10289. */
  10290. this.layers = new Layers();
  10291. /**
  10292. * When set to `true`, the 3D object gets rendered.
  10293. *
  10294. * @type {boolean}
  10295. * @default true
  10296. */
  10297. this.visible = true;
  10298. /**
  10299. * When set to `true`, the 3D object gets rendered into shadow maps.
  10300. *
  10301. * @type {boolean}
  10302. * @default false
  10303. */
  10304. this.castShadow = false;
  10305. /**
  10306. * When set to `true`, the 3D object is affected by shadows in the scene.
  10307. *
  10308. * @type {boolean}
  10309. * @default false
  10310. */
  10311. this.receiveShadow = false;
  10312. /**
  10313. * When set to `true`, the 3D object is honored by view frustum culling.
  10314. *
  10315. * @type {boolean}
  10316. * @default true
  10317. */
  10318. this.frustumCulled = true;
  10319. /**
  10320. * This value allows the default rendering order of scene graph objects to be
  10321. * overridden although opaque and transparent objects remain sorted independently.
  10322. * When this property is set for an instance of {@link Group},all descendants
  10323. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10324. * render order.
  10325. *
  10326. * @type {number}
  10327. * @default 0
  10328. */
  10329. this.renderOrder = 0;
  10330. /**
  10331. * An array holding the animation clips of the 3D object.
  10332. *
  10333. * @type {Array<AnimationClip>}
  10334. */
  10335. this.animations = [];
  10336. /**
  10337. * Custom depth material to be used when rendering to the depth map. Can only be used
  10338. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10339. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10340. * material for proper shadows.
  10341. *
  10342. * Only relevant in context of {@link WebGLRenderer}.
  10343. *
  10344. * @type {(Material|undefined)}
  10345. * @default undefined
  10346. */
  10347. this.customDepthMaterial = undefined;
  10348. /**
  10349. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10350. *
  10351. * Only relevant in context of {@link WebGLRenderer}.
  10352. *
  10353. * @type {(Material|undefined)}
  10354. * @default undefined
  10355. */
  10356. this.customDistanceMaterial = undefined;
  10357. /**
  10358. * An object that can be used to store custom data about the 3D object. It
  10359. * should not hold references to functions as these will not be cloned.
  10360. *
  10361. * @type {Object}
  10362. */
  10363. this.userData = {};
  10364. }
  10365. /**
  10366. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10367. *
  10368. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10369. * @param {Object3D} object - The 3D object.
  10370. * @param {Camera} camera - The camera that is used to render the scene.
  10371. * @param {Camera} shadowCamera - The shadow camera.
  10372. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10373. * @param {Material} depthMaterial - The depth material.
  10374. * @param {Object} group - The geometry group data.
  10375. */
  10376. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10377. /**
  10378. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10379. *
  10380. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10381. * @param {Object3D} object - The 3D object.
  10382. * @param {Camera} camera - The camera that is used to render the scene.
  10383. * @param {Camera} shadowCamera - The shadow camera.
  10384. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10385. * @param {Material} depthMaterial - The depth material.
  10386. * @param {Object} group - The geometry group data.
  10387. */
  10388. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10389. /**
  10390. * A callback that is executed immediately before a 3D object is rendered.
  10391. *
  10392. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10393. * @param {Object3D} object - The 3D object.
  10394. * @param {Camera} camera - The camera that is used to render the scene.
  10395. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10396. * @param {Material} material - The 3D object's material.
  10397. * @param {Object} group - The geometry group data.
  10398. */
  10399. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10400. /**
  10401. * A callback that is executed immediately after a 3D object is rendered.
  10402. *
  10403. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10404. * @param {Object3D} object - The 3D object.
  10405. * @param {Camera} camera - The camera that is used to render the scene.
  10406. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10407. * @param {Material} material - The 3D object's material.
  10408. * @param {Object} group - The geometry group data.
  10409. */
  10410. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10411. /**
  10412. * Applies the given transformation matrix to the object and updates the object's position,
  10413. * rotation and scale.
  10414. *
  10415. * @param {Matrix4} matrix - The transformation matrix.
  10416. */
  10417. applyMatrix4( matrix ) {
  10418. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10419. this.matrix.premultiply( matrix );
  10420. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10421. }
  10422. /**
  10423. * Applies a rotation represented by given the quaternion to the 3D object.
  10424. *
  10425. * @param {Quaternion} q - The quaternion.
  10426. * @return {Object3D} A reference to this instance.
  10427. */
  10428. applyQuaternion( q ) {
  10429. this.quaternion.premultiply( q );
  10430. return this;
  10431. }
  10432. /**
  10433. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10434. *
  10435. * @param {Vector3} axis - The (normalized) axis vector.
  10436. * @param {number} angle - The angle in radians.
  10437. */
  10438. setRotationFromAxisAngle( axis, angle ) {
  10439. // assumes axis is normalized
  10440. this.quaternion.setFromAxisAngle( axis, angle );
  10441. }
  10442. /**
  10443. * Sets the given rotation represented as Euler angles to the 3D object.
  10444. *
  10445. * @param {Euler} euler - The Euler angles.
  10446. */
  10447. setRotationFromEuler( euler ) {
  10448. this.quaternion.setFromEuler( euler, true );
  10449. }
  10450. /**
  10451. * Sets the given rotation represented as rotation matrix to the 3D object.
  10452. *
  10453. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10454. * a pure rotation matrix (i.e, unscaled).
  10455. */
  10456. setRotationFromMatrix( m ) {
  10457. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10458. this.quaternion.setFromRotationMatrix( m );
  10459. }
  10460. /**
  10461. * Sets the given rotation represented as a Quaternion to the 3D object.
  10462. *
  10463. * @param {Quaternion} q - The Quaternion
  10464. */
  10465. setRotationFromQuaternion( q ) {
  10466. // assumes q is normalized
  10467. this.quaternion.copy( q );
  10468. }
  10469. /**
  10470. * Rotates the 3D object along an axis in local space.
  10471. *
  10472. * @param {Vector3} axis - The (normalized) axis vector.
  10473. * @param {number} angle - The angle in radians.
  10474. * @return {Object3D} A reference to this instance.
  10475. */
  10476. rotateOnAxis( axis, angle ) {
  10477. // rotate object on axis in object space
  10478. // axis is assumed to be normalized
  10479. _q1.setFromAxisAngle( axis, angle );
  10480. this.quaternion.multiply( _q1 );
  10481. return this;
  10482. }
  10483. /**
  10484. * Rotates the 3D object along an axis in world space.
  10485. *
  10486. * @param {Vector3} axis - The (normalized) axis vector.
  10487. * @param {number} angle - The angle in radians.
  10488. * @return {Object3D} A reference to this instance.
  10489. */
  10490. rotateOnWorldAxis( axis, angle ) {
  10491. // rotate object on axis in world space
  10492. // axis is assumed to be normalized
  10493. // method assumes no rotated parent
  10494. _q1.setFromAxisAngle( axis, angle );
  10495. this.quaternion.premultiply( _q1 );
  10496. return this;
  10497. }
  10498. /**
  10499. * Rotates the 3D object around its X axis in local space.
  10500. *
  10501. * @param {number} angle - The angle in radians.
  10502. * @return {Object3D} A reference to this instance.
  10503. */
  10504. rotateX( angle ) {
  10505. return this.rotateOnAxis( _xAxis, angle );
  10506. }
  10507. /**
  10508. * Rotates the 3D object around its Y axis in local space.
  10509. *
  10510. * @param {number} angle - The angle in radians.
  10511. * @return {Object3D} A reference to this instance.
  10512. */
  10513. rotateY( angle ) {
  10514. return this.rotateOnAxis( _yAxis, angle );
  10515. }
  10516. /**
  10517. * Rotates the 3D object around its Z axis in local space.
  10518. *
  10519. * @param {number} angle - The angle in radians.
  10520. * @return {Object3D} A reference to this instance.
  10521. */
  10522. rotateZ( angle ) {
  10523. return this.rotateOnAxis( _zAxis, angle );
  10524. }
  10525. /**
  10526. * Translate the 3D object by a distance along the given axis in local space.
  10527. *
  10528. * @param {Vector3} axis - The (normalized) axis vector.
  10529. * @param {number} distance - The distance in world units.
  10530. * @return {Object3D} A reference to this instance.
  10531. */
  10532. translateOnAxis( axis, distance ) {
  10533. // translate object by distance along axis in object space
  10534. // axis is assumed to be normalized
  10535. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10536. this.position.add( _v1$4.multiplyScalar( distance ) );
  10537. return this;
  10538. }
  10539. /**
  10540. * Translate the 3D object by a distance along its X-axis in local space.
  10541. *
  10542. * @param {number} distance - The distance in world units.
  10543. * @return {Object3D} A reference to this instance.
  10544. */
  10545. translateX( distance ) {
  10546. return this.translateOnAxis( _xAxis, distance );
  10547. }
  10548. /**
  10549. * Translate the 3D object by a distance along its Y-axis in local space.
  10550. *
  10551. * @param {number} distance - The distance in world units.
  10552. * @return {Object3D} A reference to this instance.
  10553. */
  10554. translateY( distance ) {
  10555. return this.translateOnAxis( _yAxis, distance );
  10556. }
  10557. /**
  10558. * Translate the 3D object by a distance along its Z-axis in local space.
  10559. *
  10560. * @param {number} distance - The distance in world units.
  10561. * @return {Object3D} A reference to this instance.
  10562. */
  10563. translateZ( distance ) {
  10564. return this.translateOnAxis( _zAxis, distance );
  10565. }
  10566. /**
  10567. * Converts the given vector from this 3D object's local space to world space.
  10568. *
  10569. * @param {Vector3} vector - The vector to convert.
  10570. * @return {Vector3} The converted vector.
  10571. */
  10572. localToWorld( vector ) {
  10573. this.updateWorldMatrix( true, false );
  10574. return vector.applyMatrix4( this.matrixWorld );
  10575. }
  10576. /**
  10577. * Converts the given vector from this 3D object's word space to local space.
  10578. *
  10579. * @param {Vector3} vector - The vector to convert.
  10580. * @return {Vector3} The converted vector.
  10581. */
  10582. worldToLocal( vector ) {
  10583. this.updateWorldMatrix( true, false );
  10584. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10585. }
  10586. /**
  10587. * Rotates the object to face a point in world space.
  10588. *
  10589. * This method does not support objects having non-uniformly-scaled parent(s).
  10590. *
  10591. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10592. * @param {number} [y] - The y coordinate in world space.
  10593. * @param {number} [z] - The z coordinate in world space.
  10594. */
  10595. lookAt( x, y, z ) {
  10596. // This method does not support objects having non-uniformly-scaled parent(s)
  10597. if ( x.isVector3 ) {
  10598. _target.copy( x );
  10599. } else {
  10600. _target.set( x, y, z );
  10601. }
  10602. const parent = this.parent;
  10603. this.updateWorldMatrix( true, false );
  10604. _position$3.setFromMatrixPosition( this.matrixWorld );
  10605. if ( this.isCamera || this.isLight ) {
  10606. _m1$3.lookAt( _position$3, _target, this.up );
  10607. } else {
  10608. _m1$3.lookAt( _target, _position$3, this.up );
  10609. }
  10610. this.quaternion.setFromRotationMatrix( _m1$3 );
  10611. if ( parent ) {
  10612. _m1$3.extractRotation( parent.matrixWorld );
  10613. _q1.setFromRotationMatrix( _m1$3 );
  10614. this.quaternion.premultiply( _q1.invert() );
  10615. }
  10616. }
  10617. /**
  10618. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10619. * objects may be added. Any current parent on an object passed in here will be
  10620. * removed, since an object can have at most one parent.
  10621. *
  10622. * @fires Object3D#added
  10623. * @fires Object3D#childadded
  10624. * @param {Object3D} object - The 3D object to add.
  10625. * @return {Object3D} A reference to this instance.
  10626. */
  10627. add( object ) {
  10628. if ( arguments.length > 1 ) {
  10629. for ( let i = 0; i < arguments.length; i ++ ) {
  10630. this.add( arguments[ i ] );
  10631. }
  10632. return this;
  10633. }
  10634. if ( object === this ) {
  10635. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10636. return this;
  10637. }
  10638. if ( object && object.isObject3D ) {
  10639. object.removeFromParent();
  10640. object.parent = this;
  10641. this.children.push( object );
  10642. object.dispatchEvent( _addedEvent );
  10643. _childaddedEvent.child = object;
  10644. this.dispatchEvent( _childaddedEvent );
  10645. _childaddedEvent.child = null;
  10646. } else {
  10647. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10648. }
  10649. return this;
  10650. }
  10651. /**
  10652. * Removes the given 3D object as child from this 3D object.
  10653. * An arbitrary number of objects may be removed.
  10654. *
  10655. * @fires Object3D#removed
  10656. * @fires Object3D#childremoved
  10657. * @param {Object3D} object - The 3D object to remove.
  10658. * @return {Object3D} A reference to this instance.
  10659. */
  10660. remove( object ) {
  10661. if ( arguments.length > 1 ) {
  10662. for ( let i = 0; i < arguments.length; i ++ ) {
  10663. this.remove( arguments[ i ] );
  10664. }
  10665. return this;
  10666. }
  10667. const index = this.children.indexOf( object );
  10668. if ( index !== -1 ) {
  10669. object.parent = null;
  10670. this.children.splice( index, 1 );
  10671. object.dispatchEvent( _removedEvent );
  10672. _childremovedEvent.child = object;
  10673. this.dispatchEvent( _childremovedEvent );
  10674. _childremovedEvent.child = null;
  10675. }
  10676. return this;
  10677. }
  10678. /**
  10679. * Removes this 3D object from its current parent.
  10680. *
  10681. * @fires Object3D#removed
  10682. * @fires Object3D#childremoved
  10683. * @return {Object3D} A reference to this instance.
  10684. */
  10685. removeFromParent() {
  10686. const parent = this.parent;
  10687. if ( parent !== null ) {
  10688. parent.remove( this );
  10689. }
  10690. return this;
  10691. }
  10692. /**
  10693. * Removes all child objects.
  10694. *
  10695. * @fires Object3D#removed
  10696. * @fires Object3D#childremoved
  10697. * @return {Object3D} A reference to this instance.
  10698. */
  10699. clear() {
  10700. return this.remove( ... this.children );
  10701. }
  10702. /**
  10703. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10704. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10705. *
  10706. * @fires Object3D#added
  10707. * @fires Object3D#childadded
  10708. * @param {Object3D} object - The 3D object to attach.
  10709. * @return {Object3D} A reference to this instance.
  10710. */
  10711. attach( object ) {
  10712. // adds object as a child of this, while maintaining the object's world transform
  10713. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10714. this.updateWorldMatrix( true, false );
  10715. _m1$3.copy( this.matrixWorld ).invert();
  10716. if ( object.parent !== null ) {
  10717. object.parent.updateWorldMatrix( true, false );
  10718. _m1$3.multiply( object.parent.matrixWorld );
  10719. }
  10720. object.applyMatrix4( _m1$3 );
  10721. object.removeFromParent();
  10722. object.parent = this;
  10723. this.children.push( object );
  10724. object.updateWorldMatrix( false, true );
  10725. object.dispatchEvent( _addedEvent );
  10726. _childaddedEvent.child = object;
  10727. this.dispatchEvent( _childaddedEvent );
  10728. _childaddedEvent.child = null;
  10729. return this;
  10730. }
  10731. /**
  10732. * Searches through the 3D object and its children, starting with the 3D object
  10733. * itself, and returns the first with a matching ID.
  10734. *
  10735. * @param {number} id - The id.
  10736. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10737. */
  10738. getObjectById( id ) {
  10739. return this.getObjectByProperty( 'id', id );
  10740. }
  10741. /**
  10742. * Searches through the 3D object and its children, starting with the 3D object
  10743. * itself, and returns the first with a matching name.
  10744. *
  10745. * @param {string} name - The name.
  10746. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10747. */
  10748. getObjectByName( name ) {
  10749. return this.getObjectByProperty( 'name', name );
  10750. }
  10751. /**
  10752. * Searches through the 3D object and its children, starting with the 3D object
  10753. * itself, and returns the first with a matching property value.
  10754. *
  10755. * @param {string} name - The name of the property.
  10756. * @param {any} value - The value.
  10757. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10758. */
  10759. getObjectByProperty( name, value ) {
  10760. if ( this[ name ] === value ) return this;
  10761. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10762. const child = this.children[ i ];
  10763. const object = child.getObjectByProperty( name, value );
  10764. if ( object !== undefined ) {
  10765. return object;
  10766. }
  10767. }
  10768. return undefined;
  10769. }
  10770. /**
  10771. * Searches through the 3D object and its children, starting with the 3D object
  10772. * itself, and returns all 3D objects with a matching property value.
  10773. *
  10774. * @param {string} name - The name of the property.
  10775. * @param {any} value - The value.
  10776. * @param {Array<Object3D>} result - The method stores the result in this array.
  10777. * @return {Array<Object3D>} The found 3D objects.
  10778. */
  10779. getObjectsByProperty( name, value, result = [] ) {
  10780. if ( this[ name ] === value ) result.push( this );
  10781. const children = this.children;
  10782. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10783. children[ i ].getObjectsByProperty( name, value, result );
  10784. }
  10785. return result;
  10786. }
  10787. /**
  10788. * Returns a vector representing the position of the 3D object in world space.
  10789. *
  10790. * @param {Vector3} target - The target vector the result is stored to.
  10791. * @return {Vector3} The 3D object's position in world space.
  10792. */
  10793. getWorldPosition( target ) {
  10794. this.updateWorldMatrix( true, false );
  10795. return target.setFromMatrixPosition( this.matrixWorld );
  10796. }
  10797. /**
  10798. * Returns a Quaternion representing the position of the 3D object in world space.
  10799. *
  10800. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10801. * @return {Quaternion} The 3D object's rotation in world space.
  10802. */
  10803. getWorldQuaternion( target ) {
  10804. this.updateWorldMatrix( true, false );
  10805. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10806. return target;
  10807. }
  10808. /**
  10809. * Returns a vector representing the scale of the 3D object in world space.
  10810. *
  10811. * @param {Vector3} target - The target vector the result is stored to.
  10812. * @return {Vector3} The 3D object's scale in world space.
  10813. */
  10814. getWorldScale( target ) {
  10815. this.updateWorldMatrix( true, false );
  10816. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10817. return target;
  10818. }
  10819. /**
  10820. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10821. *
  10822. * @param {Vector3} target - The target vector the result is stored to.
  10823. * @return {Vector3} The 3D object's direction in world space.
  10824. */
  10825. getWorldDirection( target ) {
  10826. this.updateWorldMatrix( true, false );
  10827. const e = this.matrixWorld.elements;
  10828. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10829. }
  10830. /**
  10831. * Abstract method to get intersections between a casted ray and this
  10832. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10833. * implement this method in order to use raycasting.
  10834. *
  10835. * @abstract
  10836. * @param {Raycaster} raycaster - The raycaster.
  10837. * @param {Array<Object>} intersects - An array holding the result of the method.
  10838. */
  10839. raycast( /* raycaster, intersects */ ) {}
  10840. /**
  10841. * Executes the callback on this 3D object and all descendants.
  10842. *
  10843. * Note: Modifying the scene graph inside the callback is discouraged.
  10844. *
  10845. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10846. */
  10847. traverse( callback ) {
  10848. callback( this );
  10849. const children = this.children;
  10850. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10851. children[ i ].traverse( callback );
  10852. }
  10853. }
  10854. /**
  10855. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10856. * Descendants of invisible 3D objects are not traversed.
  10857. *
  10858. * Note: Modifying the scene graph inside the callback is discouraged.
  10859. *
  10860. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10861. */
  10862. traverseVisible( callback ) {
  10863. if ( this.visible === false ) return;
  10864. callback( this );
  10865. const children = this.children;
  10866. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10867. children[ i ].traverseVisible( callback );
  10868. }
  10869. }
  10870. /**
  10871. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10872. *
  10873. * Note: Modifying the scene graph inside the callback is discouraged.
  10874. *
  10875. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10876. */
  10877. traverseAncestors( callback ) {
  10878. const parent = this.parent;
  10879. if ( parent !== null ) {
  10880. callback( parent );
  10881. parent.traverseAncestors( callback );
  10882. }
  10883. }
  10884. /**
  10885. * Updates the transformation matrix in local space by computing it from the current
  10886. * position, rotation and scale values.
  10887. */
  10888. updateMatrix() {
  10889. this.matrix.compose( this.position, this.quaternion, this.scale );
  10890. this.matrixWorldNeedsUpdate = true;
  10891. }
  10892. /**
  10893. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10894. *
  10895. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10896. * local space. The computation of the local and world matrix can be controlled with the
  10897. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10898. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10899. *
  10900. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10901. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10902. */
  10903. updateMatrixWorld( force ) {
  10904. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10905. if ( this.matrixWorldNeedsUpdate || force ) {
  10906. if ( this.matrixWorldAutoUpdate === true ) {
  10907. if ( this.parent === null ) {
  10908. this.matrixWorld.copy( this.matrix );
  10909. } else {
  10910. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10911. }
  10912. }
  10913. this.matrixWorldNeedsUpdate = false;
  10914. force = true;
  10915. }
  10916. // make sure descendants are updated if required
  10917. const children = this.children;
  10918. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10919. const child = children[ i ];
  10920. child.updateMatrixWorld( force );
  10921. }
  10922. }
  10923. /**
  10924. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10925. * update of ancestor and descendant nodes.
  10926. *
  10927. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10928. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10929. */
  10930. updateWorldMatrix( updateParents, updateChildren ) {
  10931. const parent = this.parent;
  10932. if ( updateParents === true && parent !== null ) {
  10933. parent.updateWorldMatrix( true, false );
  10934. }
  10935. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10936. if ( this.matrixWorldAutoUpdate === true ) {
  10937. if ( this.parent === null ) {
  10938. this.matrixWorld.copy( this.matrix );
  10939. } else {
  10940. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10941. }
  10942. }
  10943. // make sure descendants are updated
  10944. if ( updateChildren === true ) {
  10945. const children = this.children;
  10946. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10947. const child = children[ i ];
  10948. child.updateWorldMatrix( false, true );
  10949. }
  10950. }
  10951. }
  10952. /**
  10953. * Serializes the 3D object into JSON.
  10954. *
  10955. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10956. * @return {Object} A JSON object representing the serialized 3D object.
  10957. * @see {@link ObjectLoader#parse}
  10958. */
  10959. toJSON( meta ) {
  10960. // meta is a string when called from JSON.stringify
  10961. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10962. const output = {};
  10963. // meta is a hash used to collect geometries, materials.
  10964. // not providing it implies that this is the root object
  10965. // being serialized.
  10966. if ( isRootObject ) {
  10967. // initialize meta obj
  10968. meta = {
  10969. geometries: {},
  10970. materials: {},
  10971. textures: {},
  10972. images: {},
  10973. shapes: {},
  10974. skeletons: {},
  10975. animations: {},
  10976. nodes: {}
  10977. };
  10978. output.metadata = {
  10979. version: 4.7,
  10980. type: 'Object',
  10981. generator: 'Object3D.toJSON'
  10982. };
  10983. }
  10984. // standard Object3D serialization
  10985. const object = {};
  10986. object.uuid = this.uuid;
  10987. object.type = this.type;
  10988. if ( this.name !== '' ) object.name = this.name;
  10989. if ( this.castShadow === true ) object.castShadow = true;
  10990. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10991. if ( this.visible === false ) object.visible = false;
  10992. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10993. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10994. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10995. object.layers = this.layers.mask;
  10996. object.matrix = this.matrix.toArray();
  10997. object.up = this.up.toArray();
  10998. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10999. // object specific properties
  11000. if ( this.isInstancedMesh ) {
  11001. object.type = 'InstancedMesh';
  11002. object.count = this.count;
  11003. object.instanceMatrix = this.instanceMatrix.toJSON();
  11004. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11005. }
  11006. if ( this.isBatchedMesh ) {
  11007. object.type = 'BatchedMesh';
  11008. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11009. object.sortObjects = this.sortObjects;
  11010. object.drawRanges = this._drawRanges;
  11011. object.reservedRanges = this._reservedRanges;
  11012. object.geometryInfo = this._geometryInfo.map( info => ( {
  11013. ...info,
  11014. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11015. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11016. } ) );
  11017. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11018. object.availableInstanceIds = this._availableInstanceIds.slice();
  11019. object.availableGeometryIds = this._availableGeometryIds.slice();
  11020. object.nextIndexStart = this._nextIndexStart;
  11021. object.nextVertexStart = this._nextVertexStart;
  11022. object.geometryCount = this._geometryCount;
  11023. object.maxInstanceCount = this._maxInstanceCount;
  11024. object.maxVertexCount = this._maxVertexCount;
  11025. object.maxIndexCount = this._maxIndexCount;
  11026. object.geometryInitialized = this._geometryInitialized;
  11027. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11028. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11029. if ( this._colorsTexture !== null ) {
  11030. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11031. }
  11032. if ( this.boundingSphere !== null ) {
  11033. object.boundingSphere = this.boundingSphere.toJSON();
  11034. }
  11035. if ( this.boundingBox !== null ) {
  11036. object.boundingBox = this.boundingBox.toJSON();
  11037. }
  11038. }
  11039. //
  11040. function serialize( library, element ) {
  11041. if ( library[ element.uuid ] === undefined ) {
  11042. library[ element.uuid ] = element.toJSON( meta );
  11043. }
  11044. return element.uuid;
  11045. }
  11046. if ( this.isScene ) {
  11047. if ( this.background ) {
  11048. if ( this.background.isColor ) {
  11049. object.background = this.background.toJSON();
  11050. } else if ( this.background.isTexture ) {
  11051. object.background = this.background.toJSON( meta ).uuid;
  11052. }
  11053. }
  11054. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11055. object.environment = this.environment.toJSON( meta ).uuid;
  11056. }
  11057. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11058. object.geometry = serialize( meta.geometries, this.geometry );
  11059. const parameters = this.geometry.parameters;
  11060. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11061. const shapes = parameters.shapes;
  11062. if ( Array.isArray( shapes ) ) {
  11063. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11064. const shape = shapes[ i ];
  11065. serialize( meta.shapes, shape );
  11066. }
  11067. } else {
  11068. serialize( meta.shapes, shapes );
  11069. }
  11070. }
  11071. }
  11072. if ( this.isSkinnedMesh ) {
  11073. object.bindMode = this.bindMode;
  11074. object.bindMatrix = this.bindMatrix.toArray();
  11075. if ( this.skeleton !== undefined ) {
  11076. serialize( meta.skeletons, this.skeleton );
  11077. object.skeleton = this.skeleton.uuid;
  11078. }
  11079. }
  11080. if ( this.material !== undefined ) {
  11081. if ( Array.isArray( this.material ) ) {
  11082. const uuids = [];
  11083. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11084. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11085. }
  11086. object.material = uuids;
  11087. } else {
  11088. object.material = serialize( meta.materials, this.material );
  11089. }
  11090. }
  11091. //
  11092. if ( this.children.length > 0 ) {
  11093. object.children = [];
  11094. for ( let i = 0; i < this.children.length; i ++ ) {
  11095. object.children.push( this.children[ i ].toJSON( meta ).object );
  11096. }
  11097. }
  11098. //
  11099. if ( this.animations.length > 0 ) {
  11100. object.animations = [];
  11101. for ( let i = 0; i < this.animations.length; i ++ ) {
  11102. const animation = this.animations[ i ];
  11103. object.animations.push( serialize( meta.animations, animation ) );
  11104. }
  11105. }
  11106. if ( isRootObject ) {
  11107. const geometries = extractFromCache( meta.geometries );
  11108. const materials = extractFromCache( meta.materials );
  11109. const textures = extractFromCache( meta.textures );
  11110. const images = extractFromCache( meta.images );
  11111. const shapes = extractFromCache( meta.shapes );
  11112. const skeletons = extractFromCache( meta.skeletons );
  11113. const animations = extractFromCache( meta.animations );
  11114. const nodes = extractFromCache( meta.nodes );
  11115. if ( geometries.length > 0 ) output.geometries = geometries;
  11116. if ( materials.length > 0 ) output.materials = materials;
  11117. if ( textures.length > 0 ) output.textures = textures;
  11118. if ( images.length > 0 ) output.images = images;
  11119. if ( shapes.length > 0 ) output.shapes = shapes;
  11120. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11121. if ( animations.length > 0 ) output.animations = animations;
  11122. if ( nodes.length > 0 ) output.nodes = nodes;
  11123. }
  11124. output.object = object;
  11125. return output;
  11126. // extract data from the cache hash
  11127. // remove metadata on each item
  11128. // and return as array
  11129. function extractFromCache( cache ) {
  11130. const values = [];
  11131. for ( const key in cache ) {
  11132. const data = cache[ key ];
  11133. delete data.metadata;
  11134. values.push( data );
  11135. }
  11136. return values;
  11137. }
  11138. }
  11139. /**
  11140. * Returns a new 3D object with copied values from this instance.
  11141. *
  11142. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11143. * @return {Object3D} A clone of this instance.
  11144. */
  11145. clone( recursive ) {
  11146. return new this.constructor().copy( this, recursive );
  11147. }
  11148. /**
  11149. * Copies the values of the given 3D object to this instance.
  11150. *
  11151. * @param {Object3D} source - The 3D object to copy.
  11152. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11153. * @return {Object3D} A reference to this instance.
  11154. */
  11155. copy( source, recursive = true ) {
  11156. this.name = source.name;
  11157. this.up.copy( source.up );
  11158. this.position.copy( source.position );
  11159. this.rotation.order = source.rotation.order;
  11160. this.quaternion.copy( source.quaternion );
  11161. this.scale.copy( source.scale );
  11162. this.matrix.copy( source.matrix );
  11163. this.matrixWorld.copy( source.matrixWorld );
  11164. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11165. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11166. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11167. this.layers.mask = source.layers.mask;
  11168. this.visible = source.visible;
  11169. this.castShadow = source.castShadow;
  11170. this.receiveShadow = source.receiveShadow;
  11171. this.frustumCulled = source.frustumCulled;
  11172. this.renderOrder = source.renderOrder;
  11173. this.animations = source.animations.slice();
  11174. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11175. if ( recursive === true ) {
  11176. for ( let i = 0; i < source.children.length; i ++ ) {
  11177. const child = source.children[ i ];
  11178. this.add( child.clone() );
  11179. }
  11180. }
  11181. return this;
  11182. }
  11183. }
  11184. /**
  11185. * The default up direction for objects, also used as the default
  11186. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11187. *
  11188. * @static
  11189. * @type {Vector3}
  11190. * @default (0,1,0)
  11191. */
  11192. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11193. /**
  11194. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11195. * newly created 3D objects.
  11196. *
  11197. * @static
  11198. * @type {boolean}
  11199. * @default true
  11200. */
  11201. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11202. /**
  11203. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11204. * newly created 3D objects.
  11205. *
  11206. * @static
  11207. * @type {boolean}
  11208. * @default true
  11209. */
  11210. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11211. const _v0$2 = /*@__PURE__*/ new Vector3();
  11212. const _v1$3 = /*@__PURE__*/ new Vector3();
  11213. const _v2$2 = /*@__PURE__*/ new Vector3();
  11214. const _v3$2 = /*@__PURE__*/ new Vector3();
  11215. const _vab = /*@__PURE__*/ new Vector3();
  11216. const _vac = /*@__PURE__*/ new Vector3();
  11217. const _vbc = /*@__PURE__*/ new Vector3();
  11218. const _vap = /*@__PURE__*/ new Vector3();
  11219. const _vbp = /*@__PURE__*/ new Vector3();
  11220. const _vcp = /*@__PURE__*/ new Vector3();
  11221. const _v40 = /*@__PURE__*/ new Vector4();
  11222. const _v41 = /*@__PURE__*/ new Vector4();
  11223. const _v42 = /*@__PURE__*/ new Vector4();
  11224. /**
  11225. * A geometric triangle as defined by three vectors representing its three corners.
  11226. */
  11227. class Triangle {
  11228. /**
  11229. * Constructs a new triangle.
  11230. *
  11231. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11232. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11233. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11234. */
  11235. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11236. /**
  11237. * The first corner of the triangle.
  11238. *
  11239. * @type {Vector3}
  11240. */
  11241. this.a = a;
  11242. /**
  11243. * The second corner of the triangle.
  11244. *
  11245. * @type {Vector3}
  11246. */
  11247. this.b = b;
  11248. /**
  11249. * The third corner of the triangle.
  11250. *
  11251. * @type {Vector3}
  11252. */
  11253. this.c = c;
  11254. }
  11255. /**
  11256. * Computes the normal vector of a triangle.
  11257. *
  11258. * @param {Vector3} a - The first corner of the triangle.
  11259. * @param {Vector3} b - The second corner of the triangle.
  11260. * @param {Vector3} c - The third corner of the triangle.
  11261. * @param {Vector3} target - The target vector that is used to store the method's result.
  11262. * @return {Vector3} The triangle's normal.
  11263. */
  11264. static getNormal( a, b, c, target ) {
  11265. target.subVectors( c, b );
  11266. _v0$2.subVectors( a, b );
  11267. target.cross( _v0$2 );
  11268. const targetLengthSq = target.lengthSq();
  11269. if ( targetLengthSq > 0 ) {
  11270. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11271. }
  11272. return target.set( 0, 0, 0 );
  11273. }
  11274. /**
  11275. * Computes a barycentric coordinates from the given vector.
  11276. * Returns `null` if the triangle is degenerate.
  11277. *
  11278. * @param {Vector3} point - A point in 3D space.
  11279. * @param {Vector3} a - The first corner of the triangle.
  11280. * @param {Vector3} b - The second corner of the triangle.
  11281. * @param {Vector3} c - The third corner of the triangle.
  11282. * @param {Vector3} target - The target vector that is used to store the method's result.
  11283. * @return {?Vector3} The barycentric coordinates for the given point
  11284. */
  11285. static getBarycoord( point, a, b, c, target ) {
  11286. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11287. _v0$2.subVectors( c, a );
  11288. _v1$3.subVectors( b, a );
  11289. _v2$2.subVectors( point, a );
  11290. const dot00 = _v0$2.dot( _v0$2 );
  11291. const dot01 = _v0$2.dot( _v1$3 );
  11292. const dot02 = _v0$2.dot( _v2$2 );
  11293. const dot11 = _v1$3.dot( _v1$3 );
  11294. const dot12 = _v1$3.dot( _v2$2 );
  11295. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11296. // collinear or singular triangle
  11297. if ( denom === 0 ) {
  11298. target.set( 0, 0, 0 );
  11299. return null;
  11300. }
  11301. const invDenom = 1 / denom;
  11302. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11303. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11304. // barycentric coordinates must always sum to 1
  11305. return target.set( 1 - u - v, v, u );
  11306. }
  11307. /**
  11308. * Returns `true` if the given point, when projected onto the plane of the
  11309. * triangle, lies within the triangle.
  11310. *
  11311. * @param {Vector3} point - The point in 3D space to test.
  11312. * @param {Vector3} a - The first corner of the triangle.
  11313. * @param {Vector3} b - The second corner of the triangle.
  11314. * @param {Vector3} c - The third corner of the triangle.
  11315. * @return {boolean} Whether the given point, when projected onto the plane of the
  11316. * triangle, lies within the triangle or not.
  11317. */
  11318. static containsPoint( point, a, b, c ) {
  11319. // if the triangle is degenerate then we can't contain a point
  11320. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11321. return false;
  11322. }
  11323. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11324. }
  11325. /**
  11326. * Computes the value barycentrically interpolated for the given point on the
  11327. * triangle. Returns `null` if the triangle is degenerate.
  11328. *
  11329. * @param {Vector3} point - Position of interpolated point.
  11330. * @param {Vector3} p1 - The first corner of the triangle.
  11331. * @param {Vector3} p2 - The second corner of the triangle.
  11332. * @param {Vector3} p3 - The third corner of the triangle.
  11333. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11334. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11335. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11336. * @param {Vector3} target - The target vector that is used to store the method's result.
  11337. * @return {?Vector3} The interpolated value.
  11338. */
  11339. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11340. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11341. target.x = 0;
  11342. target.y = 0;
  11343. if ( 'z' in target ) target.z = 0;
  11344. if ( 'w' in target ) target.w = 0;
  11345. return null;
  11346. }
  11347. target.setScalar( 0 );
  11348. target.addScaledVector( v1, _v3$2.x );
  11349. target.addScaledVector( v2, _v3$2.y );
  11350. target.addScaledVector( v3, _v3$2.z );
  11351. return target;
  11352. }
  11353. /**
  11354. * Computes the value barycentrically interpolated for the given attribute and indices.
  11355. *
  11356. * @param {BufferAttribute} attr - The attribute to interpolate.
  11357. * @param {number} i1 - Index of first vertex.
  11358. * @param {number} i2 - Index of second vertex.
  11359. * @param {number} i3 - Index of third vertex.
  11360. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11361. * @param {Vector3} target - The target vector that is used to store the method's result.
  11362. * @return {Vector3} The interpolated attribute value.
  11363. */
  11364. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11365. _v40.setScalar( 0 );
  11366. _v41.setScalar( 0 );
  11367. _v42.setScalar( 0 );
  11368. _v40.fromBufferAttribute( attr, i1 );
  11369. _v41.fromBufferAttribute( attr, i2 );
  11370. _v42.fromBufferAttribute( attr, i3 );
  11371. target.setScalar( 0 );
  11372. target.addScaledVector( _v40, barycoord.x );
  11373. target.addScaledVector( _v41, barycoord.y );
  11374. target.addScaledVector( _v42, barycoord.z );
  11375. return target;
  11376. }
  11377. /**
  11378. * Returns `true` if the triangle is oriented towards the given direction.
  11379. *
  11380. * @param {Vector3} a - The first corner of the triangle.
  11381. * @param {Vector3} b - The second corner of the triangle.
  11382. * @param {Vector3} c - The third corner of the triangle.
  11383. * @param {Vector3} direction - The (normalized) direction vector.
  11384. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11385. */
  11386. static isFrontFacing( a, b, c, direction ) {
  11387. _v0$2.subVectors( c, b );
  11388. _v1$3.subVectors( a, b );
  11389. // strictly front facing
  11390. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11391. }
  11392. /**
  11393. * Sets the triangle's vertices by copying the given values.
  11394. *
  11395. * @param {Vector3} a - The first corner of the triangle.
  11396. * @param {Vector3} b - The second corner of the triangle.
  11397. * @param {Vector3} c - The third corner of the triangle.
  11398. * @return {Triangle} A reference to this triangle.
  11399. */
  11400. set( a, b, c ) {
  11401. this.a.copy( a );
  11402. this.b.copy( b );
  11403. this.c.copy( c );
  11404. return this;
  11405. }
  11406. /**
  11407. * Sets the triangle's vertices by copying the given array values.
  11408. *
  11409. * @param {Array<Vector3>} points - An array with 3D points.
  11410. * @param {number} i0 - The array index representing the first corner of the triangle.
  11411. * @param {number} i1 - The array index representing the second corner of the triangle.
  11412. * @param {number} i2 - The array index representing the third corner of the triangle.
  11413. * @return {Triangle} A reference to this triangle.
  11414. */
  11415. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11416. this.a.copy( points[ i0 ] );
  11417. this.b.copy( points[ i1 ] );
  11418. this.c.copy( points[ i2 ] );
  11419. return this;
  11420. }
  11421. /**
  11422. * Sets the triangle's vertices by copying the given attribute values.
  11423. *
  11424. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11425. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11426. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11427. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11428. * @return {Triangle} A reference to this triangle.
  11429. */
  11430. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11431. this.a.fromBufferAttribute( attribute, i0 );
  11432. this.b.fromBufferAttribute( attribute, i1 );
  11433. this.c.fromBufferAttribute( attribute, i2 );
  11434. return this;
  11435. }
  11436. /**
  11437. * Returns a new triangle with copied values from this instance.
  11438. *
  11439. * @return {Triangle} A clone of this instance.
  11440. */
  11441. clone() {
  11442. return new this.constructor().copy( this );
  11443. }
  11444. /**
  11445. * Copies the values of the given triangle to this instance.
  11446. *
  11447. * @param {Triangle} triangle - The triangle to copy.
  11448. * @return {Triangle} A reference to this triangle.
  11449. */
  11450. copy( triangle ) {
  11451. this.a.copy( triangle.a );
  11452. this.b.copy( triangle.b );
  11453. this.c.copy( triangle.c );
  11454. return this;
  11455. }
  11456. /**
  11457. * Computes the area of the triangle.
  11458. *
  11459. * @return {number} The triangle's area.
  11460. */
  11461. getArea() {
  11462. _v0$2.subVectors( this.c, this.b );
  11463. _v1$3.subVectors( this.a, this.b );
  11464. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11465. }
  11466. /**
  11467. * Computes the midpoint of the triangle.
  11468. *
  11469. * @param {Vector3} target - The target vector that is used to store the method's result.
  11470. * @return {Vector3} The triangle's midpoint.
  11471. */
  11472. getMidpoint( target ) {
  11473. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11474. }
  11475. /**
  11476. * Computes the normal of the triangle.
  11477. *
  11478. * @param {Vector3} target - The target vector that is used to store the method's result.
  11479. * @return {Vector3} The triangle's normal.
  11480. */
  11481. getNormal( target ) {
  11482. return Triangle.getNormal( this.a, this.b, this.c, target );
  11483. }
  11484. /**
  11485. * Computes a plane the triangle lies within.
  11486. *
  11487. * @param {Plane} target - The target vector that is used to store the method's result.
  11488. * @return {Plane} The plane the triangle lies within.
  11489. */
  11490. getPlane( target ) {
  11491. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11492. }
  11493. /**
  11494. * Computes a barycentric coordinates from the given vector.
  11495. * Returns `null` if the triangle is degenerate.
  11496. *
  11497. * @param {Vector3} point - A point in 3D space.
  11498. * @param {Vector3} target - The target vector that is used to store the method's result.
  11499. * @return {?Vector3} The barycentric coordinates for the given point
  11500. */
  11501. getBarycoord( point, target ) {
  11502. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11503. }
  11504. /**
  11505. * Computes the value barycentrically interpolated for the given point on the
  11506. * triangle. Returns `null` if the triangle is degenerate.
  11507. *
  11508. * @param {Vector3} point - Position of interpolated point.
  11509. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11510. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11511. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11512. * @param {Vector3} target - The target vector that is used to store the method's result.
  11513. * @return {?Vector3} The interpolated value.
  11514. */
  11515. getInterpolation( point, v1, v2, v3, target ) {
  11516. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11517. }
  11518. /**
  11519. * Returns `true` if the given point, when projected onto the plane of the
  11520. * triangle, lies within the triangle.
  11521. *
  11522. * @param {Vector3} point - The point in 3D space to test.
  11523. * @return {boolean} Whether the given point, when projected onto the plane of the
  11524. * triangle, lies within the triangle or not.
  11525. */
  11526. containsPoint( point ) {
  11527. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11528. }
  11529. /**
  11530. * Returns `true` if the triangle is oriented towards the given direction.
  11531. *
  11532. * @param {Vector3} direction - The (normalized) direction vector.
  11533. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11534. */
  11535. isFrontFacing( direction ) {
  11536. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11537. }
  11538. /**
  11539. * Returns `true` if this triangle intersects with the given box.
  11540. *
  11541. * @param {Box3} box - The box to intersect.
  11542. * @return {boolean} Whether this triangle intersects with the given box or not.
  11543. */
  11544. intersectsBox( box ) {
  11545. return box.intersectsTriangle( this );
  11546. }
  11547. /**
  11548. * Returns the closest point on the triangle to the given point.
  11549. *
  11550. * @param {Vector3} p - The point to compute the closest point for.
  11551. * @param {Vector3} target - The target vector that is used to store the method's result.
  11552. * @return {Vector3} The closest point on the triangle.
  11553. */
  11554. closestPointToPoint( p, target ) {
  11555. const a = this.a, b = this.b, c = this.c;
  11556. let v, w;
  11557. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11558. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11559. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11560. // basically, we're distinguishing which of the voronoi regions of the triangle
  11561. // the point lies in with the minimum amount of redundant computation.
  11562. _vab.subVectors( b, a );
  11563. _vac.subVectors( c, a );
  11564. _vap.subVectors( p, a );
  11565. const d1 = _vab.dot( _vap );
  11566. const d2 = _vac.dot( _vap );
  11567. if ( d1 <= 0 && d2 <= 0 ) {
  11568. // vertex region of A; barycentric coords (1, 0, 0)
  11569. return target.copy( a );
  11570. }
  11571. _vbp.subVectors( p, b );
  11572. const d3 = _vab.dot( _vbp );
  11573. const d4 = _vac.dot( _vbp );
  11574. if ( d3 >= 0 && d4 <= d3 ) {
  11575. // vertex region of B; barycentric coords (0, 1, 0)
  11576. return target.copy( b );
  11577. }
  11578. const vc = d1 * d4 - d3 * d2;
  11579. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11580. v = d1 / ( d1 - d3 );
  11581. // edge region of AB; barycentric coords (1-v, v, 0)
  11582. return target.copy( a ).addScaledVector( _vab, v );
  11583. }
  11584. _vcp.subVectors( p, c );
  11585. const d5 = _vab.dot( _vcp );
  11586. const d6 = _vac.dot( _vcp );
  11587. if ( d6 >= 0 && d5 <= d6 ) {
  11588. // vertex region of C; barycentric coords (0, 0, 1)
  11589. return target.copy( c );
  11590. }
  11591. const vb = d5 * d2 - d1 * d6;
  11592. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11593. w = d2 / ( d2 - d6 );
  11594. // edge region of AC; barycentric coords (1-w, 0, w)
  11595. return target.copy( a ).addScaledVector( _vac, w );
  11596. }
  11597. const va = d3 * d6 - d5 * d4;
  11598. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11599. _vbc.subVectors( c, b );
  11600. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11601. // edge region of BC; barycentric coords (0, 1-w, w)
  11602. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11603. }
  11604. // face region
  11605. const denom = 1 / ( va + vb + vc );
  11606. // u = va * denom
  11607. v = vb * denom;
  11608. w = vc * denom;
  11609. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11610. }
  11611. /**
  11612. * Returns `true` if this triangle is equal with the given one.
  11613. *
  11614. * @param {Triangle} triangle - The triangle to test for equality.
  11615. * @return {boolean} Whether this triangle is equal with the given one.
  11616. */
  11617. equals( triangle ) {
  11618. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11619. }
  11620. }
  11621. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11622. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11623. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11624. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11625. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11626. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11627. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11628. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11629. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11630. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11631. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11632. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11633. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11634. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11635. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11636. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11637. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11638. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11639. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11640. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11641. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11642. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11643. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11644. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11645. const _hslA = { h: 0, s: 0, l: 0 };
  11646. const _hslB = { h: 0, s: 0, l: 0 };
  11647. function hue2rgb( p, q, t ) {
  11648. if ( t < 0 ) t += 1;
  11649. if ( t > 1 ) t -= 1;
  11650. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11651. if ( t < 1 / 2 ) return q;
  11652. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11653. return p;
  11654. }
  11655. /**
  11656. * A Color instance is represented by RGB components in the linear <i>working
  11657. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11658. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11659. * strings) are converted to the working color space automatically.
  11660. *
  11661. * ```js
  11662. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11663. * const color = new THREE.Color().setHex( 0x112233 );
  11664. * ```
  11665. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11666. * ```js
  11667. * // assumed already LinearSRGBColorSpace; no conversion
  11668. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11669. *
  11670. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11671. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11672. * ```
  11673. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11674. * see <i>Color management</i>. Iterating through a Color instance will yield
  11675. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11676. * in any of the following ways:
  11677. * ```js
  11678. * //empty constructor - will default white
  11679. * const color1 = new THREE.Color();
  11680. *
  11681. * //Hexadecimal color (recommended)
  11682. * const color2 = new THREE.Color( 0xff0000 );
  11683. *
  11684. * //RGB string
  11685. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11686. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11687. *
  11688. * //X11 color name - all 140 color names are supported.
  11689. * //Note the lack of CamelCase in the name
  11690. * const color5 = new THREE.Color( 'skyblue' );
  11691. * //HSL string
  11692. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11693. *
  11694. * //Separate RGB values between 0 and 1
  11695. * const color7 = new THREE.Color( 1, 0, 0 );
  11696. * ```
  11697. */
  11698. class Color {
  11699. /**
  11700. * Constructs a new color.
  11701. *
  11702. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11703. * and that method is used throughout the rest of the documentation.
  11704. *
  11705. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11706. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11707. * @param {number} [g] - The green component.
  11708. * @param {number} [b] - The blue component.
  11709. */
  11710. constructor( r, g, b ) {
  11711. /**
  11712. * This flag can be used for type testing.
  11713. *
  11714. * @type {boolean}
  11715. * @readonly
  11716. * @default true
  11717. */
  11718. this.isColor = true;
  11719. /**
  11720. * The red component.
  11721. *
  11722. * @type {number}
  11723. * @default 1
  11724. */
  11725. this.r = 1;
  11726. /**
  11727. * The green component.
  11728. *
  11729. * @type {number}
  11730. * @default 1
  11731. */
  11732. this.g = 1;
  11733. /**
  11734. * The blue component.
  11735. *
  11736. * @type {number}
  11737. * @default 1
  11738. */
  11739. this.b = 1;
  11740. return this.set( r, g, b );
  11741. }
  11742. /**
  11743. * Sets the colors's components from the given values.
  11744. *
  11745. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11746. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11747. * @param {number} [g] - The green component.
  11748. * @param {number} [b] - The blue component.
  11749. * @return {Color} A reference to this color.
  11750. */
  11751. set( r, g, b ) {
  11752. if ( g === undefined && b === undefined ) {
  11753. // r is THREE.Color, hex or string
  11754. const value = r;
  11755. if ( value && value.isColor ) {
  11756. this.copy( value );
  11757. } else if ( typeof value === 'number' ) {
  11758. this.setHex( value );
  11759. } else if ( typeof value === 'string' ) {
  11760. this.setStyle( value );
  11761. }
  11762. } else {
  11763. this.setRGB( r, g, b );
  11764. }
  11765. return this;
  11766. }
  11767. /**
  11768. * Sets the colors's components to the given scalar value.
  11769. *
  11770. * @param {number} scalar - The scalar value.
  11771. * @return {Color} A reference to this color.
  11772. */
  11773. setScalar( scalar ) {
  11774. this.r = scalar;
  11775. this.g = scalar;
  11776. this.b = scalar;
  11777. return this;
  11778. }
  11779. /**
  11780. * Sets this color from a hexadecimal value.
  11781. *
  11782. * @param {number} hex - The hexadecimal value.
  11783. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11784. * @return {Color} A reference to this color.
  11785. */
  11786. setHex( hex, colorSpace = SRGBColorSpace ) {
  11787. hex = Math.floor( hex );
  11788. this.r = ( hex >> 16 & 255 ) / 255;
  11789. this.g = ( hex >> 8 & 255 ) / 255;
  11790. this.b = ( hex & 255 ) / 255;
  11791. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11792. return this;
  11793. }
  11794. /**
  11795. * Sets this color from RGB values.
  11796. *
  11797. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11798. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11799. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11800. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11801. * @return {Color} A reference to this color.
  11802. */
  11803. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11804. this.r = r;
  11805. this.g = g;
  11806. this.b = b;
  11807. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11808. return this;
  11809. }
  11810. /**
  11811. * Sets this color from RGB values.
  11812. *
  11813. * @param {number} h - Hue value between `0.0` and `1.0`.
  11814. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11815. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11816. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11817. * @return {Color} A reference to this color.
  11818. */
  11819. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11820. // h,s,l ranges are in 0.0 - 1.0
  11821. h = euclideanModulo( h, 1 );
  11822. s = clamp( s, 0, 1 );
  11823. l = clamp( l, 0, 1 );
  11824. if ( s === 0 ) {
  11825. this.r = this.g = this.b = l;
  11826. } else {
  11827. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11828. const q = ( 2 * l ) - p;
  11829. this.r = hue2rgb( q, p, h + 1 / 3 );
  11830. this.g = hue2rgb( q, p, h );
  11831. this.b = hue2rgb( q, p, h - 1 / 3 );
  11832. }
  11833. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11834. return this;
  11835. }
  11836. /**
  11837. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11838. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11839. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  11840. * all 140 color names are supported).
  11841. *
  11842. * @param {string} style - Color as a CSS-style string.
  11843. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11844. * @return {Color} A reference to this color.
  11845. */
  11846. setStyle( style, colorSpace = SRGBColorSpace ) {
  11847. function handleAlpha( string ) {
  11848. if ( string === undefined ) return;
  11849. if ( parseFloat( string ) < 1 ) {
  11850. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  11851. }
  11852. }
  11853. let m;
  11854. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11855. // rgb / hsl
  11856. let color;
  11857. const name = m[ 1 ];
  11858. const components = m[ 2 ];
  11859. switch ( name ) {
  11860. case 'rgb':
  11861. case 'rgba':
  11862. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11863. // rgb(255,0,0) rgba(255,0,0,0.5)
  11864. handleAlpha( color[ 4 ] );
  11865. return this.setRGB(
  11866. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11867. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11868. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11869. colorSpace
  11870. );
  11871. }
  11872. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11873. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11874. handleAlpha( color[ 4 ] );
  11875. return this.setRGB(
  11876. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11877. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11878. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11879. colorSpace
  11880. );
  11881. }
  11882. break;
  11883. case 'hsl':
  11884. case 'hsla':
  11885. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11886. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11887. handleAlpha( color[ 4 ] );
  11888. return this.setHSL(
  11889. parseFloat( color[ 1 ] ) / 360,
  11890. parseFloat( color[ 2 ] ) / 100,
  11891. parseFloat( color[ 3 ] ) / 100,
  11892. colorSpace
  11893. );
  11894. }
  11895. break;
  11896. default:
  11897. warn( 'Color: Unknown color model ' + style );
  11898. }
  11899. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11900. // hex color
  11901. const hex = m[ 1 ];
  11902. const size = hex.length;
  11903. if ( size === 3 ) {
  11904. // #ff0
  11905. return this.setRGB(
  11906. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11907. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11908. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11909. colorSpace
  11910. );
  11911. } else if ( size === 6 ) {
  11912. // #ff0000
  11913. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11914. } else {
  11915. warn( 'Color: Invalid hex color ' + style );
  11916. }
  11917. } else if ( style && style.length > 0 ) {
  11918. return this.setColorName( style, colorSpace );
  11919. }
  11920. return this;
  11921. }
  11922. /**
  11923. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11924. * you don't need the other CSS-style formats.
  11925. *
  11926. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11927. * ```js
  11928. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11929. * ```
  11930. *
  11931. * @param {string} style - The color name.
  11932. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11933. * @return {Color} A reference to this color.
  11934. */
  11935. setColorName( style, colorSpace = SRGBColorSpace ) {
  11936. // color keywords
  11937. const hex = _colorKeywords[ style.toLowerCase() ];
  11938. if ( hex !== undefined ) {
  11939. // red
  11940. this.setHex( hex, colorSpace );
  11941. } else {
  11942. // unknown color
  11943. warn( 'Color: Unknown color ' + style );
  11944. }
  11945. return this;
  11946. }
  11947. /**
  11948. * Returns a new color with copied values from this instance.
  11949. *
  11950. * @return {Color} A clone of this instance.
  11951. */
  11952. clone() {
  11953. return new this.constructor( this.r, this.g, this.b );
  11954. }
  11955. /**
  11956. * Copies the values of the given color to this instance.
  11957. *
  11958. * @param {Color} color - The color to copy.
  11959. * @return {Color} A reference to this color.
  11960. */
  11961. copy( color ) {
  11962. this.r = color.r;
  11963. this.g = color.g;
  11964. this.b = color.b;
  11965. return this;
  11966. }
  11967. /**
  11968. * Copies the given color into this color, and then converts this color from
  11969. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11970. *
  11971. * @param {Color} color - The color to copy/convert.
  11972. * @return {Color} A reference to this color.
  11973. */
  11974. copySRGBToLinear( color ) {
  11975. this.r = SRGBToLinear( color.r );
  11976. this.g = SRGBToLinear( color.g );
  11977. this.b = SRGBToLinear( color.b );
  11978. return this;
  11979. }
  11980. /**
  11981. * Copies the given color into this color, and then converts this color from
  11982. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11983. *
  11984. * @param {Color} color - The color to copy/convert.
  11985. * @return {Color} A reference to this color.
  11986. */
  11987. copyLinearToSRGB( color ) {
  11988. this.r = LinearToSRGB( color.r );
  11989. this.g = LinearToSRGB( color.g );
  11990. this.b = LinearToSRGB( color.b );
  11991. return this;
  11992. }
  11993. /**
  11994. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11995. *
  11996. * @return {Color} A reference to this color.
  11997. */
  11998. convertSRGBToLinear() {
  11999. this.copySRGBToLinear( this );
  12000. return this;
  12001. }
  12002. /**
  12003. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12004. *
  12005. * @return {Color} A reference to this color.
  12006. */
  12007. convertLinearToSRGB() {
  12008. this.copyLinearToSRGB( this );
  12009. return this;
  12010. }
  12011. /**
  12012. * Returns the hexadecimal value of this color.
  12013. *
  12014. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12015. * @return {number} The hexadecimal value.
  12016. */
  12017. getHex( colorSpace = SRGBColorSpace ) {
  12018. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12019. 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 ) );
  12020. }
  12021. /**
  12022. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12023. *
  12024. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12025. * @return {string} The hexadecimal value as a string.
  12026. */
  12027. getHexString( colorSpace = SRGBColorSpace ) {
  12028. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12029. }
  12030. /**
  12031. * Converts the colors RGB values into the HSL format and stores them into the
  12032. * given target object.
  12033. *
  12034. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12035. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12036. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12037. */
  12038. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12039. // h,s,l ranges are in 0.0 - 1.0
  12040. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12041. const r = _color.r, g = _color.g, b = _color.b;
  12042. const max = Math.max( r, g, b );
  12043. const min = Math.min( r, g, b );
  12044. let hue, saturation;
  12045. const lightness = ( min + max ) / 2.0;
  12046. if ( min === max ) {
  12047. hue = 0;
  12048. saturation = 0;
  12049. } else {
  12050. const delta = max - min;
  12051. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12052. switch ( max ) {
  12053. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12054. case g: hue = ( b - r ) / delta + 2; break;
  12055. case b: hue = ( r - g ) / delta + 4; break;
  12056. }
  12057. hue /= 6;
  12058. }
  12059. target.h = hue;
  12060. target.s = saturation;
  12061. target.l = lightness;
  12062. return target;
  12063. }
  12064. /**
  12065. * Returns the RGB values of this color and stores them into the given target object.
  12066. *
  12067. * @param {Color} target - The target color that is used to store the method's result.
  12068. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12069. * @return {Color} The RGB representation of this color.
  12070. */
  12071. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12072. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12073. target.r = _color.r;
  12074. target.g = _color.g;
  12075. target.b = _color.b;
  12076. return target;
  12077. }
  12078. /**
  12079. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12080. *
  12081. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12082. * @return {string} The CSS representation of this color.
  12083. */
  12084. getStyle( colorSpace = SRGBColorSpace ) {
  12085. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12086. const r = _color.r, g = _color.g, b = _color.b;
  12087. if ( colorSpace !== SRGBColorSpace ) {
  12088. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12089. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12090. }
  12091. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12092. }
  12093. /**
  12094. * Adds the given HSL values to this color's values.
  12095. * Internally, this converts the color's RGB values to HSL, adds HSL
  12096. * and then converts the color back to RGB.
  12097. *
  12098. * @param {number} h - Hue value between `0.0` and `1.0`.
  12099. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12100. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12101. * @return {Color} A reference to this color.
  12102. */
  12103. offsetHSL( h, s, l ) {
  12104. this.getHSL( _hslA );
  12105. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12106. }
  12107. /**
  12108. * Adds the RGB values of the given color to the RGB values of this color.
  12109. *
  12110. * @param {Color} color - The color to add.
  12111. * @return {Color} A reference to this color.
  12112. */
  12113. add( color ) {
  12114. this.r += color.r;
  12115. this.g += color.g;
  12116. this.b += color.b;
  12117. return this;
  12118. }
  12119. /**
  12120. * Adds the RGB values of the given colors and stores the result in this instance.
  12121. *
  12122. * @param {Color} color1 - The first color.
  12123. * @param {Color} color2 - The second color.
  12124. * @return {Color} A reference to this color.
  12125. */
  12126. addColors( color1, color2 ) {
  12127. this.r = color1.r + color2.r;
  12128. this.g = color1.g + color2.g;
  12129. this.b = color1.b + color2.b;
  12130. return this;
  12131. }
  12132. /**
  12133. * Adds the given scalar value to the RGB values of this color.
  12134. *
  12135. * @param {number} s - The scalar to add.
  12136. * @return {Color} A reference to this color.
  12137. */
  12138. addScalar( s ) {
  12139. this.r += s;
  12140. this.g += s;
  12141. this.b += s;
  12142. return this;
  12143. }
  12144. /**
  12145. * Subtracts the RGB values of the given color from the RGB values of this color.
  12146. *
  12147. * @param {Color} color - The color to subtract.
  12148. * @return {Color} A reference to this color.
  12149. */
  12150. sub( color ) {
  12151. this.r = Math.max( 0, this.r - color.r );
  12152. this.g = Math.max( 0, this.g - color.g );
  12153. this.b = Math.max( 0, this.b - color.b );
  12154. return this;
  12155. }
  12156. /**
  12157. * Multiplies the RGB values of the given color with the RGB values of this color.
  12158. *
  12159. * @param {Color} color - The color to multiply.
  12160. * @return {Color} A reference to this color.
  12161. */
  12162. multiply( color ) {
  12163. this.r *= color.r;
  12164. this.g *= color.g;
  12165. this.b *= color.b;
  12166. return this;
  12167. }
  12168. /**
  12169. * Multiplies the given scalar value with the RGB values of this color.
  12170. *
  12171. * @param {number} s - The scalar to multiply.
  12172. * @return {Color} A reference to this color.
  12173. */
  12174. multiplyScalar( s ) {
  12175. this.r *= s;
  12176. this.g *= s;
  12177. this.b *= s;
  12178. return this;
  12179. }
  12180. /**
  12181. * Linearly interpolates this color's RGB values toward the RGB values of the
  12182. * given color. The alpha argument can be thought of as the ratio between
  12183. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12184. *
  12185. * @param {Color} color - The color to converge on.
  12186. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12187. * @return {Color} A reference to this color.
  12188. */
  12189. lerp( color, alpha ) {
  12190. this.r += ( color.r - this.r ) * alpha;
  12191. this.g += ( color.g - this.g ) * alpha;
  12192. this.b += ( color.b - this.b ) * alpha;
  12193. return this;
  12194. }
  12195. /**
  12196. * Linearly interpolates between the given colors and stores the result in this instance.
  12197. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12198. * is the first and `1.0` is the second color.
  12199. *
  12200. * @param {Color} color1 - The first color.
  12201. * @param {Color} color2 - The second color.
  12202. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12203. * @return {Color} A reference to this color.
  12204. */
  12205. lerpColors( color1, color2, alpha ) {
  12206. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12207. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12208. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12209. return this;
  12210. }
  12211. /**
  12212. * Linearly interpolates this color's HSL values toward the HSL values of the
  12213. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12214. * from one color to the other, but instead going through all the hues in between
  12215. * those two colors. The alpha argument can be thought of as the ratio between
  12216. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12217. *
  12218. * @param {Color} color - The color to converge on.
  12219. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12220. * @return {Color} A reference to this color.
  12221. */
  12222. lerpHSL( color, alpha ) {
  12223. this.getHSL( _hslA );
  12224. color.getHSL( _hslB );
  12225. const h = lerp( _hslA.h, _hslB.h, alpha );
  12226. const s = lerp( _hslA.s, _hslB.s, alpha );
  12227. const l = lerp( _hslA.l, _hslB.l, alpha );
  12228. this.setHSL( h, s, l );
  12229. return this;
  12230. }
  12231. /**
  12232. * Sets the color's RGB components from the given 3D vector.
  12233. *
  12234. * @param {Vector3} v - The vector to set.
  12235. * @return {Color} A reference to this color.
  12236. */
  12237. setFromVector3( v ) {
  12238. this.r = v.x;
  12239. this.g = v.y;
  12240. this.b = v.z;
  12241. return this;
  12242. }
  12243. /**
  12244. * Transforms this color with the given 3x3 matrix.
  12245. *
  12246. * @param {Matrix3} m - The matrix.
  12247. * @return {Color} A reference to this color.
  12248. */
  12249. applyMatrix3( m ) {
  12250. const r = this.r, g = this.g, b = this.b;
  12251. const e = m.elements;
  12252. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12253. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12254. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12255. return this;
  12256. }
  12257. /**
  12258. * Returns `true` if this color is equal with the given one.
  12259. *
  12260. * @param {Color} c - The color to test for equality.
  12261. * @return {boolean} Whether this bounding color is equal with the given one.
  12262. */
  12263. equals( c ) {
  12264. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12265. }
  12266. /**
  12267. * Sets this color's RGB components from the given array.
  12268. *
  12269. * @param {Array<number>} array - An array holding the RGB values.
  12270. * @param {number} [offset=0] - The offset into the array.
  12271. * @return {Color} A reference to this color.
  12272. */
  12273. fromArray( array, offset = 0 ) {
  12274. this.r = array[ offset ];
  12275. this.g = array[ offset + 1 ];
  12276. this.b = array[ offset + 2 ];
  12277. return this;
  12278. }
  12279. /**
  12280. * Writes the RGB components of this color to the given array. If no array is provided,
  12281. * the method returns a new instance.
  12282. *
  12283. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12284. * @param {number} [offset=0] - Index of the first element in the array.
  12285. * @return {Array<number>} The color components.
  12286. */
  12287. toArray( array = [], offset = 0 ) {
  12288. array[ offset ] = this.r;
  12289. array[ offset + 1 ] = this.g;
  12290. array[ offset + 2 ] = this.b;
  12291. return array;
  12292. }
  12293. /**
  12294. * Sets the components of this color from the given buffer attribute.
  12295. *
  12296. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12297. * @param {number} index - The index into the attribute.
  12298. * @return {Color} A reference to this color.
  12299. */
  12300. fromBufferAttribute( attribute, index ) {
  12301. this.r = attribute.getX( index );
  12302. this.g = attribute.getY( index );
  12303. this.b = attribute.getZ( index );
  12304. return this;
  12305. }
  12306. /**
  12307. * This methods defines the serialization result of this class. Returns the color
  12308. * as a hexadecimal value.
  12309. *
  12310. * @return {number} The hexadecimal value.
  12311. */
  12312. toJSON() {
  12313. return this.getHex();
  12314. }
  12315. *[ Symbol.iterator ]() {
  12316. yield this.r;
  12317. yield this.g;
  12318. yield this.b;
  12319. }
  12320. }
  12321. const _color = /*@__PURE__*/ new Color();
  12322. /**
  12323. * A dictionary with X11 color names.
  12324. *
  12325. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12326. *
  12327. * @static
  12328. * @type {Object}
  12329. */
  12330. Color.NAMES = _colorKeywords;
  12331. let _materialId = 0;
  12332. /**
  12333. * Abstract base class for materials.
  12334. *
  12335. * Materials define the appearance of renderable 3D objects.
  12336. *
  12337. * @abstract
  12338. * @augments EventDispatcher
  12339. */
  12340. class Material extends EventDispatcher {
  12341. /**
  12342. * Constructs a new material.
  12343. */
  12344. constructor() {
  12345. super();
  12346. /**
  12347. * This flag can be used for type testing.
  12348. *
  12349. * @type {boolean}
  12350. * @readonly
  12351. * @default true
  12352. */
  12353. this.isMaterial = true;
  12354. /**
  12355. * The ID of the material.
  12356. *
  12357. * @name Material#id
  12358. * @type {number}
  12359. * @readonly
  12360. */
  12361. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12362. /**
  12363. * The UUID of the material.
  12364. *
  12365. * @type {string}
  12366. * @readonly
  12367. */
  12368. this.uuid = generateUUID();
  12369. /**
  12370. * The name of the material.
  12371. *
  12372. * @type {string}
  12373. */
  12374. this.name = '';
  12375. /**
  12376. * The type property is used for detecting the object type
  12377. * in context of serialization/deserialization.
  12378. *
  12379. * @type {string}
  12380. * @readonly
  12381. */
  12382. this.type = 'Material';
  12383. /**
  12384. * Defines the blending type of the material.
  12385. *
  12386. * It must be set to `CustomBlending` if custom blending properties like
  12387. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12388. * should have any effect.
  12389. *
  12390. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12391. * @default NormalBlending
  12392. */
  12393. this.blending = NormalBlending;
  12394. /**
  12395. * Defines which side of faces will be rendered - front, back or both.
  12396. *
  12397. * @type {(FrontSide|BackSide|DoubleSide)}
  12398. * @default FrontSide
  12399. */
  12400. this.side = FrontSide;
  12401. /**
  12402. * If set to `true`, vertex colors should be used.
  12403. *
  12404. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12405. * four (RGBA) component color buffer attribute is used.
  12406. *
  12407. * @type {boolean}
  12408. * @default false
  12409. */
  12410. this.vertexColors = false;
  12411. /**
  12412. * Defines how transparent the material is.
  12413. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12414. *
  12415. * If the {@link Material#transparent} is not set to `true`,
  12416. * the material will remain fully opaque and this value will only affect its color.
  12417. *
  12418. * @type {number}
  12419. * @default 1
  12420. */
  12421. this.opacity = 1;
  12422. /**
  12423. * Defines whether this material is transparent. This has an effect on
  12424. * rendering as transparent objects need special treatment and are rendered
  12425. * after non-transparent objects.
  12426. *
  12427. * When set to true, the extent to which the material is transparent is
  12428. * controlled by {@link Material#opacity}.
  12429. *
  12430. * @type {boolean}
  12431. * @default false
  12432. */
  12433. this.transparent = false;
  12434. /**
  12435. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12436. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12437. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12438. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12439. *
  12440. * @type {boolean}
  12441. * @default false
  12442. */
  12443. this.alphaHash = false;
  12444. /**
  12445. * Defines the blending source factor.
  12446. *
  12447. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12448. * @default SrcAlphaFactor
  12449. */
  12450. this.blendSrc = SrcAlphaFactor;
  12451. /**
  12452. * Defines the blending destination factor.
  12453. *
  12454. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12455. * @default OneMinusSrcAlphaFactor
  12456. */
  12457. this.blendDst = OneMinusSrcAlphaFactor;
  12458. /**
  12459. * Defines the blending equation.
  12460. *
  12461. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12462. * @default AddEquation
  12463. */
  12464. this.blendEquation = AddEquation;
  12465. /**
  12466. * Defines the blending source alpha factor.
  12467. *
  12468. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12469. * @default null
  12470. */
  12471. this.blendSrcAlpha = null;
  12472. /**
  12473. * Defines the blending destination alpha factor.
  12474. *
  12475. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12476. * @default null
  12477. */
  12478. this.blendDstAlpha = null;
  12479. /**
  12480. * Defines the blending equation of the alpha channel.
  12481. *
  12482. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12483. * @default null
  12484. */
  12485. this.blendEquationAlpha = null;
  12486. /**
  12487. * Represents the RGB values of the constant blend color.
  12488. *
  12489. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12490. *
  12491. * @type {Color}
  12492. * @default (0,0,0)
  12493. */
  12494. this.blendColor = new Color( 0, 0, 0 );
  12495. /**
  12496. * Represents the alpha value of the constant blend color.
  12497. *
  12498. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12499. *
  12500. * @type {number}
  12501. * @default 0
  12502. */
  12503. this.blendAlpha = 0;
  12504. /**
  12505. * Defines the depth function.
  12506. *
  12507. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12508. * @default LessEqualDepth
  12509. */
  12510. this.depthFunc = LessEqualDepth;
  12511. /**
  12512. * Whether to have depth test enabled when rendering this material.
  12513. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12514. *
  12515. * @type {boolean}
  12516. * @default true
  12517. */
  12518. this.depthTest = true;
  12519. /**
  12520. * Whether rendering this material has any effect on the depth buffer.
  12521. *
  12522. * When drawing 2D overlays it can be useful to disable the depth writing in
  12523. * order to layer several things together without creating z-index artifacts.
  12524. *
  12525. * @type {boolean}
  12526. * @default true
  12527. */
  12528. this.depthWrite = true;
  12529. /**
  12530. * The bit mask to use when writing to the stencil buffer.
  12531. *
  12532. * @type {number}
  12533. * @default 0xff
  12534. */
  12535. this.stencilWriteMask = 0xff;
  12536. /**
  12537. * The stencil comparison function to use.
  12538. *
  12539. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12540. * @default AlwaysStencilFunc
  12541. */
  12542. this.stencilFunc = AlwaysStencilFunc;
  12543. /**
  12544. * The value to use when performing stencil comparisons or stencil operations.
  12545. *
  12546. * @type {number}
  12547. * @default 0
  12548. */
  12549. this.stencilRef = 0;
  12550. /**
  12551. * The bit mask to use when comparing against the stencil buffer.
  12552. *
  12553. * @type {number}
  12554. * @default 0xff
  12555. */
  12556. this.stencilFuncMask = 0xff;
  12557. /**
  12558. * Which stencil operation to perform when the comparison function returns `false`.
  12559. *
  12560. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12561. * @default KeepStencilOp
  12562. */
  12563. this.stencilFail = KeepStencilOp;
  12564. /**
  12565. * Which stencil operation to perform when the comparison function returns
  12566. * `true` but the depth test fails.
  12567. *
  12568. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12569. * @default KeepStencilOp
  12570. */
  12571. this.stencilZFail = KeepStencilOp;
  12572. /**
  12573. * Which stencil operation to perform when the comparison function returns
  12574. * `true` and the depth test passes.
  12575. *
  12576. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12577. * @default KeepStencilOp
  12578. */
  12579. this.stencilZPass = KeepStencilOp;
  12580. /**
  12581. * Whether stencil operations are performed against the stencil buffer. In
  12582. * order to perform writes or comparisons against the stencil buffer this
  12583. * value must be `true`.
  12584. *
  12585. * @type {boolean}
  12586. * @default false
  12587. */
  12588. this.stencilWrite = false;
  12589. /**
  12590. * User-defined clipping planes specified as THREE.Plane objects in world
  12591. * space. These planes apply to the objects this material is attached to.
  12592. * Points in space whose signed distance to the plane is negative are clipped
  12593. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12594. * be `true`.
  12595. *
  12596. * @type {?Array<Plane>}
  12597. * @default null
  12598. */
  12599. this.clippingPlanes = null;
  12600. /**
  12601. * Changes the behavior of clipping planes so that only their intersection is
  12602. * clipped, rather than their union.
  12603. *
  12604. * @type {boolean}
  12605. * @default false
  12606. */
  12607. this.clipIntersection = false;
  12608. /**
  12609. * Defines whether to clip shadows according to the clipping planes specified
  12610. * on this material.
  12611. *
  12612. * @type {boolean}
  12613. * @default false
  12614. */
  12615. this.clipShadows = false;
  12616. /**
  12617. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12618. * is determined as follows:
  12619. *
  12620. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12621. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12622. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12623. *
  12624. * @type {?(FrontSide|BackSide|DoubleSide)}
  12625. * @default null
  12626. */
  12627. this.shadowSide = null;
  12628. /**
  12629. * Whether to render the material's color.
  12630. *
  12631. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12632. * objects that occlude other objects.
  12633. *
  12634. * @type {boolean}
  12635. * @default true
  12636. */
  12637. this.colorWrite = true;
  12638. /**
  12639. * Override the renderer's default precision for this material.
  12640. *
  12641. * @type {?('highp'|'mediump'|'lowp')}
  12642. * @default null
  12643. */
  12644. this.precision = null;
  12645. /**
  12646. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12647. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12648. * The offset is added before the depth test is performed and before the value is written
  12649. * into the depth buffer.
  12650. *
  12651. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12652. * rendering solids with highlighted edges.
  12653. *
  12654. * @type {boolean}
  12655. * @default false
  12656. */
  12657. this.polygonOffset = false;
  12658. /**
  12659. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12660. *
  12661. * @type {number}
  12662. * @default 0
  12663. */
  12664. this.polygonOffsetFactor = 0;
  12665. /**
  12666. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12667. *
  12668. * @type {number}
  12669. * @default 0
  12670. */
  12671. this.polygonOffsetUnits = 0;
  12672. /**
  12673. * Whether to apply dithering to the color to remove the appearance of banding.
  12674. *
  12675. * @type {boolean}
  12676. * @default false
  12677. */
  12678. this.dithering = false;
  12679. /**
  12680. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12681. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12682. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12683. *
  12684. * @type {boolean}
  12685. * @default false
  12686. */
  12687. this.alphaToCoverage = false;
  12688. /**
  12689. * Whether to premultiply the alpha (transparency) value.
  12690. *
  12691. * @type {boolean}
  12692. * @default false
  12693. */
  12694. this.premultipliedAlpha = false;
  12695. /**
  12696. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12697. *
  12698. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12699. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12700. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12701. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12702. * disable the two pass rendering to avoid performance issues.
  12703. *
  12704. * @type {boolean}
  12705. * @default false
  12706. */
  12707. this.forceSinglePass = false;
  12708. /**
  12709. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12710. *
  12711. * @type {boolean}
  12712. * @default true
  12713. */
  12714. this.allowOverride = true;
  12715. /**
  12716. * Defines whether 3D objects using this material are visible.
  12717. *
  12718. * @type {boolean}
  12719. * @default true
  12720. */
  12721. this.visible = true;
  12722. /**
  12723. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12724. *
  12725. * It is ignored when rendering to a render target or using post processing or when using
  12726. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12727. *
  12728. * @type {boolean}
  12729. * @default true
  12730. */
  12731. this.toneMapped = true;
  12732. /**
  12733. * An object that can be used to store custom data about the Material. It
  12734. * should not hold references to functions as these will not be cloned.
  12735. *
  12736. * @type {Object}
  12737. */
  12738. this.userData = {};
  12739. /**
  12740. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12741. *
  12742. * @type {number}
  12743. * @readonly
  12744. * @default 0
  12745. */
  12746. this.version = 0;
  12747. this._alphaTest = 0;
  12748. }
  12749. /**
  12750. * Sets the alpha value to be used when running an alpha test. The material
  12751. * will not be rendered if the opacity is lower than this value.
  12752. *
  12753. * @type {number}
  12754. * @readonly
  12755. * @default 0
  12756. */
  12757. get alphaTest() {
  12758. return this._alphaTest;
  12759. }
  12760. set alphaTest( value ) {
  12761. if ( this._alphaTest > 0 !== value > 0 ) {
  12762. this.version ++;
  12763. }
  12764. this._alphaTest = value;
  12765. }
  12766. /**
  12767. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12768. *
  12769. * This method can only be used when rendering with {@link WebGLRenderer}.
  12770. *
  12771. * @param {WebGLRenderer} renderer - The renderer.
  12772. * @param {Scene} scene - The scene.
  12773. * @param {Camera} camera - The camera that is used to render the scene.
  12774. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12775. * @param {Object3D} object - The 3D object.
  12776. * @param {Object} group - The geometry group data.
  12777. */
  12778. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12779. /**
  12780. * An optional callback that is executed immediately before the shader
  12781. * program is compiled. This function is called with the shader source code
  12782. * as a parameter. Useful for the modification of built-in materials.
  12783. *
  12784. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12785. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12786. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12787. *
  12788. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12789. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12790. */
  12791. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12792. /**
  12793. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12794. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12795. * shader or recompile the shader for this material as needed.
  12796. *
  12797. * This method can only be used when rendering with {@link WebGLRenderer}.
  12798. *
  12799. * @return {string} The custom program cache key.
  12800. */
  12801. customProgramCacheKey() {
  12802. return this.onBeforeCompile.toString();
  12803. }
  12804. /**
  12805. * This method can be used to set default values from parameter objects.
  12806. * It is a generic implementation so it can be used with different types
  12807. * of materials.
  12808. *
  12809. * @param {Object} [values] - The material values to set.
  12810. */
  12811. setValues( values ) {
  12812. if ( values === undefined ) return;
  12813. for ( const key in values ) {
  12814. const newValue = values[ key ];
  12815. if ( newValue === undefined ) {
  12816. warn( `Material: parameter '${ key }' has value of undefined.` );
  12817. continue;
  12818. }
  12819. const currentValue = this[ key ];
  12820. if ( currentValue === undefined ) {
  12821. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12822. continue;
  12823. }
  12824. if ( currentValue && currentValue.isColor ) {
  12825. currentValue.set( newValue );
  12826. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12827. currentValue.copy( newValue );
  12828. } else {
  12829. this[ key ] = newValue;
  12830. }
  12831. }
  12832. }
  12833. /**
  12834. * Serializes the material into JSON.
  12835. *
  12836. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12837. * @return {Object} A JSON object representing the serialized material.
  12838. * @see {@link ObjectLoader#parse}
  12839. */
  12840. toJSON( meta ) {
  12841. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12842. if ( isRootObject ) {
  12843. meta = {
  12844. textures: {},
  12845. images: {}
  12846. };
  12847. }
  12848. const data = {
  12849. metadata: {
  12850. version: 4.7,
  12851. type: 'Material',
  12852. generator: 'Material.toJSON'
  12853. }
  12854. };
  12855. // standard Material serialization
  12856. data.uuid = this.uuid;
  12857. data.type = this.type;
  12858. if ( this.name !== '' ) data.name = this.name;
  12859. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12860. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12861. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12862. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12863. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12864. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12865. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12866. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12867. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12868. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12869. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12870. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12871. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12872. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12873. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12874. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12875. }
  12876. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12877. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12878. }
  12879. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12880. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12881. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12882. }
  12883. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12884. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12885. }
  12886. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12887. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12888. }
  12889. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12890. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12891. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12892. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12893. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12894. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12895. }
  12896. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12897. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12898. }
  12899. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12900. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12901. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12902. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12903. }
  12904. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12905. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12906. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12907. if ( this.lightMap && this.lightMap.isTexture ) {
  12908. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12909. data.lightMapIntensity = this.lightMapIntensity;
  12910. }
  12911. if ( this.aoMap && this.aoMap.isTexture ) {
  12912. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12913. data.aoMapIntensity = this.aoMapIntensity;
  12914. }
  12915. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12916. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12917. data.bumpScale = this.bumpScale;
  12918. }
  12919. if ( this.normalMap && this.normalMap.isTexture ) {
  12920. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12921. data.normalMapType = this.normalMapType;
  12922. data.normalScale = this.normalScale.toArray();
  12923. }
  12924. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12925. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12926. data.displacementScale = this.displacementScale;
  12927. data.displacementBias = this.displacementBias;
  12928. }
  12929. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12930. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12931. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12932. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12933. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12934. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12935. if ( this.envMap && this.envMap.isTexture ) {
  12936. data.envMap = this.envMap.toJSON( meta ).uuid;
  12937. if ( this.combine !== undefined ) data.combine = this.combine;
  12938. }
  12939. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12940. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12941. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12942. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12943. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12944. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12945. }
  12946. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12947. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12948. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12949. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12950. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12951. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12952. if ( this.size !== undefined ) data.size = this.size;
  12953. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12954. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12955. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12956. if ( this.side !== FrontSide ) data.side = this.side;
  12957. if ( this.vertexColors === true ) data.vertexColors = true;
  12958. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12959. if ( this.transparent === true ) data.transparent = true;
  12960. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12961. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12962. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12963. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12964. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12965. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12966. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12967. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12968. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12969. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12970. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12971. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12972. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12973. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12974. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12975. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12976. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12977. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12978. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12979. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12980. // rotation (SpriteMaterial)
  12981. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12982. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12983. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12984. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12985. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12986. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12987. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12988. if ( this.scale !== undefined ) data.scale = this.scale;
  12989. if ( this.dithering === true ) data.dithering = true;
  12990. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12991. if ( this.alphaHash === true ) data.alphaHash = true;
  12992. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12993. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12994. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12995. if ( this.allowOverride === false ) data.allowOverride = false;
  12996. if ( this.wireframe === true ) data.wireframe = true;
  12997. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12998. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12999. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13000. if ( this.flatShading === true ) data.flatShading = true;
  13001. if ( this.visible === false ) data.visible = false;
  13002. if ( this.toneMapped === false ) data.toneMapped = false;
  13003. if ( this.fog === false ) data.fog = false;
  13004. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13005. // TODO: Copied from Object3D.toJSON
  13006. function extractFromCache( cache ) {
  13007. const values = [];
  13008. for ( const key in cache ) {
  13009. const data = cache[ key ];
  13010. delete data.metadata;
  13011. values.push( data );
  13012. }
  13013. return values;
  13014. }
  13015. if ( isRootObject ) {
  13016. const textures = extractFromCache( meta.textures );
  13017. const images = extractFromCache( meta.images );
  13018. if ( textures.length > 0 ) data.textures = textures;
  13019. if ( images.length > 0 ) data.images = images;
  13020. }
  13021. return data;
  13022. }
  13023. /**
  13024. * Returns a new material with copied values from this instance.
  13025. *
  13026. * @return {Material} A clone of this instance.
  13027. */
  13028. clone() {
  13029. return new this.constructor().copy( this );
  13030. }
  13031. /**
  13032. * Copies the values of the given material to this instance.
  13033. *
  13034. * @param {Material} source - The material to copy.
  13035. * @return {Material} A reference to this instance.
  13036. */
  13037. copy( source ) {
  13038. this.name = source.name;
  13039. this.blending = source.blending;
  13040. this.side = source.side;
  13041. this.vertexColors = source.vertexColors;
  13042. this.opacity = source.opacity;
  13043. this.transparent = source.transparent;
  13044. this.blendSrc = source.blendSrc;
  13045. this.blendDst = source.blendDst;
  13046. this.blendEquation = source.blendEquation;
  13047. this.blendSrcAlpha = source.blendSrcAlpha;
  13048. this.blendDstAlpha = source.blendDstAlpha;
  13049. this.blendEquationAlpha = source.blendEquationAlpha;
  13050. this.blendColor.copy( source.blendColor );
  13051. this.blendAlpha = source.blendAlpha;
  13052. this.depthFunc = source.depthFunc;
  13053. this.depthTest = source.depthTest;
  13054. this.depthWrite = source.depthWrite;
  13055. this.stencilWriteMask = source.stencilWriteMask;
  13056. this.stencilFunc = source.stencilFunc;
  13057. this.stencilRef = source.stencilRef;
  13058. this.stencilFuncMask = source.stencilFuncMask;
  13059. this.stencilFail = source.stencilFail;
  13060. this.stencilZFail = source.stencilZFail;
  13061. this.stencilZPass = source.stencilZPass;
  13062. this.stencilWrite = source.stencilWrite;
  13063. const srcPlanes = source.clippingPlanes;
  13064. let dstPlanes = null;
  13065. if ( srcPlanes !== null ) {
  13066. const n = srcPlanes.length;
  13067. dstPlanes = new Array( n );
  13068. for ( let i = 0; i !== n; ++ i ) {
  13069. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13070. }
  13071. }
  13072. this.clippingPlanes = dstPlanes;
  13073. this.clipIntersection = source.clipIntersection;
  13074. this.clipShadows = source.clipShadows;
  13075. this.shadowSide = source.shadowSide;
  13076. this.colorWrite = source.colorWrite;
  13077. this.precision = source.precision;
  13078. this.polygonOffset = source.polygonOffset;
  13079. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13080. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13081. this.dithering = source.dithering;
  13082. this.alphaTest = source.alphaTest;
  13083. this.alphaHash = source.alphaHash;
  13084. this.alphaToCoverage = source.alphaToCoverage;
  13085. this.premultipliedAlpha = source.premultipliedAlpha;
  13086. this.forceSinglePass = source.forceSinglePass;
  13087. this.allowOverride = source.allowOverride;
  13088. this.visible = source.visible;
  13089. this.toneMapped = source.toneMapped;
  13090. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13091. return this;
  13092. }
  13093. /**
  13094. * Frees the GPU-related resources allocated by this instance. Call this
  13095. * method whenever this instance is no longer used in your app.
  13096. *
  13097. * @fires Material#dispose
  13098. */
  13099. dispose() {
  13100. /**
  13101. * Fires when the material has been disposed of.
  13102. *
  13103. * @event Material#dispose
  13104. * @type {Object}
  13105. */
  13106. this.dispatchEvent( { type: 'dispose' } );
  13107. }
  13108. /**
  13109. * Setting this property to `true` indicates the engine the material
  13110. * needs to be recompiled.
  13111. *
  13112. * @type {boolean}
  13113. * @default false
  13114. * @param {boolean} value
  13115. */
  13116. set needsUpdate( value ) {
  13117. if ( value === true ) this.version ++;
  13118. }
  13119. }
  13120. /**
  13121. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13122. *
  13123. * This material is not affected by lights.
  13124. *
  13125. * @augments Material
  13126. * @demo scenes/material-browser.html#MeshBasicMaterial
  13127. */
  13128. class MeshBasicMaterial extends Material {
  13129. /**
  13130. * Constructs a new mesh basic material.
  13131. *
  13132. * @param {Object} [parameters] - An object with one or more properties
  13133. * defining the material's appearance. Any property of the material
  13134. * (including any property from inherited materials) can be passed
  13135. * in here. Color values can be passed any type of value accepted
  13136. * by {@link Color#set}.
  13137. */
  13138. constructor( parameters ) {
  13139. super();
  13140. /**
  13141. * This flag can be used for type testing.
  13142. *
  13143. * @type {boolean}
  13144. * @readonly
  13145. * @default true
  13146. */
  13147. this.isMeshBasicMaterial = true;
  13148. this.type = 'MeshBasicMaterial';
  13149. /**
  13150. * Color of the material.
  13151. *
  13152. * @type {Color}
  13153. * @default (1,1,1)
  13154. */
  13155. this.color = new Color( 0xffffff ); // diffuse
  13156. /**
  13157. * The color map. May optionally include an alpha channel, typically combined
  13158. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13159. * color is modulated by the diffuse `color`.
  13160. *
  13161. * @type {?Texture}
  13162. * @default null
  13163. */
  13164. this.map = null;
  13165. /**
  13166. * The light map. Requires a second set of UVs.
  13167. *
  13168. * @type {?Texture}
  13169. * @default null
  13170. */
  13171. this.lightMap = null;
  13172. /**
  13173. * Intensity of the baked light.
  13174. *
  13175. * @type {number}
  13176. * @default 1
  13177. */
  13178. this.lightMapIntensity = 1.0;
  13179. /**
  13180. * The red channel of this texture is used as the ambient occlusion map.
  13181. * Requires a second set of UVs.
  13182. *
  13183. * @type {?Texture}
  13184. * @default null
  13185. */
  13186. this.aoMap = null;
  13187. /**
  13188. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13189. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13190. * red channel is also `1`, ambient light is fully occluded on a surface.
  13191. *
  13192. * @type {number}
  13193. * @default 1
  13194. */
  13195. this.aoMapIntensity = 1.0;
  13196. /**
  13197. * Specular map used by the material.
  13198. *
  13199. * @type {?Texture}
  13200. * @default null
  13201. */
  13202. this.specularMap = null;
  13203. /**
  13204. * The alpha map is a grayscale texture that controls the opacity across the
  13205. * surface (black: fully transparent; white: fully opaque).
  13206. *
  13207. * Only the color of the texture is used, ignoring the alpha channel if one
  13208. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13209. * when sampling this texture due to the extra bit of precision provided for
  13210. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13211. * luminance/alpha textures will also still work as expected.
  13212. *
  13213. * @type {?Texture}
  13214. * @default null
  13215. */
  13216. this.alphaMap = null;
  13217. /**
  13218. * The environment map.
  13219. *
  13220. * @type {?Texture}
  13221. * @default null
  13222. */
  13223. this.envMap = null;
  13224. /**
  13225. * The rotation of the environment map in radians.
  13226. *
  13227. * @type {Euler}
  13228. * @default (0,0,0)
  13229. */
  13230. this.envMapRotation = new Euler();
  13231. /**
  13232. * How to combine the result of the surface's color with the environment map, if any.
  13233. *
  13234. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13235. * blend between the two colors.
  13236. *
  13237. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13238. * @default MultiplyOperation
  13239. */
  13240. this.combine = MultiplyOperation;
  13241. /**
  13242. * How much the environment map affects the surface.
  13243. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13244. *
  13245. * @type {number}
  13246. * @default 1
  13247. */
  13248. this.reflectivity = 1;
  13249. /**
  13250. * The index of refraction (IOR) of air (approximately 1) divided by the
  13251. * index of refraction of the material. It is used with environment mapping
  13252. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13253. * The refraction ratio should not exceed `1`.
  13254. *
  13255. * @type {number}
  13256. * @default 0.98
  13257. */
  13258. this.refractionRatio = 0.98;
  13259. /**
  13260. * Renders the geometry as a wireframe.
  13261. *
  13262. * @type {boolean}
  13263. * @default false
  13264. */
  13265. this.wireframe = false;
  13266. /**
  13267. * Controls the thickness of the wireframe.
  13268. *
  13269. * Can only be used with {@link SVGRenderer}.
  13270. *
  13271. * @type {number}
  13272. * @default 1
  13273. */
  13274. this.wireframeLinewidth = 1;
  13275. /**
  13276. * Defines appearance of wireframe ends.
  13277. *
  13278. * Can only be used with {@link SVGRenderer}.
  13279. *
  13280. * @type {('round'|'bevel'|'miter')}
  13281. * @default 'round'
  13282. */
  13283. this.wireframeLinecap = 'round';
  13284. /**
  13285. * Defines appearance of wireframe joints.
  13286. *
  13287. * Can only be used with {@link SVGRenderer}.
  13288. *
  13289. * @type {('round'|'bevel'|'miter')}
  13290. * @default 'round'
  13291. */
  13292. this.wireframeLinejoin = 'round';
  13293. /**
  13294. * Whether the material is affected by fog or not.
  13295. *
  13296. * @type {boolean}
  13297. * @default true
  13298. */
  13299. this.fog = true;
  13300. this.setValues( parameters );
  13301. }
  13302. copy( source ) {
  13303. super.copy( source );
  13304. this.color.copy( source.color );
  13305. this.map = source.map;
  13306. this.lightMap = source.lightMap;
  13307. this.lightMapIntensity = source.lightMapIntensity;
  13308. this.aoMap = source.aoMap;
  13309. this.aoMapIntensity = source.aoMapIntensity;
  13310. this.specularMap = source.specularMap;
  13311. this.alphaMap = source.alphaMap;
  13312. this.envMap = source.envMap;
  13313. this.envMapRotation.copy( source.envMapRotation );
  13314. this.combine = source.combine;
  13315. this.reflectivity = source.reflectivity;
  13316. this.refractionRatio = source.refractionRatio;
  13317. this.wireframe = source.wireframe;
  13318. this.wireframeLinewidth = source.wireframeLinewidth;
  13319. this.wireframeLinecap = source.wireframeLinecap;
  13320. this.wireframeLinejoin = source.wireframeLinejoin;
  13321. this.fog = source.fog;
  13322. return this;
  13323. }
  13324. }
  13325. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13326. const _tables = /*@__PURE__*/ _generateTables();
  13327. function _generateTables() {
  13328. // float32 to float16 helpers
  13329. const buffer = new ArrayBuffer( 4 );
  13330. const floatView = new Float32Array( buffer );
  13331. const uint32View = new Uint32Array( buffer );
  13332. const baseTable = new Uint32Array( 512 );
  13333. const shiftTable = new Uint32Array( 512 );
  13334. for ( let i = 0; i < 256; ++ i ) {
  13335. const e = i - 127;
  13336. // very small number (0, -0)
  13337. if ( e < -27 ) {
  13338. baseTable[ i ] = 0x0000;
  13339. baseTable[ i | 0x100 ] = 0x8000;
  13340. shiftTable[ i ] = 24;
  13341. shiftTable[ i | 0x100 ] = 24;
  13342. // small number (denorm)
  13343. } else if ( e < -14 ) {
  13344. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13345. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13346. shiftTable[ i ] = - e - 1;
  13347. shiftTable[ i | 0x100 ] = - e - 1;
  13348. // normal number
  13349. } else if ( e <= 15 ) {
  13350. baseTable[ i ] = ( e + 15 ) << 10;
  13351. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13352. shiftTable[ i ] = 13;
  13353. shiftTable[ i | 0x100 ] = 13;
  13354. // large number (Infinity, -Infinity)
  13355. } else if ( e < 128 ) {
  13356. baseTable[ i ] = 0x7c00;
  13357. baseTable[ i | 0x100 ] = 0xfc00;
  13358. shiftTable[ i ] = 24;
  13359. shiftTable[ i | 0x100 ] = 24;
  13360. // stay (NaN, Infinity, -Infinity)
  13361. } else {
  13362. baseTable[ i ] = 0x7c00;
  13363. baseTable[ i | 0x100 ] = 0xfc00;
  13364. shiftTable[ i ] = 13;
  13365. shiftTable[ i | 0x100 ] = 13;
  13366. }
  13367. }
  13368. // float16 to float32 helpers
  13369. const mantissaTable = new Uint32Array( 2048 );
  13370. const exponentTable = new Uint32Array( 64 );
  13371. const offsetTable = new Uint32Array( 64 );
  13372. for ( let i = 1; i < 1024; ++ i ) {
  13373. let m = i << 13; // zero pad mantissa bits
  13374. let e = 0; // zero exponent
  13375. // normalized
  13376. while ( ( m & 0x00800000 ) === 0 ) {
  13377. m <<= 1;
  13378. e -= 0x00800000; // decrement exponent
  13379. }
  13380. m &= -8388609; // clear leading 1 bit
  13381. e += 0x38800000; // adjust bias
  13382. mantissaTable[ i ] = m | e;
  13383. }
  13384. for ( let i = 1024; i < 2048; ++ i ) {
  13385. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13386. }
  13387. for ( let i = 1; i < 31; ++ i ) {
  13388. exponentTable[ i ] = i << 23;
  13389. }
  13390. exponentTable[ 31 ] = 0x47800000;
  13391. exponentTable[ 32 ] = 0x80000000;
  13392. for ( let i = 33; i < 63; ++ i ) {
  13393. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13394. }
  13395. exponentTable[ 63 ] = 0xc7800000;
  13396. for ( let i = 1; i < 64; ++ i ) {
  13397. if ( i !== 32 ) {
  13398. offsetTable[ i ] = 1024;
  13399. }
  13400. }
  13401. return {
  13402. floatView: floatView,
  13403. uint32View: uint32View,
  13404. baseTable: baseTable,
  13405. shiftTable: shiftTable,
  13406. mantissaTable: mantissaTable,
  13407. exponentTable: exponentTable,
  13408. offsetTable: offsetTable
  13409. };
  13410. }
  13411. /**
  13412. * Returns a half precision floating point value (FP16) from the given single
  13413. * precision floating point value (FP32).
  13414. *
  13415. * @param {number} val - A single precision floating point value.
  13416. * @return {number} The FP16 value.
  13417. */
  13418. function toHalfFloat( val ) {
  13419. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13420. val = clamp( val, -65504, 65504 );
  13421. _tables.floatView[ 0 ] = val;
  13422. const f = _tables.uint32View[ 0 ];
  13423. const e = ( f >> 23 ) & 0x1ff;
  13424. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13425. }
  13426. /**
  13427. * Returns a single precision floating point value (FP32) from the given half
  13428. * precision floating point value (FP16).
  13429. *
  13430. * @param {number} val - A half precision floating point value.
  13431. * @return {number} The FP32 value.
  13432. */
  13433. function fromHalfFloat( val ) {
  13434. const m = val >> 10;
  13435. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13436. return _tables.floatView[ 0 ];
  13437. }
  13438. /**
  13439. * A class containing utility functions for data.
  13440. *
  13441. * @hideconstructor
  13442. */
  13443. class DataUtils {
  13444. /**
  13445. * Returns a half precision floating point value (FP16) from the given single
  13446. * precision floating point value (FP32).
  13447. *
  13448. * @param {number} val - A single precision floating point value.
  13449. * @return {number} The FP16 value.
  13450. */
  13451. static toHalfFloat( val ) {
  13452. return toHalfFloat( val );
  13453. }
  13454. /**
  13455. * Returns a single precision floating point value (FP32) from the given half
  13456. * precision floating point value (FP16).
  13457. *
  13458. * @param {number} val - A half precision floating point value.
  13459. * @return {number} The FP32 value.
  13460. */
  13461. static fromHalfFloat( val ) {
  13462. return fromHalfFloat( val );
  13463. }
  13464. }
  13465. const _vector$9 = /*@__PURE__*/ new Vector3();
  13466. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13467. let _id$3 = 0;
  13468. /**
  13469. * This class stores data for an attribute (such as vertex positions, face
  13470. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13471. * a geometry, which allows for more efficient passing of data to the GPU.
  13472. *
  13473. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13474. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13475. */
  13476. class BufferAttribute {
  13477. /**
  13478. * Constructs a new buffer attribute.
  13479. *
  13480. * @param {TypedArray} array - The array holding the attribute data.
  13481. * @param {number} itemSize - The item size.
  13482. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13483. */
  13484. constructor( array, itemSize, normalized = false ) {
  13485. if ( Array.isArray( array ) ) {
  13486. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13487. }
  13488. /**
  13489. * This flag can be used for type testing.
  13490. *
  13491. * @type {boolean}
  13492. * @readonly
  13493. * @default true
  13494. */
  13495. this.isBufferAttribute = true;
  13496. /**
  13497. * The ID of the buffer attribute.
  13498. *
  13499. * @name BufferAttribute#id
  13500. * @type {number}
  13501. * @readonly
  13502. */
  13503. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13504. /**
  13505. * The name of the buffer attribute.
  13506. *
  13507. * @type {string}
  13508. */
  13509. this.name = '';
  13510. /**
  13511. * The array holding the attribute data. It should have `itemSize * numVertices`
  13512. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13513. *
  13514. * @type {TypedArray}
  13515. */
  13516. this.array = array;
  13517. /**
  13518. * The number of values of the array that should be associated with a particular vertex.
  13519. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13520. * normal, or color), then the value should be `3`.
  13521. *
  13522. * @type {number}
  13523. */
  13524. this.itemSize = itemSize;
  13525. /**
  13526. * Represents the number of items this buffer attribute stores. It is internally computed
  13527. * by dividing the `array` length by the `itemSize`.
  13528. *
  13529. * @type {number}
  13530. * @readonly
  13531. */
  13532. this.count = array !== undefined ? array.length / itemSize : 0;
  13533. /**
  13534. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13535. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13536. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13537. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13538. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13539. *
  13540. * @type {boolean}
  13541. */
  13542. this.normalized = normalized;
  13543. /**
  13544. * Defines the intended usage pattern of the data store for optimization purposes.
  13545. *
  13546. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13547. * instantiate a new one and set the desired usage before the next render.
  13548. *
  13549. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13550. * @default StaticDrawUsage
  13551. */
  13552. this.usage = StaticDrawUsage;
  13553. /**
  13554. * This can be used to only update some components of stored vectors (for example, just the
  13555. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13556. *
  13557. * @type {Array<Object>}
  13558. */
  13559. this.updateRanges = [];
  13560. /**
  13561. * Configures the bound GPU type for use in shaders.
  13562. *
  13563. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13564. * For lower precision float types, use `Float16BufferAttribute`.
  13565. *
  13566. * @type {(FloatType|IntType)}
  13567. * @default FloatType
  13568. */
  13569. this.gpuType = FloatType;
  13570. /**
  13571. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13572. *
  13573. * @type {number}
  13574. */
  13575. this.version = 0;
  13576. }
  13577. /**
  13578. * A callback function that is executed after the renderer has transferred the attribute
  13579. * array data to the GPU.
  13580. */
  13581. onUploadCallback() {}
  13582. /**
  13583. * Flag to indicate that this attribute has changed and should be re-sent to
  13584. * the GPU. Set this to `true` when you modify the value of the array.
  13585. *
  13586. * @type {number}
  13587. * @default false
  13588. * @param {boolean} value
  13589. */
  13590. set needsUpdate( value ) {
  13591. if ( value === true ) this.version ++;
  13592. }
  13593. /**
  13594. * Sets the usage of this buffer attribute.
  13595. *
  13596. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13597. * @return {BufferAttribute} A reference to this buffer attribute.
  13598. */
  13599. setUsage( value ) {
  13600. this.usage = value;
  13601. return this;
  13602. }
  13603. /**
  13604. * Adds a range of data in the data array to be updated on the GPU.
  13605. *
  13606. * @param {number} start - Position at which to start update.
  13607. * @param {number} count - The number of components to update.
  13608. */
  13609. addUpdateRange( start, count ) {
  13610. this.updateRanges.push( { start, count } );
  13611. }
  13612. /**
  13613. * Clears the update ranges.
  13614. */
  13615. clearUpdateRanges() {
  13616. this.updateRanges.length = 0;
  13617. }
  13618. /**
  13619. * Copies the values of the given buffer attribute to this instance.
  13620. *
  13621. * @param {BufferAttribute} source - The buffer attribute to copy.
  13622. * @return {BufferAttribute} A reference to this instance.
  13623. */
  13624. copy( source ) {
  13625. this.name = source.name;
  13626. this.array = new source.array.constructor( source.array );
  13627. this.itemSize = source.itemSize;
  13628. this.count = source.count;
  13629. this.normalized = source.normalized;
  13630. this.usage = source.usage;
  13631. this.gpuType = source.gpuType;
  13632. return this;
  13633. }
  13634. /**
  13635. * Copies a vector from the given buffer attribute to this one. The start
  13636. * and destination position in the attribute buffers are represented by the
  13637. * given indices.
  13638. *
  13639. * @param {number} index1 - The destination index into this buffer attribute.
  13640. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13641. * @param {number} index2 - The source index into the given buffer attribute.
  13642. * @return {BufferAttribute} A reference to this instance.
  13643. */
  13644. copyAt( index1, attribute, index2 ) {
  13645. index1 *= this.itemSize;
  13646. index2 *= attribute.itemSize;
  13647. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13648. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13649. }
  13650. return this;
  13651. }
  13652. /**
  13653. * Copies the given array data into this buffer attribute.
  13654. *
  13655. * @param {(TypedArray|Array)} array - The array to copy.
  13656. * @return {BufferAttribute} A reference to this instance.
  13657. */
  13658. copyArray( array ) {
  13659. this.array.set( array );
  13660. return this;
  13661. }
  13662. /**
  13663. * Applies the given 3x3 matrix to the given attribute. Works with
  13664. * item size `2` and `3`.
  13665. *
  13666. * @param {Matrix3} m - The matrix to apply.
  13667. * @return {BufferAttribute} A reference to this instance.
  13668. */
  13669. applyMatrix3( m ) {
  13670. if ( this.itemSize === 2 ) {
  13671. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13672. _vector2$1.fromBufferAttribute( this, i );
  13673. _vector2$1.applyMatrix3( m );
  13674. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13675. }
  13676. } else if ( this.itemSize === 3 ) {
  13677. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13678. _vector$9.fromBufferAttribute( this, i );
  13679. _vector$9.applyMatrix3( m );
  13680. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13681. }
  13682. }
  13683. return this;
  13684. }
  13685. /**
  13686. * Applies the given 4x4 matrix to the given attribute. Only works with
  13687. * item size `3`.
  13688. *
  13689. * @param {Matrix4} m - The matrix to apply.
  13690. * @return {BufferAttribute} A reference to this instance.
  13691. */
  13692. applyMatrix4( m ) {
  13693. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13694. _vector$9.fromBufferAttribute( this, i );
  13695. _vector$9.applyMatrix4( m );
  13696. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13697. }
  13698. return this;
  13699. }
  13700. /**
  13701. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13702. * item size `3`.
  13703. *
  13704. * @param {Matrix3} m - The normal matrix to apply.
  13705. * @return {BufferAttribute} A reference to this instance.
  13706. */
  13707. applyNormalMatrix( m ) {
  13708. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13709. _vector$9.fromBufferAttribute( this, i );
  13710. _vector$9.applyNormalMatrix( m );
  13711. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13712. }
  13713. return this;
  13714. }
  13715. /**
  13716. * Applies the given 4x4 matrix to the given attribute. Only works with
  13717. * item size `3` and with direction vectors.
  13718. *
  13719. * @param {Matrix4} m - The matrix to apply.
  13720. * @return {BufferAttribute} A reference to this instance.
  13721. */
  13722. transformDirection( m ) {
  13723. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13724. _vector$9.fromBufferAttribute( this, i );
  13725. _vector$9.transformDirection( m );
  13726. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13727. }
  13728. return this;
  13729. }
  13730. /**
  13731. * Sets the given array data in the buffer attribute.
  13732. *
  13733. * @param {(TypedArray|Array)} value - The array data to set.
  13734. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13735. * @return {BufferAttribute} A reference to this instance.
  13736. */
  13737. set( value, offset = 0 ) {
  13738. // Matching BufferAttribute constructor, do not normalize the array.
  13739. this.array.set( value, offset );
  13740. return this;
  13741. }
  13742. /**
  13743. * Returns the given component of the vector at the given index.
  13744. *
  13745. * @param {number} index - The index into the buffer attribute.
  13746. * @param {number} component - The component index.
  13747. * @return {number} The returned value.
  13748. */
  13749. getComponent( index, component ) {
  13750. let value = this.array[ index * this.itemSize + component ];
  13751. if ( this.normalized ) value = denormalize( value, this.array );
  13752. return value;
  13753. }
  13754. /**
  13755. * Sets the given value to the given component of the vector at the given index.
  13756. *
  13757. * @param {number} index - The index into the buffer attribute.
  13758. * @param {number} component - The component index.
  13759. * @param {number} value - The value to set.
  13760. * @return {BufferAttribute} A reference to this instance.
  13761. */
  13762. setComponent( index, component, value ) {
  13763. if ( this.normalized ) value = normalize( value, this.array );
  13764. this.array[ index * this.itemSize + component ] = value;
  13765. return this;
  13766. }
  13767. /**
  13768. * Returns the x component of the vector at the given index.
  13769. *
  13770. * @param {number} index - The index into the buffer attribute.
  13771. * @return {number} The x component.
  13772. */
  13773. getX( index ) {
  13774. let x = this.array[ index * this.itemSize ];
  13775. if ( this.normalized ) x = denormalize( x, this.array );
  13776. return x;
  13777. }
  13778. /**
  13779. * Sets the x component of the vector at the given index.
  13780. *
  13781. * @param {number} index - The index into the buffer attribute.
  13782. * @param {number} x - The value to set.
  13783. * @return {BufferAttribute} A reference to this instance.
  13784. */
  13785. setX( index, x ) {
  13786. if ( this.normalized ) x = normalize( x, this.array );
  13787. this.array[ index * this.itemSize ] = x;
  13788. return this;
  13789. }
  13790. /**
  13791. * Returns the y component of the vector at the given index.
  13792. *
  13793. * @param {number} index - The index into the buffer attribute.
  13794. * @return {number} The y component.
  13795. */
  13796. getY( index ) {
  13797. let y = this.array[ index * this.itemSize + 1 ];
  13798. if ( this.normalized ) y = denormalize( y, this.array );
  13799. return y;
  13800. }
  13801. /**
  13802. * Sets the y component of the vector at the given index.
  13803. *
  13804. * @param {number} index - The index into the buffer attribute.
  13805. * @param {number} y - The value to set.
  13806. * @return {BufferAttribute} A reference to this instance.
  13807. */
  13808. setY( index, y ) {
  13809. if ( this.normalized ) y = normalize( y, this.array );
  13810. this.array[ index * this.itemSize + 1 ] = y;
  13811. return this;
  13812. }
  13813. /**
  13814. * Returns the z component of the vector at the given index.
  13815. *
  13816. * @param {number} index - The index into the buffer attribute.
  13817. * @return {number} The z component.
  13818. */
  13819. getZ( index ) {
  13820. let z = this.array[ index * this.itemSize + 2 ];
  13821. if ( this.normalized ) z = denormalize( z, this.array );
  13822. return z;
  13823. }
  13824. /**
  13825. * Sets the z component of the vector at the given index.
  13826. *
  13827. * @param {number} index - The index into the buffer attribute.
  13828. * @param {number} z - The value to set.
  13829. * @return {BufferAttribute} A reference to this instance.
  13830. */
  13831. setZ( index, z ) {
  13832. if ( this.normalized ) z = normalize( z, this.array );
  13833. this.array[ index * this.itemSize + 2 ] = z;
  13834. return this;
  13835. }
  13836. /**
  13837. * Returns the w component of the vector at the given index.
  13838. *
  13839. * @param {number} index - The index into the buffer attribute.
  13840. * @return {number} The w component.
  13841. */
  13842. getW( index ) {
  13843. let w = this.array[ index * this.itemSize + 3 ];
  13844. if ( this.normalized ) w = denormalize( w, this.array );
  13845. return w;
  13846. }
  13847. /**
  13848. * Sets the w component of the vector at the given index.
  13849. *
  13850. * @param {number} index - The index into the buffer attribute.
  13851. * @param {number} w - The value to set.
  13852. * @return {BufferAttribute} A reference to this instance.
  13853. */
  13854. setW( index, w ) {
  13855. if ( this.normalized ) w = normalize( w, this.array );
  13856. this.array[ index * this.itemSize + 3 ] = w;
  13857. return this;
  13858. }
  13859. /**
  13860. * Sets the x and y component of the vector at the given index.
  13861. *
  13862. * @param {number} index - The index into the buffer attribute.
  13863. * @param {number} x - The value for the x component to set.
  13864. * @param {number} y - The value for the y component to set.
  13865. * @return {BufferAttribute} A reference to this instance.
  13866. */
  13867. setXY( index, x, y ) {
  13868. index *= this.itemSize;
  13869. if ( this.normalized ) {
  13870. x = normalize( x, this.array );
  13871. y = normalize( y, this.array );
  13872. }
  13873. this.array[ index + 0 ] = x;
  13874. this.array[ index + 1 ] = y;
  13875. return this;
  13876. }
  13877. /**
  13878. * Sets the x, y and z component of the vector at the given index.
  13879. *
  13880. * @param {number} index - The index into the buffer attribute.
  13881. * @param {number} x - The value for the x component to set.
  13882. * @param {number} y - The value for the y component to set.
  13883. * @param {number} z - The value for the z component to set.
  13884. * @return {BufferAttribute} A reference to this instance.
  13885. */
  13886. setXYZ( index, x, y, z ) {
  13887. index *= this.itemSize;
  13888. if ( this.normalized ) {
  13889. x = normalize( x, this.array );
  13890. y = normalize( y, this.array );
  13891. z = normalize( z, this.array );
  13892. }
  13893. this.array[ index + 0 ] = x;
  13894. this.array[ index + 1 ] = y;
  13895. this.array[ index + 2 ] = z;
  13896. return this;
  13897. }
  13898. /**
  13899. * Sets the x, y, z and w component of the vector at the given index.
  13900. *
  13901. * @param {number} index - The index into the buffer attribute.
  13902. * @param {number} x - The value for the x component to set.
  13903. * @param {number} y - The value for the y component to set.
  13904. * @param {number} z - The value for the z component to set.
  13905. * @param {number} w - The value for the w component to set.
  13906. * @return {BufferAttribute} A reference to this instance.
  13907. */
  13908. setXYZW( index, x, y, z, w ) {
  13909. index *= this.itemSize;
  13910. if ( this.normalized ) {
  13911. x = normalize( x, this.array );
  13912. y = normalize( y, this.array );
  13913. z = normalize( z, this.array );
  13914. w = normalize( w, this.array );
  13915. }
  13916. this.array[ index + 0 ] = x;
  13917. this.array[ index + 1 ] = y;
  13918. this.array[ index + 2 ] = z;
  13919. this.array[ index + 3 ] = w;
  13920. return this;
  13921. }
  13922. /**
  13923. * Sets the given callback function that is executed after the Renderer has transferred
  13924. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13925. * the upload when attribute data are not needed anymore on the CPU side.
  13926. *
  13927. * @param {Function} callback - The `onUpload()` callback.
  13928. * @return {BufferAttribute} A reference to this instance.
  13929. */
  13930. onUpload( callback ) {
  13931. this.onUploadCallback = callback;
  13932. return this;
  13933. }
  13934. /**
  13935. * Returns a new buffer attribute with copied values from this instance.
  13936. *
  13937. * @return {BufferAttribute} A clone of this instance.
  13938. */
  13939. clone() {
  13940. return new this.constructor( this.array, this.itemSize ).copy( this );
  13941. }
  13942. /**
  13943. * Serializes the buffer attribute into JSON.
  13944. *
  13945. * @return {Object} A JSON object representing the serialized buffer attribute.
  13946. */
  13947. toJSON() {
  13948. const data = {
  13949. itemSize: this.itemSize,
  13950. type: this.array.constructor.name,
  13951. array: Array.from( this.array ),
  13952. normalized: this.normalized
  13953. };
  13954. if ( this.name !== '' ) data.name = this.name;
  13955. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13956. return data;
  13957. }
  13958. }
  13959. /**
  13960. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13961. * a plain `Array` instance.
  13962. *
  13963. * @augments BufferAttribute
  13964. */
  13965. class Int8BufferAttribute extends BufferAttribute {
  13966. /**
  13967. * Constructs a new buffer attribute.
  13968. *
  13969. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13970. * @param {number} itemSize - The item size.
  13971. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13972. */
  13973. constructor( array, itemSize, normalized ) {
  13974. super( new Int8Array( array ), itemSize, normalized );
  13975. }
  13976. }
  13977. /**
  13978. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13979. * a plain `Array` instance.
  13980. *
  13981. * @augments BufferAttribute
  13982. */
  13983. class Uint8BufferAttribute extends BufferAttribute {
  13984. /**
  13985. * Constructs a new buffer attribute.
  13986. *
  13987. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13988. * @param {number} itemSize - The item size.
  13989. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13990. */
  13991. constructor( array, itemSize, normalized ) {
  13992. super( new Uint8Array( array ), itemSize, normalized );
  13993. }
  13994. }
  13995. /**
  13996. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13997. * a plain `Array` instance.
  13998. *
  13999. * @augments BufferAttribute
  14000. */
  14001. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14002. /**
  14003. * Constructs a new buffer attribute.
  14004. *
  14005. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14006. * @param {number} itemSize - The item size.
  14007. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14008. */
  14009. constructor( array, itemSize, normalized ) {
  14010. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14011. }
  14012. }
  14013. /**
  14014. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14015. * a plain `Array` instance.
  14016. *
  14017. * @augments BufferAttribute
  14018. */
  14019. class Int16BufferAttribute extends BufferAttribute {
  14020. /**
  14021. * Constructs a new buffer attribute.
  14022. *
  14023. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14024. * @param {number} itemSize - The item size.
  14025. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14026. */
  14027. constructor( array, itemSize, normalized ) {
  14028. super( new Int16Array( array ), itemSize, normalized );
  14029. }
  14030. }
  14031. /**
  14032. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14033. * a plain `Array` instance.
  14034. *
  14035. * @augments BufferAttribute
  14036. */
  14037. class Uint16BufferAttribute extends BufferAttribute {
  14038. /**
  14039. * Constructs a new buffer attribute.
  14040. *
  14041. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14042. * @param {number} itemSize - The item size.
  14043. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14044. */
  14045. constructor( array, itemSize, normalized ) {
  14046. super( new Uint16Array( array ), itemSize, normalized );
  14047. }
  14048. }
  14049. /**
  14050. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14051. * a plain `Array` instance.
  14052. *
  14053. * @augments BufferAttribute
  14054. */
  14055. class Int32BufferAttribute extends BufferAttribute {
  14056. /**
  14057. * Constructs a new buffer attribute.
  14058. *
  14059. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14060. * @param {number} itemSize - The item size.
  14061. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14062. */
  14063. constructor( array, itemSize, normalized ) {
  14064. super( new Int32Array( array ), itemSize, normalized );
  14065. }
  14066. }
  14067. /**
  14068. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14069. * a plain `Array` instance.
  14070. *
  14071. * @augments BufferAttribute
  14072. */
  14073. class Uint32BufferAttribute extends BufferAttribute {
  14074. /**
  14075. * Constructs a new buffer attribute.
  14076. *
  14077. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14078. * @param {number} itemSize - The item size.
  14079. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14080. */
  14081. constructor( array, itemSize, normalized ) {
  14082. super( new Uint32Array( array ), itemSize, normalized );
  14083. }
  14084. }
  14085. /**
  14086. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14087. * a plain `Array` instance.
  14088. *
  14089. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14090. * browser support is still problematic.
  14091. *
  14092. * @augments BufferAttribute
  14093. */
  14094. class Float16BufferAttribute extends BufferAttribute {
  14095. /**
  14096. * Constructs a new buffer attribute.
  14097. *
  14098. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14099. * @param {number} itemSize - The item size.
  14100. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14101. */
  14102. constructor( array, itemSize, normalized ) {
  14103. super( new Uint16Array( array ), itemSize, normalized );
  14104. this.isFloat16BufferAttribute = true;
  14105. }
  14106. getX( index ) {
  14107. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14108. if ( this.normalized ) x = denormalize( x, this.array );
  14109. return x;
  14110. }
  14111. setX( index, x ) {
  14112. if ( this.normalized ) x = normalize( x, this.array );
  14113. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14114. return this;
  14115. }
  14116. getY( index ) {
  14117. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14118. if ( this.normalized ) y = denormalize( y, this.array );
  14119. return y;
  14120. }
  14121. setY( index, y ) {
  14122. if ( this.normalized ) y = normalize( y, this.array );
  14123. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14124. return this;
  14125. }
  14126. getZ( index ) {
  14127. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14128. if ( this.normalized ) z = denormalize( z, this.array );
  14129. return z;
  14130. }
  14131. setZ( index, z ) {
  14132. if ( this.normalized ) z = normalize( z, this.array );
  14133. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14134. return this;
  14135. }
  14136. getW( index ) {
  14137. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14138. if ( this.normalized ) w = denormalize( w, this.array );
  14139. return w;
  14140. }
  14141. setW( index, w ) {
  14142. if ( this.normalized ) w = normalize( w, this.array );
  14143. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14144. return this;
  14145. }
  14146. setXY( index, x, y ) {
  14147. index *= this.itemSize;
  14148. if ( this.normalized ) {
  14149. x = normalize( x, this.array );
  14150. y = normalize( y, this.array );
  14151. }
  14152. this.array[ index + 0 ] = toHalfFloat( x );
  14153. this.array[ index + 1 ] = toHalfFloat( y );
  14154. return this;
  14155. }
  14156. setXYZ( index, x, y, z ) {
  14157. index *= this.itemSize;
  14158. if ( this.normalized ) {
  14159. x = normalize( x, this.array );
  14160. y = normalize( y, this.array );
  14161. z = normalize( z, this.array );
  14162. }
  14163. this.array[ index + 0 ] = toHalfFloat( x );
  14164. this.array[ index + 1 ] = toHalfFloat( y );
  14165. this.array[ index + 2 ] = toHalfFloat( z );
  14166. return this;
  14167. }
  14168. setXYZW( index, x, y, z, w ) {
  14169. index *= this.itemSize;
  14170. if ( this.normalized ) {
  14171. x = normalize( x, this.array );
  14172. y = normalize( y, this.array );
  14173. z = normalize( z, this.array );
  14174. w = normalize( w, this.array );
  14175. }
  14176. this.array[ index + 0 ] = toHalfFloat( x );
  14177. this.array[ index + 1 ] = toHalfFloat( y );
  14178. this.array[ index + 2 ] = toHalfFloat( z );
  14179. this.array[ index + 3 ] = toHalfFloat( w );
  14180. return this;
  14181. }
  14182. }
  14183. /**
  14184. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14185. * a plain `Array` instance.
  14186. *
  14187. * @augments BufferAttribute
  14188. */
  14189. class Float32BufferAttribute extends BufferAttribute {
  14190. /**
  14191. * Constructs a new buffer attribute.
  14192. *
  14193. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14194. * @param {number} itemSize - The item size.
  14195. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14196. */
  14197. constructor( array, itemSize, normalized ) {
  14198. super( new Float32Array( array ), itemSize, normalized );
  14199. }
  14200. }
  14201. let _id$2 = 0;
  14202. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14203. const _obj = /*@__PURE__*/ new Object3D();
  14204. const _offset = /*@__PURE__*/ new Vector3();
  14205. const _box$2 = /*@__PURE__*/ new Box3();
  14206. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14207. const _vector$8 = /*@__PURE__*/ new Vector3();
  14208. /**
  14209. * A representation of mesh, line, or point geometry. Includes vertex
  14210. * positions, face indices, normals, colors, UVs, and custom attributes
  14211. * within buffers, reducing the cost of passing all this data to the GPU.
  14212. *
  14213. * ```js
  14214. * const geometry = new THREE.BufferGeometry();
  14215. * // create a simple square shape. We duplicate the top left and bottom right
  14216. * // vertices because each vertex needs to appear once per triangle.
  14217. * const vertices = new Float32Array( [
  14218. * -1.0, -1.0, 1.0, // v0
  14219. * 1.0, -1.0, 1.0, // v1
  14220. * 1.0, 1.0, 1.0, // v2
  14221. *
  14222. * 1.0, 1.0, 1.0, // v3
  14223. * -1.0, 1.0, 1.0, // v4
  14224. * -1.0, -1.0, 1.0 // v5
  14225. * ] );
  14226. * // itemSize = 3 because there are 3 values (components) per vertex
  14227. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14228. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14229. * const mesh = new THREE.Mesh( geometry, material );
  14230. * ```
  14231. *
  14232. * @augments EventDispatcher
  14233. */
  14234. class BufferGeometry extends EventDispatcher {
  14235. /**
  14236. * Constructs a new geometry.
  14237. */
  14238. constructor() {
  14239. super();
  14240. /**
  14241. * This flag can be used for type testing.
  14242. *
  14243. * @type {boolean}
  14244. * @readonly
  14245. * @default true
  14246. */
  14247. this.isBufferGeometry = true;
  14248. /**
  14249. * The ID of the geometry.
  14250. *
  14251. * @name BufferGeometry#id
  14252. * @type {number}
  14253. * @readonly
  14254. */
  14255. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14256. /**
  14257. * The UUID of the geometry.
  14258. *
  14259. * @type {string}
  14260. * @readonly
  14261. */
  14262. this.uuid = generateUUID();
  14263. /**
  14264. * The name of the geometry.
  14265. *
  14266. * @type {string}
  14267. */
  14268. this.name = '';
  14269. this.type = 'BufferGeometry';
  14270. /**
  14271. * Allows for vertices to be re-used across multiple triangles; this is
  14272. * called using "indexed triangles". Each triangle is associated with the
  14273. * indices of three vertices. This attribute therefore stores the index of
  14274. * each vertex for each triangular face. If this attribute is not set, the
  14275. * renderer assumes that each three contiguous positions represent a single triangle.
  14276. *
  14277. * @type {?BufferAttribute}
  14278. * @default null
  14279. */
  14280. this.index = null;
  14281. /**
  14282. * A (storage) buffer attribute which was generated with a compute shader and
  14283. * now defines indirect draw calls.
  14284. *
  14285. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14286. *
  14287. * @type {?BufferAttribute}
  14288. * @default null
  14289. */
  14290. this.indirect = null;
  14291. /**
  14292. * 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.
  14293. *
  14294. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14295. *
  14296. * @type {number|Array<number>}
  14297. * @default 0
  14298. */
  14299. this.indirectOffset = 0;
  14300. /**
  14301. * This dictionary has as id the name of the attribute to be set and as value
  14302. * the buffer attribute to set it to. Rather than accessing this property directly,
  14303. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14304. *
  14305. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14306. */
  14307. this.attributes = {};
  14308. /**
  14309. * This dictionary holds the morph targets of the geometry.
  14310. *
  14311. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14312. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14313. *
  14314. * @type {Object}
  14315. */
  14316. this.morphAttributes = {};
  14317. /**
  14318. * Used to control the morph target behavior; when set to `true`, the morph
  14319. * target data is treated as relative offsets, rather than as absolute
  14320. * positions/normals.
  14321. *
  14322. * @type {boolean}
  14323. * @default false
  14324. */
  14325. this.morphTargetsRelative = false;
  14326. /**
  14327. * Split the geometry into groups, each of which will be rendered in a
  14328. * separate draw call. This allows an array of materials to be used with the geometry.
  14329. *
  14330. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14331. *
  14332. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14333. * indices, and must not leave vertices or indices unused.
  14334. *
  14335. * @type {Array<Object>}
  14336. */
  14337. this.groups = [];
  14338. /**
  14339. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14340. *
  14341. * @type {?Box3}
  14342. * @default null
  14343. */
  14344. this.boundingBox = null;
  14345. /**
  14346. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14347. *
  14348. * @type {?Sphere}
  14349. * @default null
  14350. */
  14351. this.boundingSphere = null;
  14352. /**
  14353. * Determines the part of the geometry to render. This should not be set directly,
  14354. * instead use `setDrawRange()`.
  14355. *
  14356. * @type {{start:number,count:number}}
  14357. */
  14358. this.drawRange = { start: 0, count: Infinity };
  14359. /**
  14360. * An object that can be used to store custom data about the geometry.
  14361. * It should not hold references to functions as these will not be cloned.
  14362. *
  14363. * @type {Object}
  14364. */
  14365. this.userData = {};
  14366. }
  14367. /**
  14368. * Returns the index of this geometry.
  14369. *
  14370. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14371. */
  14372. getIndex() {
  14373. return this.index;
  14374. }
  14375. /**
  14376. * Sets the given index to this geometry.
  14377. *
  14378. * @param {Array<number>|BufferAttribute} index - The index to set.
  14379. * @return {BufferGeometry} A reference to this instance.
  14380. */
  14381. setIndex( index ) {
  14382. if ( Array.isArray( index ) ) {
  14383. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14384. } else {
  14385. this.index = index;
  14386. }
  14387. return this;
  14388. }
  14389. /**
  14390. * Sets the given indirect attribute to this geometry.
  14391. *
  14392. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14393. * @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.
  14394. * @return {BufferGeometry} A reference to this instance.
  14395. */
  14396. setIndirect( indirect, indirectOffset = 0 ) {
  14397. this.indirect = indirect;
  14398. this.indirectOffset = indirectOffset;
  14399. return this;
  14400. }
  14401. /**
  14402. * Returns the indirect attribute of this geometry.
  14403. *
  14404. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14405. */
  14406. getIndirect() {
  14407. return this.indirect;
  14408. }
  14409. /**
  14410. * Returns the buffer attribute for the given name.
  14411. *
  14412. * @param {string} name - The attribute name.
  14413. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14414. * Returns `undefined` if not attribute has been found.
  14415. */
  14416. getAttribute( name ) {
  14417. return this.attributes[ name ];
  14418. }
  14419. /**
  14420. * Sets the given attribute for the given name.
  14421. *
  14422. * @param {string} name - The attribute name.
  14423. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14424. * @return {BufferGeometry} A reference to this instance.
  14425. */
  14426. setAttribute( name, attribute ) {
  14427. this.attributes[ name ] = attribute;
  14428. return this;
  14429. }
  14430. /**
  14431. * Deletes the attribute for the given name.
  14432. *
  14433. * @param {string} name - The attribute name to delete.
  14434. * @return {BufferGeometry} A reference to this instance.
  14435. */
  14436. deleteAttribute( name ) {
  14437. delete this.attributes[ name ];
  14438. return this;
  14439. }
  14440. /**
  14441. * Returns `true` if this geometry has an attribute for the given name.
  14442. *
  14443. * @param {string} name - The attribute name.
  14444. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14445. */
  14446. hasAttribute( name ) {
  14447. return this.attributes[ name ] !== undefined;
  14448. }
  14449. /**
  14450. * Adds a group to this geometry.
  14451. *
  14452. * @param {number} start - The first element in this draw call. That is the first
  14453. * vertex for non-indexed geometry, otherwise the first triangle index.
  14454. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14455. * @param {number} [materialIndex=0] - The material array index to use.
  14456. */
  14457. addGroup( start, count, materialIndex = 0 ) {
  14458. this.groups.push( {
  14459. start: start,
  14460. count: count,
  14461. materialIndex: materialIndex
  14462. } );
  14463. }
  14464. /**
  14465. * Clears all groups.
  14466. */
  14467. clearGroups() {
  14468. this.groups = [];
  14469. }
  14470. /**
  14471. * Sets the draw range for this geometry.
  14472. *
  14473. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14474. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14475. * For indexed BufferGeometry, `count` is the number of indices to render.
  14476. */
  14477. setDrawRange( start, count ) {
  14478. this.drawRange.start = start;
  14479. this.drawRange.count = count;
  14480. }
  14481. /**
  14482. * Applies the given 4x4 transformation matrix to the geometry.
  14483. *
  14484. * @param {Matrix4} matrix - The matrix to apply.
  14485. * @return {BufferGeometry} A reference to this instance.
  14486. */
  14487. applyMatrix4( matrix ) {
  14488. const position = this.attributes.position;
  14489. if ( position !== undefined ) {
  14490. position.applyMatrix4( matrix );
  14491. position.needsUpdate = true;
  14492. }
  14493. const normal = this.attributes.normal;
  14494. if ( normal !== undefined ) {
  14495. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14496. normal.applyNormalMatrix( normalMatrix );
  14497. normal.needsUpdate = true;
  14498. }
  14499. const tangent = this.attributes.tangent;
  14500. if ( tangent !== undefined ) {
  14501. tangent.transformDirection( matrix );
  14502. tangent.needsUpdate = true;
  14503. }
  14504. if ( this.boundingBox !== null ) {
  14505. this.computeBoundingBox();
  14506. }
  14507. if ( this.boundingSphere !== null ) {
  14508. this.computeBoundingSphere();
  14509. }
  14510. return this;
  14511. }
  14512. /**
  14513. * Applies the rotation represented by the Quaternion to the geometry.
  14514. *
  14515. * @param {Quaternion} q - The Quaternion to apply.
  14516. * @return {BufferGeometry} A reference to this instance.
  14517. */
  14518. applyQuaternion( q ) {
  14519. _m1$2.makeRotationFromQuaternion( q );
  14520. this.applyMatrix4( _m1$2 );
  14521. return this;
  14522. }
  14523. /**
  14524. * Rotates the geometry about the X axis. This is typically done as a one time
  14525. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14526. * real-time mesh rotation.
  14527. *
  14528. * @param {number} angle - The angle in radians.
  14529. * @return {BufferGeometry} A reference to this instance.
  14530. */
  14531. rotateX( angle ) {
  14532. // rotate geometry around world x-axis
  14533. _m1$2.makeRotationX( angle );
  14534. this.applyMatrix4( _m1$2 );
  14535. return this;
  14536. }
  14537. /**
  14538. * Rotates the geometry about the Y axis. This is typically done as a one time
  14539. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14540. * real-time mesh rotation.
  14541. *
  14542. * @param {number} angle - The angle in radians.
  14543. * @return {BufferGeometry} A reference to this instance.
  14544. */
  14545. rotateY( angle ) {
  14546. // rotate geometry around world y-axis
  14547. _m1$2.makeRotationY( angle );
  14548. this.applyMatrix4( _m1$2 );
  14549. return this;
  14550. }
  14551. /**
  14552. * Rotates the geometry about the Z axis. This is typically done as a one time
  14553. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14554. * real-time mesh rotation.
  14555. *
  14556. * @param {number} angle - The angle in radians.
  14557. * @return {BufferGeometry} A reference to this instance.
  14558. */
  14559. rotateZ( angle ) {
  14560. // rotate geometry around world z-axis
  14561. _m1$2.makeRotationZ( angle );
  14562. this.applyMatrix4( _m1$2 );
  14563. return this;
  14564. }
  14565. /**
  14566. * Translates the geometry. This is typically done as a one time
  14567. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14568. * real-time mesh rotation.
  14569. *
  14570. * @param {number} x - The x offset.
  14571. * @param {number} y - The y offset.
  14572. * @param {number} z - The z offset.
  14573. * @return {BufferGeometry} A reference to this instance.
  14574. */
  14575. translate( x, y, z ) {
  14576. // translate geometry
  14577. _m1$2.makeTranslation( x, y, z );
  14578. this.applyMatrix4( _m1$2 );
  14579. return this;
  14580. }
  14581. /**
  14582. * Scales the geometry. This is typically done as a one time
  14583. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14584. * real-time mesh rotation.
  14585. *
  14586. * @param {number} x - The x scale.
  14587. * @param {number} y - The y scale.
  14588. * @param {number} z - The z scale.
  14589. * @return {BufferGeometry} A reference to this instance.
  14590. */
  14591. scale( x, y, z ) {
  14592. // scale geometry
  14593. _m1$2.makeScale( x, y, z );
  14594. this.applyMatrix4( _m1$2 );
  14595. return this;
  14596. }
  14597. /**
  14598. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14599. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14600. * real-time mesh rotation.
  14601. *
  14602. * @param {Vector3} vector - The target point.
  14603. * @return {BufferGeometry} A reference to this instance.
  14604. */
  14605. lookAt( vector ) {
  14606. _obj.lookAt( vector );
  14607. _obj.updateMatrix();
  14608. this.applyMatrix4( _obj.matrix );
  14609. return this;
  14610. }
  14611. /**
  14612. * Center the geometry based on its bounding box.
  14613. *
  14614. * @return {BufferGeometry} A reference to this instance.
  14615. */
  14616. center() {
  14617. this.computeBoundingBox();
  14618. this.boundingBox.getCenter( _offset ).negate();
  14619. this.translate( _offset.x, _offset.y, _offset.z );
  14620. return this;
  14621. }
  14622. /**
  14623. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14624. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14625. * set to `0`.
  14626. *
  14627. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14628. * data from the array. The length of the array must match the vertex count.
  14629. *
  14630. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14631. * @return {BufferGeometry} A reference to this instance.
  14632. */
  14633. setFromPoints( points ) {
  14634. const positionAttribute = this.getAttribute( 'position' );
  14635. if ( positionAttribute === undefined ) {
  14636. const position = [];
  14637. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14638. const point = points[ i ];
  14639. position.push( point.x, point.y, point.z || 0 );
  14640. }
  14641. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14642. } else {
  14643. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14644. for ( let i = 0; i < l; i ++ ) {
  14645. const point = points[ i ];
  14646. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14647. }
  14648. if ( points.length > positionAttribute.count ) {
  14649. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14650. }
  14651. positionAttribute.needsUpdate = true;
  14652. }
  14653. return this;
  14654. }
  14655. /**
  14656. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14657. * The bounding box is not computed by the engine; it must be computed by your app.
  14658. * You may need to recompute the bounding box if the geometry vertices are modified.
  14659. */
  14660. computeBoundingBox() {
  14661. if ( this.boundingBox === null ) {
  14662. this.boundingBox = new Box3();
  14663. }
  14664. const position = this.attributes.position;
  14665. const morphAttributesPosition = this.morphAttributes.position;
  14666. if ( position && position.isGLBufferAttribute ) {
  14667. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14668. this.boundingBox.set(
  14669. new Vector3( - Infinity, - Infinity, - Infinity ),
  14670. new Vector3( + Infinity, + Infinity, + Infinity )
  14671. );
  14672. return;
  14673. }
  14674. if ( position !== undefined ) {
  14675. this.boundingBox.setFromBufferAttribute( position );
  14676. // process morph attributes if present
  14677. if ( morphAttributesPosition ) {
  14678. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14679. const morphAttribute = morphAttributesPosition[ i ];
  14680. _box$2.setFromBufferAttribute( morphAttribute );
  14681. if ( this.morphTargetsRelative ) {
  14682. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14683. this.boundingBox.expandByPoint( _vector$8 );
  14684. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14685. this.boundingBox.expandByPoint( _vector$8 );
  14686. } else {
  14687. this.boundingBox.expandByPoint( _box$2.min );
  14688. this.boundingBox.expandByPoint( _box$2.max );
  14689. }
  14690. }
  14691. }
  14692. } else {
  14693. this.boundingBox.makeEmpty();
  14694. }
  14695. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14696. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14697. }
  14698. }
  14699. /**
  14700. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14701. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14702. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14703. */
  14704. computeBoundingSphere() {
  14705. if ( this.boundingSphere === null ) {
  14706. this.boundingSphere = new Sphere();
  14707. }
  14708. const position = this.attributes.position;
  14709. const morphAttributesPosition = this.morphAttributes.position;
  14710. if ( position && position.isGLBufferAttribute ) {
  14711. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14712. this.boundingSphere.set( new Vector3(), Infinity );
  14713. return;
  14714. }
  14715. if ( position ) {
  14716. // first, find the center of the bounding sphere
  14717. const center = this.boundingSphere.center;
  14718. _box$2.setFromBufferAttribute( position );
  14719. // process morph attributes if present
  14720. if ( morphAttributesPosition ) {
  14721. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14722. const morphAttribute = morphAttributesPosition[ i ];
  14723. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14724. if ( this.morphTargetsRelative ) {
  14725. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14726. _box$2.expandByPoint( _vector$8 );
  14727. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14728. _box$2.expandByPoint( _vector$8 );
  14729. } else {
  14730. _box$2.expandByPoint( _boxMorphTargets.min );
  14731. _box$2.expandByPoint( _boxMorphTargets.max );
  14732. }
  14733. }
  14734. }
  14735. _box$2.getCenter( center );
  14736. // second, try to find a boundingSphere with a radius smaller than the
  14737. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14738. let maxRadiusSq = 0;
  14739. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14740. _vector$8.fromBufferAttribute( position, i );
  14741. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14742. }
  14743. // process morph attributes if present
  14744. if ( morphAttributesPosition ) {
  14745. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14746. const morphAttribute = morphAttributesPosition[ i ];
  14747. const morphTargetsRelative = this.morphTargetsRelative;
  14748. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14749. _vector$8.fromBufferAttribute( morphAttribute, j );
  14750. if ( morphTargetsRelative ) {
  14751. _offset.fromBufferAttribute( position, j );
  14752. _vector$8.add( _offset );
  14753. }
  14754. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14755. }
  14756. }
  14757. }
  14758. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14759. if ( isNaN( this.boundingSphere.radius ) ) {
  14760. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14761. }
  14762. }
  14763. }
  14764. /**
  14765. * Calculates and adds a tangent attribute to this geometry.
  14766. *
  14767. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14768. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14769. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14770. */
  14771. computeTangents() {
  14772. const index = this.index;
  14773. const attributes = this.attributes;
  14774. // based on http://www.terathon.com/code/tangent.html
  14775. // (per vertex tangents)
  14776. if ( index === null ||
  14777. attributes.position === undefined ||
  14778. attributes.normal === undefined ||
  14779. attributes.uv === undefined ) {
  14780. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14781. return;
  14782. }
  14783. const positionAttribute = attributes.position;
  14784. const normalAttribute = attributes.normal;
  14785. const uvAttribute = attributes.uv;
  14786. if ( this.hasAttribute( 'tangent' ) === false ) {
  14787. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14788. }
  14789. const tangentAttribute = this.getAttribute( 'tangent' );
  14790. const tan1 = [], tan2 = [];
  14791. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14792. tan1[ i ] = new Vector3();
  14793. tan2[ i ] = new Vector3();
  14794. }
  14795. const vA = new Vector3(),
  14796. vB = new Vector3(),
  14797. vC = new Vector3(),
  14798. uvA = new Vector2(),
  14799. uvB = new Vector2(),
  14800. uvC = new Vector2(),
  14801. sdir = new Vector3(),
  14802. tdir = new Vector3();
  14803. function handleTriangle( a, b, c ) {
  14804. vA.fromBufferAttribute( positionAttribute, a );
  14805. vB.fromBufferAttribute( positionAttribute, b );
  14806. vC.fromBufferAttribute( positionAttribute, c );
  14807. uvA.fromBufferAttribute( uvAttribute, a );
  14808. uvB.fromBufferAttribute( uvAttribute, b );
  14809. uvC.fromBufferAttribute( uvAttribute, c );
  14810. vB.sub( vA );
  14811. vC.sub( vA );
  14812. uvB.sub( uvA );
  14813. uvC.sub( uvA );
  14814. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14815. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14816. if ( ! isFinite( r ) ) return;
  14817. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14818. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14819. tan1[ a ].add( sdir );
  14820. tan1[ b ].add( sdir );
  14821. tan1[ c ].add( sdir );
  14822. tan2[ a ].add( tdir );
  14823. tan2[ b ].add( tdir );
  14824. tan2[ c ].add( tdir );
  14825. }
  14826. let groups = this.groups;
  14827. if ( groups.length === 0 ) {
  14828. groups = [ {
  14829. start: 0,
  14830. count: index.count
  14831. } ];
  14832. }
  14833. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14834. const group = groups[ i ];
  14835. const start = group.start;
  14836. const count = group.count;
  14837. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14838. handleTriangle(
  14839. index.getX( j + 0 ),
  14840. index.getX( j + 1 ),
  14841. index.getX( j + 2 )
  14842. );
  14843. }
  14844. }
  14845. const tmp = new Vector3(), tmp2 = new Vector3();
  14846. const n = new Vector3(), n2 = new Vector3();
  14847. function handleVertex( v ) {
  14848. n.fromBufferAttribute( normalAttribute, v );
  14849. n2.copy( n );
  14850. const t = tan1[ v ];
  14851. // Gram-Schmidt orthogonalize
  14852. tmp.copy( t );
  14853. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14854. // Calculate handedness
  14855. tmp2.crossVectors( n2, t );
  14856. const test = tmp2.dot( tan2[ v ] );
  14857. const w = ( test < 0.0 ) ? -1 : 1.0;
  14858. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14859. }
  14860. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14861. const group = groups[ i ];
  14862. const start = group.start;
  14863. const count = group.count;
  14864. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14865. handleVertex( index.getX( j + 0 ) );
  14866. handleVertex( index.getX( j + 1 ) );
  14867. handleVertex( index.getX( j + 2 ) );
  14868. }
  14869. }
  14870. }
  14871. /**
  14872. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14873. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14874. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14875. * to be the same as the face normal.
  14876. */
  14877. computeVertexNormals() {
  14878. const index = this.index;
  14879. const positionAttribute = this.getAttribute( 'position' );
  14880. if ( positionAttribute !== undefined ) {
  14881. let normalAttribute = this.getAttribute( 'normal' );
  14882. if ( normalAttribute === undefined ) {
  14883. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14884. this.setAttribute( 'normal', normalAttribute );
  14885. } else {
  14886. // reset existing normals to zero
  14887. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14888. normalAttribute.setXYZ( i, 0, 0, 0 );
  14889. }
  14890. }
  14891. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14892. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14893. const cb = new Vector3(), ab = new Vector3();
  14894. // indexed elements
  14895. if ( index ) {
  14896. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14897. const vA = index.getX( i + 0 );
  14898. const vB = index.getX( i + 1 );
  14899. const vC = index.getX( i + 2 );
  14900. pA.fromBufferAttribute( positionAttribute, vA );
  14901. pB.fromBufferAttribute( positionAttribute, vB );
  14902. pC.fromBufferAttribute( positionAttribute, vC );
  14903. cb.subVectors( pC, pB );
  14904. ab.subVectors( pA, pB );
  14905. cb.cross( ab );
  14906. nA.fromBufferAttribute( normalAttribute, vA );
  14907. nB.fromBufferAttribute( normalAttribute, vB );
  14908. nC.fromBufferAttribute( normalAttribute, vC );
  14909. nA.add( cb );
  14910. nB.add( cb );
  14911. nC.add( cb );
  14912. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14913. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14914. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14915. }
  14916. } else {
  14917. // non-indexed elements (unconnected triangle soup)
  14918. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14919. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14920. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14921. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14922. cb.subVectors( pC, pB );
  14923. ab.subVectors( pA, pB );
  14924. cb.cross( ab );
  14925. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14926. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14927. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14928. }
  14929. }
  14930. this.normalizeNormals();
  14931. normalAttribute.needsUpdate = true;
  14932. }
  14933. }
  14934. /**
  14935. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14936. * correct lighting on the geometry surfaces.
  14937. */
  14938. normalizeNormals() {
  14939. const normals = this.attributes.normal;
  14940. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14941. _vector$8.fromBufferAttribute( normals, i );
  14942. _vector$8.normalize();
  14943. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14944. }
  14945. }
  14946. /**
  14947. * Return a new non-index version of this indexed geometry. If the geometry
  14948. * is already non-indexed, the method is a NOOP.
  14949. *
  14950. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14951. */
  14952. toNonIndexed() {
  14953. function convertBufferAttribute( attribute, indices ) {
  14954. const array = attribute.array;
  14955. const itemSize = attribute.itemSize;
  14956. const normalized = attribute.normalized;
  14957. const array2 = new array.constructor( indices.length * itemSize );
  14958. let index = 0, index2 = 0;
  14959. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14960. if ( attribute.isInterleavedBufferAttribute ) {
  14961. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14962. } else {
  14963. index = indices[ i ] * itemSize;
  14964. }
  14965. for ( let j = 0; j < itemSize; j ++ ) {
  14966. array2[ index2 ++ ] = array[ index ++ ];
  14967. }
  14968. }
  14969. return new BufferAttribute( array2, itemSize, normalized );
  14970. }
  14971. //
  14972. if ( this.index === null ) {
  14973. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14974. return this;
  14975. }
  14976. const geometry2 = new BufferGeometry();
  14977. const indices = this.index.array;
  14978. const attributes = this.attributes;
  14979. // attributes
  14980. for ( const name in attributes ) {
  14981. const attribute = attributes[ name ];
  14982. const newAttribute = convertBufferAttribute( attribute, indices );
  14983. geometry2.setAttribute( name, newAttribute );
  14984. }
  14985. // morph attributes
  14986. const morphAttributes = this.morphAttributes;
  14987. for ( const name in morphAttributes ) {
  14988. const morphArray = [];
  14989. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14990. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14991. const attribute = morphAttribute[ i ];
  14992. const newAttribute = convertBufferAttribute( attribute, indices );
  14993. morphArray.push( newAttribute );
  14994. }
  14995. geometry2.morphAttributes[ name ] = morphArray;
  14996. }
  14997. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14998. // groups
  14999. const groups = this.groups;
  15000. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15001. const group = groups[ i ];
  15002. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15003. }
  15004. return geometry2;
  15005. }
  15006. /**
  15007. * Serializes the geometry into JSON.
  15008. *
  15009. * @return {Object} A JSON object representing the serialized geometry.
  15010. */
  15011. toJSON() {
  15012. const data = {
  15013. metadata: {
  15014. version: 4.7,
  15015. type: 'BufferGeometry',
  15016. generator: 'BufferGeometry.toJSON'
  15017. }
  15018. };
  15019. // standard BufferGeometry serialization
  15020. data.uuid = this.uuid;
  15021. data.type = this.type;
  15022. if ( this.name !== '' ) data.name = this.name;
  15023. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15024. if ( this.parameters !== undefined ) {
  15025. const parameters = this.parameters;
  15026. for ( const key in parameters ) {
  15027. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15028. }
  15029. return data;
  15030. }
  15031. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15032. data.data = { attributes: {} };
  15033. const index = this.index;
  15034. if ( index !== null ) {
  15035. data.data.index = {
  15036. type: index.array.constructor.name,
  15037. array: Array.prototype.slice.call( index.array )
  15038. };
  15039. }
  15040. const attributes = this.attributes;
  15041. for ( const key in attributes ) {
  15042. const attribute = attributes[ key ];
  15043. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15044. }
  15045. const morphAttributes = {};
  15046. let hasMorphAttributes = false;
  15047. for ( const key in this.morphAttributes ) {
  15048. const attributeArray = this.morphAttributes[ key ];
  15049. const array = [];
  15050. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15051. const attribute = attributeArray[ i ];
  15052. array.push( attribute.toJSON( data.data ) );
  15053. }
  15054. if ( array.length > 0 ) {
  15055. morphAttributes[ key ] = array;
  15056. hasMorphAttributes = true;
  15057. }
  15058. }
  15059. if ( hasMorphAttributes ) {
  15060. data.data.morphAttributes = morphAttributes;
  15061. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15062. }
  15063. const groups = this.groups;
  15064. if ( groups.length > 0 ) {
  15065. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15066. }
  15067. const boundingSphere = this.boundingSphere;
  15068. if ( boundingSphere !== null ) {
  15069. data.data.boundingSphere = boundingSphere.toJSON();
  15070. }
  15071. return data;
  15072. }
  15073. /**
  15074. * Returns a new geometry with copied values from this instance.
  15075. *
  15076. * @return {BufferGeometry} A clone of this instance.
  15077. */
  15078. clone() {
  15079. return new this.constructor().copy( this );
  15080. }
  15081. /**
  15082. * Copies the values of the given geometry to this instance.
  15083. *
  15084. * @param {BufferGeometry} source - The geometry to copy.
  15085. * @return {BufferGeometry} A reference to this instance.
  15086. */
  15087. copy( source ) {
  15088. // reset
  15089. this.index = null;
  15090. this.attributes = {};
  15091. this.morphAttributes = {};
  15092. this.groups = [];
  15093. this.boundingBox = null;
  15094. this.boundingSphere = null;
  15095. // used for storing cloned, shared data
  15096. const data = {};
  15097. // name
  15098. this.name = source.name;
  15099. // index
  15100. const index = source.index;
  15101. if ( index !== null ) {
  15102. this.setIndex( index.clone() );
  15103. }
  15104. // attributes
  15105. const attributes = source.attributes;
  15106. for ( const name in attributes ) {
  15107. const attribute = attributes[ name ];
  15108. this.setAttribute( name, attribute.clone( data ) );
  15109. }
  15110. // morph attributes
  15111. const morphAttributes = source.morphAttributes;
  15112. for ( const name in morphAttributes ) {
  15113. const array = [];
  15114. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15115. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15116. array.push( morphAttribute[ i ].clone( data ) );
  15117. }
  15118. this.morphAttributes[ name ] = array;
  15119. }
  15120. this.morphTargetsRelative = source.morphTargetsRelative;
  15121. // groups
  15122. const groups = source.groups;
  15123. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15124. const group = groups[ i ];
  15125. this.addGroup( group.start, group.count, group.materialIndex );
  15126. }
  15127. // bounding box
  15128. const boundingBox = source.boundingBox;
  15129. if ( boundingBox !== null ) {
  15130. this.boundingBox = boundingBox.clone();
  15131. }
  15132. // bounding sphere
  15133. const boundingSphere = source.boundingSphere;
  15134. if ( boundingSphere !== null ) {
  15135. this.boundingSphere = boundingSphere.clone();
  15136. }
  15137. // draw range
  15138. this.drawRange.start = source.drawRange.start;
  15139. this.drawRange.count = source.drawRange.count;
  15140. // user data
  15141. this.userData = source.userData;
  15142. return this;
  15143. }
  15144. /**
  15145. * Frees the GPU-related resources allocated by this instance. Call this
  15146. * method whenever this instance is no longer used in your app.
  15147. *
  15148. * @fires BufferGeometry#dispose
  15149. */
  15150. dispose() {
  15151. this.dispatchEvent( { type: 'dispose' } );
  15152. }
  15153. }
  15154. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15155. const _ray$3 = /*@__PURE__*/ new Ray();
  15156. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15157. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15158. const _vA$1 = /*@__PURE__*/ new Vector3();
  15159. const _vB$1 = /*@__PURE__*/ new Vector3();
  15160. const _vC$1 = /*@__PURE__*/ new Vector3();
  15161. const _tempA = /*@__PURE__*/ new Vector3();
  15162. const _morphA = /*@__PURE__*/ new Vector3();
  15163. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15164. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15165. /**
  15166. * Class representing triangular polygon mesh based objects.
  15167. *
  15168. * ```js
  15169. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15170. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15171. * const mesh = new THREE.Mesh( geometry, material );
  15172. * scene.add( mesh );
  15173. * ```
  15174. *
  15175. * @augments Object3D
  15176. */
  15177. class Mesh extends Object3D {
  15178. /**
  15179. * Constructs a new mesh.
  15180. *
  15181. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15182. * @param {Material|Array<Material>} [material] - The mesh material.
  15183. */
  15184. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15185. super();
  15186. /**
  15187. * This flag can be used for type testing.
  15188. *
  15189. * @type {boolean}
  15190. * @readonly
  15191. * @default true
  15192. */
  15193. this.isMesh = true;
  15194. this.type = 'Mesh';
  15195. /**
  15196. * The mesh geometry.
  15197. *
  15198. * @type {BufferGeometry}
  15199. */
  15200. this.geometry = geometry;
  15201. /**
  15202. * The mesh material.
  15203. *
  15204. * @type {Material|Array<Material>}
  15205. * @default MeshBasicMaterial
  15206. */
  15207. this.material = material;
  15208. /**
  15209. * A dictionary representing the morph targets in the geometry. The key is the
  15210. * morph targets name, the value its attribute index. This member is `undefined`
  15211. * by default and only set when morph targets are detected in the geometry.
  15212. *
  15213. * @type {Object<string,number>|undefined}
  15214. * @default undefined
  15215. */
  15216. this.morphTargetDictionary = undefined;
  15217. /**
  15218. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15219. * is applied. This member is `undefined` by default and only set when morph targets are
  15220. * detected in the geometry.
  15221. *
  15222. * @type {Array<number>|undefined}
  15223. * @default undefined
  15224. */
  15225. this.morphTargetInfluences = undefined;
  15226. /**
  15227. * The number of instances of this mesh.
  15228. * Can only be used with {@link WebGPURenderer}.
  15229. *
  15230. * @type {number}
  15231. * @default 1
  15232. */
  15233. this.count = 1;
  15234. this.updateMorphTargets();
  15235. }
  15236. copy( source, recursive ) {
  15237. super.copy( source, recursive );
  15238. if ( source.morphTargetInfluences !== undefined ) {
  15239. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15240. }
  15241. if ( source.morphTargetDictionary !== undefined ) {
  15242. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15243. }
  15244. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15245. this.geometry = source.geometry;
  15246. return this;
  15247. }
  15248. /**
  15249. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15250. * to make sure existing morph targets can influence this 3D object.
  15251. */
  15252. updateMorphTargets() {
  15253. const geometry = this.geometry;
  15254. const morphAttributes = geometry.morphAttributes;
  15255. const keys = Object.keys( morphAttributes );
  15256. if ( keys.length > 0 ) {
  15257. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15258. if ( morphAttribute !== undefined ) {
  15259. this.morphTargetInfluences = [];
  15260. this.morphTargetDictionary = {};
  15261. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15262. const name = morphAttribute[ m ].name || String( m );
  15263. this.morphTargetInfluences.push( 0 );
  15264. this.morphTargetDictionary[ name ] = m;
  15265. }
  15266. }
  15267. }
  15268. }
  15269. /**
  15270. * Returns the local-space position of the vertex at the given index, taking into
  15271. * account the current animation state of both morph targets and skinning.
  15272. *
  15273. * @param {number} index - The vertex index.
  15274. * @param {Vector3} target - The target object that is used to store the method's result.
  15275. * @return {Vector3} The vertex position in local space.
  15276. */
  15277. getVertexPosition( index, target ) {
  15278. const geometry = this.geometry;
  15279. const position = geometry.attributes.position;
  15280. const morphPosition = geometry.morphAttributes.position;
  15281. const morphTargetsRelative = geometry.morphTargetsRelative;
  15282. target.fromBufferAttribute( position, index );
  15283. const morphInfluences = this.morphTargetInfluences;
  15284. if ( morphPosition && morphInfluences ) {
  15285. _morphA.set( 0, 0, 0 );
  15286. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15287. const influence = morphInfluences[ i ];
  15288. const morphAttribute = morphPosition[ i ];
  15289. if ( influence === 0 ) continue;
  15290. _tempA.fromBufferAttribute( morphAttribute, index );
  15291. if ( morphTargetsRelative ) {
  15292. _morphA.addScaledVector( _tempA, influence );
  15293. } else {
  15294. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15295. }
  15296. }
  15297. target.add( _morphA );
  15298. }
  15299. return target;
  15300. }
  15301. /**
  15302. * Computes intersection points between a casted ray and this line.
  15303. *
  15304. * @param {Raycaster} raycaster - The raycaster.
  15305. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15306. */
  15307. raycast( raycaster, intersects ) {
  15308. const geometry = this.geometry;
  15309. const material = this.material;
  15310. const matrixWorld = this.matrixWorld;
  15311. if ( material === undefined ) return;
  15312. // test with bounding sphere in world space
  15313. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15314. _sphere$6.copy( geometry.boundingSphere );
  15315. _sphere$6.applyMatrix4( matrixWorld );
  15316. // check distance from ray origin to bounding sphere
  15317. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15318. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15319. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15320. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15321. }
  15322. // convert ray to local space of mesh
  15323. _inverseMatrix$3.copy( matrixWorld ).invert();
  15324. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15325. // test with bounding box in local space
  15326. if ( geometry.boundingBox !== null ) {
  15327. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15328. }
  15329. // test for intersections with geometry
  15330. this._computeIntersections( raycaster, intersects, _ray$3 );
  15331. }
  15332. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15333. let intersection;
  15334. const geometry = this.geometry;
  15335. const material = this.material;
  15336. const index = geometry.index;
  15337. const position = geometry.attributes.position;
  15338. const uv = geometry.attributes.uv;
  15339. const uv1 = geometry.attributes.uv1;
  15340. const normal = geometry.attributes.normal;
  15341. const groups = geometry.groups;
  15342. const drawRange = geometry.drawRange;
  15343. if ( index !== null ) {
  15344. // indexed buffer geometry
  15345. if ( Array.isArray( material ) ) {
  15346. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15347. const group = groups[ i ];
  15348. const groupMaterial = material[ group.materialIndex ];
  15349. const start = Math.max( group.start, drawRange.start );
  15350. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15351. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15352. const a = index.getX( j );
  15353. const b = index.getX( j + 1 );
  15354. const c = index.getX( j + 2 );
  15355. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15356. if ( intersection ) {
  15357. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15358. intersection.face.materialIndex = group.materialIndex;
  15359. intersects.push( intersection );
  15360. }
  15361. }
  15362. }
  15363. } else {
  15364. const start = Math.max( 0, drawRange.start );
  15365. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15366. for ( let i = start, il = end; i < il; i += 3 ) {
  15367. const a = index.getX( i );
  15368. const b = index.getX( i + 1 );
  15369. const c = index.getX( i + 2 );
  15370. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15371. if ( intersection ) {
  15372. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15373. intersects.push( intersection );
  15374. }
  15375. }
  15376. }
  15377. } else if ( position !== undefined ) {
  15378. // non-indexed buffer geometry
  15379. if ( Array.isArray( material ) ) {
  15380. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15381. const group = groups[ i ];
  15382. const groupMaterial = material[ group.materialIndex ];
  15383. const start = Math.max( group.start, drawRange.start );
  15384. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15385. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15386. const a = j;
  15387. const b = j + 1;
  15388. const c = j + 2;
  15389. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15390. if ( intersection ) {
  15391. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15392. intersection.face.materialIndex = group.materialIndex;
  15393. intersects.push( intersection );
  15394. }
  15395. }
  15396. }
  15397. } else {
  15398. const start = Math.max( 0, drawRange.start );
  15399. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15400. for ( let i = start, il = end; i < il; i += 3 ) {
  15401. const a = i;
  15402. const b = i + 1;
  15403. const c = i + 2;
  15404. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15405. if ( intersection ) {
  15406. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15407. intersects.push( intersection );
  15408. }
  15409. }
  15410. }
  15411. }
  15412. }
  15413. }
  15414. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15415. let intersect;
  15416. if ( material.side === BackSide ) {
  15417. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15418. } else {
  15419. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15420. }
  15421. if ( intersect === null ) return null;
  15422. _intersectionPointWorld.copy( point );
  15423. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15424. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15425. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15426. return {
  15427. distance: distance,
  15428. point: _intersectionPointWorld.clone(),
  15429. object: object
  15430. };
  15431. }
  15432. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15433. object.getVertexPosition( a, _vA$1 );
  15434. object.getVertexPosition( b, _vB$1 );
  15435. object.getVertexPosition( c, _vC$1 );
  15436. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15437. if ( intersection ) {
  15438. const barycoord = new Vector3();
  15439. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15440. if ( uv ) {
  15441. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15442. }
  15443. if ( uv1 ) {
  15444. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15445. }
  15446. if ( normal ) {
  15447. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15448. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15449. intersection.normal.multiplyScalar( -1 );
  15450. }
  15451. }
  15452. const face = {
  15453. a: a,
  15454. b: b,
  15455. c: c,
  15456. normal: new Vector3(),
  15457. materialIndex: 0
  15458. };
  15459. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15460. intersection.face = face;
  15461. intersection.barycoord = barycoord;
  15462. }
  15463. return intersection;
  15464. }
  15465. /**
  15466. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15467. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15468. * of the axes.
  15469. *
  15470. * ```js
  15471. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15472. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15473. * const cube = new THREE.Mesh( geometry, material );
  15474. * scene.add( cube );
  15475. * ```
  15476. *
  15477. * @augments BufferGeometry
  15478. * @demo scenes/geometry-browser.html#BoxGeometry
  15479. */
  15480. class BoxGeometry extends BufferGeometry {
  15481. /**
  15482. * Constructs a new box geometry.
  15483. *
  15484. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15485. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15486. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15487. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15488. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15489. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15490. */
  15491. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15492. super();
  15493. this.type = 'BoxGeometry';
  15494. /**
  15495. * Holds the constructor parameters that have been
  15496. * used to generate the geometry. Any modification
  15497. * after instantiation does not change the geometry.
  15498. *
  15499. * @type {Object}
  15500. */
  15501. this.parameters = {
  15502. width: width,
  15503. height: height,
  15504. depth: depth,
  15505. widthSegments: widthSegments,
  15506. heightSegments: heightSegments,
  15507. depthSegments: depthSegments
  15508. };
  15509. const scope = this;
  15510. // segments
  15511. widthSegments = Math.floor( widthSegments );
  15512. heightSegments = Math.floor( heightSegments );
  15513. depthSegments = Math.floor( depthSegments );
  15514. // buffers
  15515. const indices = [];
  15516. const vertices = [];
  15517. const normals = [];
  15518. const uvs = [];
  15519. // helper variables
  15520. let numberOfVertices = 0;
  15521. let groupStart = 0;
  15522. // build each side of the box geometry
  15523. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15524. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15525. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15526. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15527. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15528. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15529. // build geometry
  15530. this.setIndex( indices );
  15531. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15532. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15533. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15534. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15535. const segmentWidth = width / gridX;
  15536. const segmentHeight = height / gridY;
  15537. const widthHalf = width / 2;
  15538. const heightHalf = height / 2;
  15539. const depthHalf = depth / 2;
  15540. const gridX1 = gridX + 1;
  15541. const gridY1 = gridY + 1;
  15542. let vertexCounter = 0;
  15543. let groupCount = 0;
  15544. const vector = new Vector3();
  15545. // generate vertices, normals and uvs
  15546. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15547. const y = iy * segmentHeight - heightHalf;
  15548. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15549. const x = ix * segmentWidth - widthHalf;
  15550. // set values to correct vector component
  15551. vector[ u ] = x * udir;
  15552. vector[ v ] = y * vdir;
  15553. vector[ w ] = depthHalf;
  15554. // now apply vector to vertex buffer
  15555. vertices.push( vector.x, vector.y, vector.z );
  15556. // set values to correct vector component
  15557. vector[ u ] = 0;
  15558. vector[ v ] = 0;
  15559. vector[ w ] = depth > 0 ? 1 : -1;
  15560. // now apply vector to normal buffer
  15561. normals.push( vector.x, vector.y, vector.z );
  15562. // uvs
  15563. uvs.push( ix / gridX );
  15564. uvs.push( 1 - ( iy / gridY ) );
  15565. // counters
  15566. vertexCounter += 1;
  15567. }
  15568. }
  15569. // indices
  15570. // 1. you need three indices to draw a single face
  15571. // 2. a single segment consists of two faces
  15572. // 3. so we need to generate six (2*3) indices per segment
  15573. for ( let iy = 0; iy < gridY; iy ++ ) {
  15574. for ( let ix = 0; ix < gridX; ix ++ ) {
  15575. const a = numberOfVertices + ix + gridX1 * iy;
  15576. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15577. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15578. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15579. // faces
  15580. indices.push( a, b, d );
  15581. indices.push( b, c, d );
  15582. // increase counter
  15583. groupCount += 6;
  15584. }
  15585. }
  15586. // add a group to the geometry. this will ensure multi material support
  15587. scope.addGroup( groupStart, groupCount, materialIndex );
  15588. // calculate new start value for groups
  15589. groupStart += groupCount;
  15590. // update total number of vertices
  15591. numberOfVertices += vertexCounter;
  15592. }
  15593. }
  15594. copy( source ) {
  15595. super.copy( source );
  15596. this.parameters = Object.assign( {}, source.parameters );
  15597. return this;
  15598. }
  15599. /**
  15600. * Factory method for creating an instance of this class from the given
  15601. * JSON object.
  15602. *
  15603. * @param {Object} data - A JSON object representing the serialized geometry.
  15604. * @return {BoxGeometry} A new instance.
  15605. */
  15606. static fromJSON( data ) {
  15607. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15608. }
  15609. }
  15610. /**
  15611. * Provides utility functions for managing uniforms.
  15612. *
  15613. * @module UniformsUtils
  15614. */
  15615. /**
  15616. * Clones the given uniform definitions by performing a deep-copy. That means
  15617. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15618. * the cloned uniform will refer to a new object reference.
  15619. *
  15620. * @param {Object} src - An object representing uniform definitions.
  15621. * @return {Object} The cloned uniforms.
  15622. */
  15623. function cloneUniforms( src ) {
  15624. const dst = {};
  15625. for ( const u in src ) {
  15626. dst[ u ] = {};
  15627. for ( const p in src[ u ] ) {
  15628. const property = src[ u ][ p ];
  15629. if ( property && ( property.isColor ||
  15630. property.isMatrix3 || property.isMatrix4 ||
  15631. property.isVector2 || property.isVector3 || property.isVector4 ||
  15632. property.isTexture || property.isQuaternion ) ) {
  15633. if ( property.isRenderTargetTexture ) {
  15634. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15635. dst[ u ][ p ] = null;
  15636. } else {
  15637. dst[ u ][ p ] = property.clone();
  15638. }
  15639. } else if ( Array.isArray( property ) ) {
  15640. dst[ u ][ p ] = property.slice();
  15641. } else {
  15642. dst[ u ][ p ] = property;
  15643. }
  15644. }
  15645. }
  15646. return dst;
  15647. }
  15648. /**
  15649. * Merges the given uniform definitions into a single object. Since the
  15650. * method internally uses cloneUniforms(), it performs a deep-copy when
  15651. * producing the merged uniform definitions.
  15652. *
  15653. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15654. * @return {Object} The merged uniforms.
  15655. */
  15656. function mergeUniforms( uniforms ) {
  15657. const merged = {};
  15658. for ( let u = 0; u < uniforms.length; u ++ ) {
  15659. const tmp = cloneUniforms( uniforms[ u ] );
  15660. for ( const p in tmp ) {
  15661. merged[ p ] = tmp[ p ];
  15662. }
  15663. }
  15664. return merged;
  15665. }
  15666. function cloneUniformsGroups( src ) {
  15667. const dst = [];
  15668. for ( let u = 0; u < src.length; u ++ ) {
  15669. dst.push( src[ u ].clone() );
  15670. }
  15671. return dst;
  15672. }
  15673. function getUnlitUniformColorSpace( renderer ) {
  15674. const currentRenderTarget = renderer.getRenderTarget();
  15675. if ( currentRenderTarget === null ) {
  15676. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15677. return renderer.outputColorSpace;
  15678. }
  15679. // https://github.com/mrdoob/three.js/issues/27868
  15680. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15681. return currentRenderTarget.texture.colorSpace;
  15682. }
  15683. return ColorManagement.workingColorSpace;
  15684. }
  15685. // Legacy
  15686. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15687. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15688. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15689. /**
  15690. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15691. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15692. * effect not included with any of the built-in materials.
  15693. *
  15694. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15695. *
  15696. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15697. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15698. * you don't want that, use {@link RawShaderMaterial} instead.
  15699. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15700. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15701. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15702. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15703. * - The loop variable has to be *i*.
  15704. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15705. * value of *i* for the given iteration and can be used in preprocessor
  15706. * statements.
  15707. *
  15708. * ```js
  15709. * const material = new THREE.ShaderMaterial( {
  15710. * uniforms: {
  15711. * time: { value: 1.0 },
  15712. * resolution: { value: new THREE.Vector2() }
  15713. * },
  15714. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15715. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15716. * } );
  15717. * ```
  15718. *
  15719. * @augments Material
  15720. */
  15721. class ShaderMaterial extends Material {
  15722. /**
  15723. * Constructs a new shader material.
  15724. *
  15725. * @param {Object} [parameters] - An object with one or more properties
  15726. * defining the material's appearance. Any property of the material
  15727. * (including any property from inherited materials) can be passed
  15728. * in here. Color values can be passed any type of value accepted
  15729. * by {@link Color#set}.
  15730. */
  15731. constructor( parameters ) {
  15732. super();
  15733. /**
  15734. * This flag can be used for type testing.
  15735. *
  15736. * @type {boolean}
  15737. * @readonly
  15738. * @default true
  15739. */
  15740. this.isShaderMaterial = true;
  15741. this.type = 'ShaderMaterial';
  15742. /**
  15743. * Defines custom constants using `#define` directives within the GLSL code
  15744. * for both the vertex shader and the fragment shader; each key/value pair
  15745. * yields another directive.
  15746. * ```js
  15747. * defines: {
  15748. * FOO: 15,
  15749. * BAR: true
  15750. * }
  15751. * ```
  15752. * Yields the lines:
  15753. * ```
  15754. * #define FOO 15
  15755. * #define BAR true
  15756. * ```
  15757. *
  15758. * @type {Object}
  15759. */
  15760. this.defines = {};
  15761. /**
  15762. * An object of the form:
  15763. * ```js
  15764. * {
  15765. * "uniform1": { value: 1.0 },
  15766. * "uniform2": { value: 2 }
  15767. * }
  15768. * ```
  15769. * specifying the uniforms to be passed to the shader code; keys are uniform
  15770. * names, values are definitions of the form
  15771. * ```
  15772. * {
  15773. * value: 1.0
  15774. * }
  15775. * ```
  15776. * where `value` is the value of the uniform. Names must match the name of
  15777. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15778. * on every frame, so updating the value of the uniform will immediately
  15779. * update the value available to the GLSL code.
  15780. *
  15781. * @type {Object}
  15782. */
  15783. this.uniforms = {};
  15784. /**
  15785. * An array holding uniforms groups for configuring UBOs.
  15786. *
  15787. * @type {Array<UniformsGroup>}
  15788. */
  15789. this.uniformsGroups = [];
  15790. /**
  15791. * Vertex shader GLSL code. This is the actual code for the shader.
  15792. *
  15793. * @type {string}
  15794. */
  15795. this.vertexShader = default_vertex;
  15796. /**
  15797. * Fragment shader GLSL code. This is the actual code for the shader.
  15798. *
  15799. * @type {string}
  15800. */
  15801. this.fragmentShader = default_fragment;
  15802. /**
  15803. * Controls line thickness or lines.
  15804. *
  15805. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15806. * width of one pixel.
  15807. *
  15808. * @type {number}
  15809. * @default 1
  15810. */
  15811. this.linewidth = 1;
  15812. /**
  15813. * Renders the geometry as a wireframe.
  15814. *
  15815. * @type {boolean}
  15816. * @default false
  15817. */
  15818. this.wireframe = false;
  15819. /**
  15820. * Controls the thickness of the wireframe.
  15821. *
  15822. * WebGL and WebGPU ignore this property and always render
  15823. * 1 pixel wide lines.
  15824. *
  15825. * @type {number}
  15826. * @default 1
  15827. */
  15828. this.wireframeLinewidth = 1;
  15829. /**
  15830. * Defines whether the material color is affected by global fog settings; `true`
  15831. * to pass fog uniforms to the shader.
  15832. *
  15833. * Setting this property to `true` requires the definition of fog uniforms. It is
  15834. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  15835. * with predefined fog uniforms.
  15836. *
  15837. * ```js
  15838. * const material = new ShaderMaterial( {
  15839. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  15840. * vertexShader: vertexShader,
  15841. * fragmentShader: fragmentShader,
  15842. * fog: true
  15843. * } );
  15844. * ```
  15845. *
  15846. * @type {boolean}
  15847. * @default false
  15848. */
  15849. this.fog = false;
  15850. /**
  15851. * Defines whether this material uses lighting; `true` to pass uniform data
  15852. * related to lighting to this shader.
  15853. *
  15854. * @type {boolean}
  15855. * @default false
  15856. */
  15857. this.lights = false;
  15858. /**
  15859. * Defines whether this material supports clipping; `true` to let the renderer
  15860. * pass the clippingPlanes uniform.
  15861. *
  15862. * @type {boolean}
  15863. * @default false
  15864. */
  15865. this.clipping = false;
  15866. /**
  15867. * Overwritten and set to `true` by default.
  15868. *
  15869. * @type {boolean}
  15870. * @default true
  15871. */
  15872. this.forceSinglePass = true;
  15873. /**
  15874. * This object allows to enable certain WebGL 2 extensions.
  15875. *
  15876. * - clipCullDistance: set to `true` to use vertex shader clipping
  15877. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15878. *
  15879. * @type {{clipCullDistance:false,multiDraw:false}}
  15880. */
  15881. this.extensions = {
  15882. clipCullDistance: false, // set to use vertex shader clipping
  15883. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15884. };
  15885. /**
  15886. * When the rendered geometry doesn't include these attributes but the
  15887. * material does, these default values will be passed to the shaders. This
  15888. * avoids errors when buffer data is missing.
  15889. *
  15890. * - color: [ 1, 1, 1 ]
  15891. * - uv: [ 0, 0 ]
  15892. * - uv1: [ 0, 0 ]
  15893. *
  15894. * @type {Object}
  15895. */
  15896. this.defaultAttributeValues = {
  15897. 'color': [ 1, 1, 1 ],
  15898. 'uv': [ 0, 0 ],
  15899. 'uv1': [ 0, 0 ]
  15900. };
  15901. /**
  15902. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  15903. * to bind a generic vertex index to an attribute variable.
  15904. *
  15905. * @type {string|undefined}
  15906. * @default undefined
  15907. */
  15908. this.index0AttributeName = undefined;
  15909. /**
  15910. * Can be used to force a uniform update while changing uniforms in
  15911. * {@link Object3D#onBeforeRender}.
  15912. *
  15913. * @type {boolean}
  15914. * @default false
  15915. */
  15916. this.uniformsNeedUpdate = false;
  15917. /**
  15918. * Defines the GLSL version of custom shader code.
  15919. *
  15920. * @type {?(GLSL1|GLSL3)}
  15921. * @default null
  15922. */
  15923. this.glslVersion = null;
  15924. if ( parameters !== undefined ) {
  15925. this.setValues( parameters );
  15926. }
  15927. }
  15928. copy( source ) {
  15929. super.copy( source );
  15930. this.fragmentShader = source.fragmentShader;
  15931. this.vertexShader = source.vertexShader;
  15932. this.uniforms = cloneUniforms( source.uniforms );
  15933. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15934. this.defines = Object.assign( {}, source.defines );
  15935. this.wireframe = source.wireframe;
  15936. this.wireframeLinewidth = source.wireframeLinewidth;
  15937. this.fog = source.fog;
  15938. this.lights = source.lights;
  15939. this.clipping = source.clipping;
  15940. this.extensions = Object.assign( {}, source.extensions );
  15941. this.glslVersion = source.glslVersion;
  15942. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  15943. this.index0AttributeName = source.index0AttributeName;
  15944. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  15945. return this;
  15946. }
  15947. toJSON( meta ) {
  15948. const data = super.toJSON( meta );
  15949. data.glslVersion = this.glslVersion;
  15950. data.uniforms = {};
  15951. for ( const name in this.uniforms ) {
  15952. const uniform = this.uniforms[ name ];
  15953. const value = uniform.value;
  15954. if ( value && value.isTexture ) {
  15955. data.uniforms[ name ] = {
  15956. type: 't',
  15957. value: value.toJSON( meta ).uuid
  15958. };
  15959. } else if ( value && value.isColor ) {
  15960. data.uniforms[ name ] = {
  15961. type: 'c',
  15962. value: value.getHex()
  15963. };
  15964. } else if ( value && value.isVector2 ) {
  15965. data.uniforms[ name ] = {
  15966. type: 'v2',
  15967. value: value.toArray()
  15968. };
  15969. } else if ( value && value.isVector3 ) {
  15970. data.uniforms[ name ] = {
  15971. type: 'v3',
  15972. value: value.toArray()
  15973. };
  15974. } else if ( value && value.isVector4 ) {
  15975. data.uniforms[ name ] = {
  15976. type: 'v4',
  15977. value: value.toArray()
  15978. };
  15979. } else if ( value && value.isMatrix3 ) {
  15980. data.uniforms[ name ] = {
  15981. type: 'm3',
  15982. value: value.toArray()
  15983. };
  15984. } else if ( value && value.isMatrix4 ) {
  15985. data.uniforms[ name ] = {
  15986. type: 'm4',
  15987. value: value.toArray()
  15988. };
  15989. } else {
  15990. data.uniforms[ name ] = {
  15991. value: value
  15992. };
  15993. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15994. }
  15995. }
  15996. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15997. data.vertexShader = this.vertexShader;
  15998. data.fragmentShader = this.fragmentShader;
  15999. data.lights = this.lights;
  16000. data.clipping = this.clipping;
  16001. const extensions = {};
  16002. for ( const key in this.extensions ) {
  16003. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16004. }
  16005. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16006. return data;
  16007. }
  16008. }
  16009. /**
  16010. * Abstract base class for cameras. This class should always be inherited
  16011. * when you build a new camera.
  16012. *
  16013. * @abstract
  16014. * @augments Object3D
  16015. */
  16016. class Camera extends Object3D {
  16017. /**
  16018. * Constructs a new camera.
  16019. */
  16020. constructor() {
  16021. super();
  16022. /**
  16023. * This flag can be used for type testing.
  16024. *
  16025. * @type {boolean}
  16026. * @readonly
  16027. * @default true
  16028. */
  16029. this.isCamera = true;
  16030. this.type = 'Camera';
  16031. /**
  16032. * The inverse of the camera's world matrix.
  16033. *
  16034. * @type {Matrix4}
  16035. */
  16036. this.matrixWorldInverse = new Matrix4();
  16037. /**
  16038. * The camera's projection matrix.
  16039. *
  16040. * @type {Matrix4}
  16041. */
  16042. this.projectionMatrix = new Matrix4();
  16043. /**
  16044. * The inverse of the camera's projection matrix.
  16045. *
  16046. * @type {Matrix4}
  16047. */
  16048. this.projectionMatrixInverse = new Matrix4();
  16049. /**
  16050. * The coordinate system in which the camera is used.
  16051. *
  16052. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16053. */
  16054. this.coordinateSystem = WebGLCoordinateSystem;
  16055. this._reversedDepth = false;
  16056. }
  16057. /**
  16058. * The flag that indicates whether the camera uses a reversed depth buffer.
  16059. *
  16060. * @type {boolean}
  16061. * @default false
  16062. */
  16063. get reversedDepth() {
  16064. return this._reversedDepth;
  16065. }
  16066. copy( source, recursive ) {
  16067. super.copy( source, recursive );
  16068. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16069. this.projectionMatrix.copy( source.projectionMatrix );
  16070. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16071. this.coordinateSystem = source.coordinateSystem;
  16072. return this;
  16073. }
  16074. /**
  16075. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16076. *
  16077. * This method is overwritten since cameras have a different forward vector compared to other
  16078. * 3D objects. A camera looks down its local, negative z-axis by default.
  16079. *
  16080. * @param {Vector3} target - The target vector the result is stored to.
  16081. * @return {Vector3} The 3D object's direction in world space.
  16082. */
  16083. getWorldDirection( target ) {
  16084. return super.getWorldDirection( target ).negate();
  16085. }
  16086. updateMatrixWorld( force ) {
  16087. super.updateMatrixWorld( force );
  16088. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16089. }
  16090. updateWorldMatrix( updateParents, updateChildren ) {
  16091. super.updateWorldMatrix( updateParents, updateChildren );
  16092. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16093. }
  16094. clone() {
  16095. return new this.constructor().copy( this );
  16096. }
  16097. }
  16098. const _v3$1 = /*@__PURE__*/ new Vector3();
  16099. const _minTarget = /*@__PURE__*/ new Vector2();
  16100. const _maxTarget = /*@__PURE__*/ new Vector2();
  16101. /**
  16102. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16103. *
  16104. * This projection mode is designed to mimic the way the human eye sees. It
  16105. * is the most common projection mode used for rendering a 3D scene.
  16106. *
  16107. * ```js
  16108. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16109. * scene.add( camera );
  16110. * ```
  16111. *
  16112. * @augments Camera
  16113. */
  16114. class PerspectiveCamera extends Camera {
  16115. /**
  16116. * Constructs a new perspective camera.
  16117. *
  16118. * @param {number} [fov=50] - The vertical field of view.
  16119. * @param {number} [aspect=1] - The aspect ratio.
  16120. * @param {number} [near=0.1] - The camera's near plane.
  16121. * @param {number} [far=2000] - The camera's far plane.
  16122. */
  16123. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16124. super();
  16125. /**
  16126. * This flag can be used for type testing.
  16127. *
  16128. * @type {boolean}
  16129. * @readonly
  16130. * @default true
  16131. */
  16132. this.isPerspectiveCamera = true;
  16133. this.type = 'PerspectiveCamera';
  16134. /**
  16135. * The vertical field of view, from bottom to top of view,
  16136. * in degrees.
  16137. *
  16138. * @type {number}
  16139. * @default 50
  16140. */
  16141. this.fov = fov;
  16142. /**
  16143. * The zoom factor of the camera.
  16144. *
  16145. * @type {number}
  16146. * @default 1
  16147. */
  16148. this.zoom = 1;
  16149. /**
  16150. * The camera's near plane. The valid range is greater than `0`
  16151. * and less than the current value of {@link PerspectiveCamera#far}.
  16152. *
  16153. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16154. * valid value for a perspective camera's near plane.
  16155. *
  16156. * @type {number}
  16157. * @default 0.1
  16158. */
  16159. this.near = near;
  16160. /**
  16161. * The camera's far plane. Must be greater than the
  16162. * current value of {@link PerspectiveCamera#near}.
  16163. *
  16164. * @type {number}
  16165. * @default 2000
  16166. */
  16167. this.far = far;
  16168. /**
  16169. * Object distance used for stereoscopy and depth-of-field effects. This
  16170. * parameter does not influence the projection matrix unless a
  16171. * {@link StereoCamera} is being used.
  16172. *
  16173. * @type {number}
  16174. * @default 10
  16175. */
  16176. this.focus = 10;
  16177. /**
  16178. * The aspect ratio, usually the canvas width / canvas height.
  16179. *
  16180. * @type {number}
  16181. * @default 1
  16182. */
  16183. this.aspect = aspect;
  16184. /**
  16185. * Represents the frustum window specification. This property should not be edited
  16186. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16187. *
  16188. * @type {?Object}
  16189. * @default null
  16190. */
  16191. this.view = null;
  16192. /**
  16193. * Film size used for the larger axis. Default is `35` (millimeters). This
  16194. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16195. * is set to a nonzero value.
  16196. *
  16197. * @type {number}
  16198. * @default 35
  16199. */
  16200. this.filmGauge = 35;
  16201. /**
  16202. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16203. *
  16204. * @type {number}
  16205. * @default 0
  16206. */
  16207. this.filmOffset = 0;
  16208. this.updateProjectionMatrix();
  16209. }
  16210. copy( source, recursive ) {
  16211. super.copy( source, recursive );
  16212. this.fov = source.fov;
  16213. this.zoom = source.zoom;
  16214. this.near = source.near;
  16215. this.far = source.far;
  16216. this.focus = source.focus;
  16217. this.aspect = source.aspect;
  16218. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16219. this.filmGauge = source.filmGauge;
  16220. this.filmOffset = source.filmOffset;
  16221. return this;
  16222. }
  16223. /**
  16224. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16225. *
  16226. * The default film gauge is 35, so that the focal length can be specified for
  16227. * a 35mm (full frame) camera.
  16228. *
  16229. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16230. */
  16231. setFocalLength( focalLength ) {
  16232. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16233. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16234. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16235. this.updateProjectionMatrix();
  16236. }
  16237. /**
  16238. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16239. * {@link PerspectiveCamera#filmGauge}.
  16240. *
  16241. * @return {number} The computed focal length.
  16242. */
  16243. getFocalLength() {
  16244. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16245. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16246. }
  16247. /**
  16248. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16249. *
  16250. * @return {number} The effective FOV.
  16251. */
  16252. getEffectiveFOV() {
  16253. return RAD2DEG * 2 * Math.atan(
  16254. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16255. }
  16256. /**
  16257. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16258. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16259. *
  16260. * @return {number} The film width.
  16261. */
  16262. getFilmWidth() {
  16263. // film not completely covered in portrait format (aspect < 1)
  16264. return this.filmGauge * Math.min( this.aspect, 1 );
  16265. }
  16266. /**
  16267. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16268. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16269. *
  16270. * @return {number} The film width.
  16271. */
  16272. getFilmHeight() {
  16273. // film not completely covered in landscape format (aspect > 1)
  16274. return this.filmGauge / Math.max( this.aspect, 1 );
  16275. }
  16276. /**
  16277. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16278. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16279. *
  16280. * @param {number} distance - The viewing distance.
  16281. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16282. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16283. */
  16284. getViewBounds( distance, minTarget, maxTarget ) {
  16285. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16286. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16287. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16288. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16289. }
  16290. /**
  16291. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16292. *
  16293. * @param {number} distance - The viewing distance.
  16294. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16295. * @returns {Vector2} The view size.
  16296. */
  16297. getViewSize( distance, target ) {
  16298. this.getViewBounds( distance, _minTarget, _maxTarget );
  16299. return target.subVectors( _maxTarget, _minTarget );
  16300. }
  16301. /**
  16302. * Sets an offset in a larger frustum. This is useful for multi-window or
  16303. * multi-monitor/multi-machine setups.
  16304. *
  16305. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16306. * the monitors are in grid like this
  16307. *```
  16308. * +---+---+---+
  16309. * | A | B | C |
  16310. * +---+---+---+
  16311. * | D | E | F |
  16312. * +---+---+---+
  16313. *```
  16314. * then for each monitor you would call it like this:
  16315. *```js
  16316. * const w = 1920;
  16317. * const h = 1080;
  16318. * const fullWidth = w * 3;
  16319. * const fullHeight = h * 2;
  16320. *
  16321. * // --A--
  16322. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16323. * // --B--
  16324. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16325. * // --C--
  16326. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16327. * // --D--
  16328. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16329. * // --E--
  16330. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16331. * // --F--
  16332. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16333. * ```
  16334. *
  16335. * Note there is no reason monitors have to be the same size or in a grid.
  16336. *
  16337. * @param {number} fullWidth - The full width of multiview setup.
  16338. * @param {number} fullHeight - The full height of multiview setup.
  16339. * @param {number} x - The horizontal offset of the subcamera.
  16340. * @param {number} y - The vertical offset of the subcamera.
  16341. * @param {number} width - The width of subcamera.
  16342. * @param {number} height - The height of subcamera.
  16343. */
  16344. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16345. this.aspect = fullWidth / fullHeight;
  16346. if ( this.view === null ) {
  16347. this.view = {
  16348. enabled: true,
  16349. fullWidth: 1,
  16350. fullHeight: 1,
  16351. offsetX: 0,
  16352. offsetY: 0,
  16353. width: 1,
  16354. height: 1
  16355. };
  16356. }
  16357. this.view.enabled = true;
  16358. this.view.fullWidth = fullWidth;
  16359. this.view.fullHeight = fullHeight;
  16360. this.view.offsetX = x;
  16361. this.view.offsetY = y;
  16362. this.view.width = width;
  16363. this.view.height = height;
  16364. this.updateProjectionMatrix();
  16365. }
  16366. /**
  16367. * Removes the view offset from the projection matrix.
  16368. */
  16369. clearViewOffset() {
  16370. if ( this.view !== null ) {
  16371. this.view.enabled = false;
  16372. }
  16373. this.updateProjectionMatrix();
  16374. }
  16375. /**
  16376. * Updates the camera's projection matrix. Must be called after any change of
  16377. * camera properties.
  16378. */
  16379. updateProjectionMatrix() {
  16380. const near = this.near;
  16381. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16382. let height = 2 * top;
  16383. let width = this.aspect * height;
  16384. let left = -0.5 * width;
  16385. const view = this.view;
  16386. if ( this.view !== null && this.view.enabled ) {
  16387. const fullWidth = view.fullWidth,
  16388. fullHeight = view.fullHeight;
  16389. left += view.offsetX * width / fullWidth;
  16390. top -= view.offsetY * height / fullHeight;
  16391. width *= view.width / fullWidth;
  16392. height *= view.height / fullHeight;
  16393. }
  16394. const skew = this.filmOffset;
  16395. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16396. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16397. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16398. }
  16399. toJSON( meta ) {
  16400. const data = super.toJSON( meta );
  16401. data.object.fov = this.fov;
  16402. data.object.zoom = this.zoom;
  16403. data.object.near = this.near;
  16404. data.object.far = this.far;
  16405. data.object.focus = this.focus;
  16406. data.object.aspect = this.aspect;
  16407. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16408. data.object.filmGauge = this.filmGauge;
  16409. data.object.filmOffset = this.filmOffset;
  16410. return data;
  16411. }
  16412. }
  16413. const fov = -90; // negative fov is not an error
  16414. const aspect = 1;
  16415. /**
  16416. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16417. * cube render target. The render target can then be used as an environment map for rendering
  16418. * realtime reflections in your scene.
  16419. *
  16420. * ```js
  16421. * // Create cube render target
  16422. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16423. *
  16424. * // Create cube camera
  16425. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16426. * scene.add( cubeCamera );
  16427. *
  16428. * // Create car
  16429. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16430. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16431. * scene.add( car );
  16432. *
  16433. * // Update the render target cube
  16434. * car.visible = false;
  16435. * cubeCamera.position.copy( car.position );
  16436. * cubeCamera.update( renderer, scene );
  16437. *
  16438. * // Render the scene
  16439. * car.visible = true;
  16440. * renderer.render( scene, camera );
  16441. * ```
  16442. *
  16443. * @augments Object3D
  16444. */
  16445. class CubeCamera extends Object3D {
  16446. /**
  16447. * Constructs a new cube camera.
  16448. *
  16449. * @param {number} near - The camera's near plane.
  16450. * @param {number} far - The camera's far plane.
  16451. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16452. */
  16453. constructor( near, far, renderTarget ) {
  16454. super();
  16455. this.type = 'CubeCamera';
  16456. /**
  16457. * A reference to the cube render target.
  16458. *
  16459. * @type {WebGLCubeRenderTarget}
  16460. */
  16461. this.renderTarget = renderTarget;
  16462. /**
  16463. * The current active coordinate system.
  16464. *
  16465. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16466. * @default null
  16467. */
  16468. this.coordinateSystem = null;
  16469. /**
  16470. * The current active mipmap level
  16471. *
  16472. * @type {number}
  16473. * @default 0
  16474. */
  16475. this.activeMipmapLevel = 0;
  16476. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16477. cameraPX.layers = this.layers;
  16478. this.add( cameraPX );
  16479. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16480. cameraNX.layers = this.layers;
  16481. this.add( cameraNX );
  16482. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16483. cameraPY.layers = this.layers;
  16484. this.add( cameraPY );
  16485. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16486. cameraNY.layers = this.layers;
  16487. this.add( cameraNY );
  16488. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16489. cameraPZ.layers = this.layers;
  16490. this.add( cameraPZ );
  16491. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16492. cameraNZ.layers = this.layers;
  16493. this.add( cameraNZ );
  16494. }
  16495. /**
  16496. * Must be called when the coordinate system of the cube camera is changed.
  16497. */
  16498. updateCoordinateSystem() {
  16499. const coordinateSystem = this.coordinateSystem;
  16500. const cameras = this.children.concat();
  16501. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16502. for ( const camera of cameras ) this.remove( camera );
  16503. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16504. cameraPX.up.set( 0, 1, 0 );
  16505. cameraPX.lookAt( 1, 0, 0 );
  16506. cameraNX.up.set( 0, 1, 0 );
  16507. cameraNX.lookAt( -1, 0, 0 );
  16508. cameraPY.up.set( 0, 0, -1 );
  16509. cameraPY.lookAt( 0, 1, 0 );
  16510. cameraNY.up.set( 0, 0, 1 );
  16511. cameraNY.lookAt( 0, -1, 0 );
  16512. cameraPZ.up.set( 0, 1, 0 );
  16513. cameraPZ.lookAt( 0, 0, 1 );
  16514. cameraNZ.up.set( 0, 1, 0 );
  16515. cameraNZ.lookAt( 0, 0, -1 );
  16516. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16517. cameraPX.up.set( 0, -1, 0 );
  16518. cameraPX.lookAt( -1, 0, 0 );
  16519. cameraNX.up.set( 0, -1, 0 );
  16520. cameraNX.lookAt( 1, 0, 0 );
  16521. cameraPY.up.set( 0, 0, 1 );
  16522. cameraPY.lookAt( 0, 1, 0 );
  16523. cameraNY.up.set( 0, 0, -1 );
  16524. cameraNY.lookAt( 0, -1, 0 );
  16525. cameraPZ.up.set( 0, -1, 0 );
  16526. cameraPZ.lookAt( 0, 0, 1 );
  16527. cameraNZ.up.set( 0, -1, 0 );
  16528. cameraNZ.lookAt( 0, 0, -1 );
  16529. } else {
  16530. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16531. }
  16532. for ( const camera of cameras ) {
  16533. this.add( camera );
  16534. camera.updateMatrixWorld();
  16535. }
  16536. }
  16537. /**
  16538. * Calling this method will render the given scene with the given renderer
  16539. * into the cube render target of the camera.
  16540. *
  16541. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16542. * @param {Scene} scene - The scene to render.
  16543. */
  16544. update( renderer, scene ) {
  16545. if ( this.parent === null ) this.updateMatrixWorld();
  16546. const { renderTarget, activeMipmapLevel } = this;
  16547. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16548. this.coordinateSystem = renderer.coordinateSystem;
  16549. this.updateCoordinateSystem();
  16550. }
  16551. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16552. const currentRenderTarget = renderer.getRenderTarget();
  16553. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16554. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16555. const currentXrEnabled = renderer.xr.enabled;
  16556. renderer.xr.enabled = false;
  16557. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16558. renderTarget.texture.generateMipmaps = false;
  16559. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16560. renderer.render( scene, cameraPX );
  16561. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16562. renderer.render( scene, cameraNX );
  16563. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16564. renderer.render( scene, cameraPY );
  16565. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16566. renderer.render( scene, cameraNY );
  16567. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16568. renderer.render( scene, cameraPZ );
  16569. // mipmaps are generated during the last call of render()
  16570. // at this point, all sides of the cube render target are defined
  16571. renderTarget.texture.generateMipmaps = generateMipmaps;
  16572. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16573. renderer.render( scene, cameraNZ );
  16574. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16575. renderer.xr.enabled = currentXrEnabled;
  16576. renderTarget.texture.needsPMREMUpdate = true;
  16577. }
  16578. }
  16579. /**
  16580. * Creates a cube texture made up of six images.
  16581. *
  16582. * ```js
  16583. * const loader = new THREE.CubeTextureLoader();
  16584. * loader.setPath( 'textures/cube/pisa/' );
  16585. *
  16586. * const textureCube = loader.load( [
  16587. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16588. * ] );
  16589. *
  16590. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16591. * ```
  16592. *
  16593. * @augments Texture
  16594. */
  16595. class CubeTexture extends Texture {
  16596. /**
  16597. * Constructs a new cube texture.
  16598. *
  16599. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16600. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16601. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16602. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16603. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16604. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16605. * @param {number} [format=RGBAFormat] - The texture format.
  16606. * @param {number} [type=UnsignedByteType] - The texture type.
  16607. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16608. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16609. */
  16610. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16611. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16612. /**
  16613. * This flag can be used for type testing.
  16614. *
  16615. * @type {boolean}
  16616. * @readonly
  16617. * @default true
  16618. */
  16619. this.isCubeTexture = true;
  16620. /**
  16621. * If set to `true`, the texture is flipped along the vertical axis when
  16622. * uploaded to the GPU.
  16623. *
  16624. * Overwritten and set to `false` by default.
  16625. *
  16626. * @type {boolean}
  16627. * @default false
  16628. */
  16629. this.flipY = false;
  16630. }
  16631. /**
  16632. * Alias for {@link CubeTexture#image}.
  16633. *
  16634. * @type {Array<Image>}
  16635. */
  16636. get images() {
  16637. return this.image;
  16638. }
  16639. set images( value ) {
  16640. this.image = value;
  16641. }
  16642. }
  16643. /**
  16644. * A cube render target used in context of {@link WebGLRenderer}.
  16645. *
  16646. * @augments WebGLRenderTarget
  16647. */
  16648. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16649. /**
  16650. * Constructs a new cube render target.
  16651. *
  16652. * @param {number} [size=1] - The size of the render target.
  16653. * @param {RenderTarget~Options} [options] - The configuration object.
  16654. */
  16655. constructor( size = 1, options = {} ) {
  16656. super( size, size, options );
  16657. /**
  16658. * This flag can be used for type testing.
  16659. *
  16660. * @type {boolean}
  16661. * @readonly
  16662. * @default true
  16663. */
  16664. this.isWebGLCubeRenderTarget = true;
  16665. const image = { width: size, height: size, depth: 1 };
  16666. const images = [ image, image, image, image, image, image ];
  16667. /**
  16668. * Overwritten with a different texture type.
  16669. *
  16670. * @type {DataArrayTexture}
  16671. */
  16672. this.texture = new CubeTexture( images );
  16673. this._setTextureOptions( options );
  16674. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16675. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16676. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16677. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16678. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16679. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16680. this.texture.isRenderTargetTexture = true;
  16681. }
  16682. /**
  16683. * Converts the given equirectangular texture to a cube map.
  16684. *
  16685. * @param {WebGLRenderer} renderer - The renderer.
  16686. * @param {Texture} texture - The equirectangular texture.
  16687. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16688. */
  16689. fromEquirectangularTexture( renderer, texture ) {
  16690. this.texture.type = texture.type;
  16691. this.texture.colorSpace = texture.colorSpace;
  16692. this.texture.generateMipmaps = texture.generateMipmaps;
  16693. this.texture.minFilter = texture.minFilter;
  16694. this.texture.magFilter = texture.magFilter;
  16695. const shader = {
  16696. uniforms: {
  16697. tEquirect: { value: null },
  16698. },
  16699. vertexShader: /* glsl */`
  16700. varying vec3 vWorldDirection;
  16701. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16702. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16703. }
  16704. void main() {
  16705. vWorldDirection = transformDirection( position, modelMatrix );
  16706. #include <begin_vertex>
  16707. #include <project_vertex>
  16708. }
  16709. `,
  16710. fragmentShader: /* glsl */`
  16711. uniform sampler2D tEquirect;
  16712. varying vec3 vWorldDirection;
  16713. #include <common>
  16714. void main() {
  16715. vec3 direction = normalize( vWorldDirection );
  16716. vec2 sampleUV = equirectUv( direction );
  16717. gl_FragColor = texture2D( tEquirect, sampleUV );
  16718. }
  16719. `
  16720. };
  16721. const geometry = new BoxGeometry( 5, 5, 5 );
  16722. const material = new ShaderMaterial( {
  16723. name: 'CubemapFromEquirect',
  16724. uniforms: cloneUniforms( shader.uniforms ),
  16725. vertexShader: shader.vertexShader,
  16726. fragmentShader: shader.fragmentShader,
  16727. side: BackSide,
  16728. blending: NoBlending
  16729. } );
  16730. material.uniforms.tEquirect.value = texture;
  16731. const mesh = new Mesh( geometry, material );
  16732. const currentMinFilter = texture.minFilter;
  16733. // Avoid blurred poles
  16734. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16735. const camera = new CubeCamera( 1, 10, this );
  16736. camera.update( renderer, mesh );
  16737. texture.minFilter = currentMinFilter;
  16738. mesh.geometry.dispose();
  16739. mesh.material.dispose();
  16740. return this;
  16741. }
  16742. /**
  16743. * Clears this cube render target.
  16744. *
  16745. * @param {WebGLRenderer} renderer - The renderer.
  16746. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16747. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16748. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16749. */
  16750. clear( renderer, color = true, depth = true, stencil = true ) {
  16751. const currentRenderTarget = renderer.getRenderTarget();
  16752. for ( let i = 0; i < 6; i ++ ) {
  16753. renderer.setRenderTarget( this, i );
  16754. renderer.clear( color, depth, stencil );
  16755. }
  16756. renderer.setRenderTarget( currentRenderTarget );
  16757. }
  16758. }
  16759. /**
  16760. * This is almost identical to an {@link Object3D}. Its purpose is to
  16761. * make working with groups of objects syntactically clearer.
  16762. *
  16763. * ```js
  16764. * // Create a group and add the two cubes.
  16765. * // These cubes can now be rotated / scaled etc as a group.
  16766. * const group = new THREE.Group();
  16767. *
  16768. * group.add( meshA );
  16769. * group.add( meshB );
  16770. *
  16771. * scene.add( group );
  16772. * ```
  16773. *
  16774. * @augments Object3D
  16775. */
  16776. class Group extends Object3D {
  16777. constructor() {
  16778. super();
  16779. /**
  16780. * This flag can be used for type testing.
  16781. *
  16782. * @type {boolean}
  16783. * @readonly
  16784. * @default true
  16785. */
  16786. this.isGroup = true;
  16787. this.type = 'Group';
  16788. }
  16789. }
  16790. const _moveEvent = { type: 'move' };
  16791. /**
  16792. * Class for representing a XR controller with its
  16793. * different coordinate systems.
  16794. *
  16795. * @private
  16796. */
  16797. class WebXRController {
  16798. /**
  16799. * Constructs a new XR controller.
  16800. */
  16801. constructor() {
  16802. /**
  16803. * A group representing the target ray space
  16804. * of the XR controller.
  16805. *
  16806. * @private
  16807. * @type {?Group}
  16808. * @default null
  16809. */
  16810. this._targetRay = null;
  16811. /**
  16812. * A group representing the grip space
  16813. * of the XR controller.
  16814. *
  16815. * @private
  16816. * @type {?Group}
  16817. * @default null
  16818. */
  16819. this._grip = null;
  16820. /**
  16821. * A group representing the hand space
  16822. * of the XR controller.
  16823. *
  16824. * @private
  16825. * @type {?Group}
  16826. * @default null
  16827. */
  16828. this._hand = null;
  16829. }
  16830. /**
  16831. * Returns a group representing the hand space of the XR controller.
  16832. *
  16833. * @return {Group} A group representing the hand space of the XR controller.
  16834. */
  16835. getHandSpace() {
  16836. if ( this._hand === null ) {
  16837. this._hand = new Group();
  16838. this._hand.matrixAutoUpdate = false;
  16839. this._hand.visible = false;
  16840. this._hand.joints = {};
  16841. this._hand.inputState = { pinching: false };
  16842. }
  16843. return this._hand;
  16844. }
  16845. /**
  16846. * Returns a group representing the target ray space of the XR controller.
  16847. *
  16848. * @return {Group} A group representing the target ray space of the XR controller.
  16849. */
  16850. getTargetRaySpace() {
  16851. if ( this._targetRay === null ) {
  16852. this._targetRay = new Group();
  16853. this._targetRay.matrixAutoUpdate = false;
  16854. this._targetRay.visible = false;
  16855. this._targetRay.hasLinearVelocity = false;
  16856. this._targetRay.linearVelocity = new Vector3();
  16857. this._targetRay.hasAngularVelocity = false;
  16858. this._targetRay.angularVelocity = new Vector3();
  16859. }
  16860. return this._targetRay;
  16861. }
  16862. /**
  16863. * Returns a group representing the grip space of the XR controller.
  16864. *
  16865. * @return {Group} A group representing the grip space of the XR controller.
  16866. */
  16867. getGripSpace() {
  16868. if ( this._grip === null ) {
  16869. this._grip = new Group();
  16870. this._grip.matrixAutoUpdate = false;
  16871. this._grip.visible = false;
  16872. this._grip.hasLinearVelocity = false;
  16873. this._grip.linearVelocity = new Vector3();
  16874. this._grip.hasAngularVelocity = false;
  16875. this._grip.angularVelocity = new Vector3();
  16876. }
  16877. return this._grip;
  16878. }
  16879. /**
  16880. * Dispatches the given event to the groups representing
  16881. * the different coordinate spaces of the XR controller.
  16882. *
  16883. * @param {Object} event - The event to dispatch.
  16884. * @return {WebXRController} A reference to this instance.
  16885. */
  16886. dispatchEvent( event ) {
  16887. if ( this._targetRay !== null ) {
  16888. this._targetRay.dispatchEvent( event );
  16889. }
  16890. if ( this._grip !== null ) {
  16891. this._grip.dispatchEvent( event );
  16892. }
  16893. if ( this._hand !== null ) {
  16894. this._hand.dispatchEvent( event );
  16895. }
  16896. return this;
  16897. }
  16898. /**
  16899. * Connects the controller with the given XR input source.
  16900. *
  16901. * @param {XRInputSource} inputSource - The input source.
  16902. * @return {WebXRController} A reference to this instance.
  16903. */
  16904. connect( inputSource ) {
  16905. if ( inputSource && inputSource.hand ) {
  16906. const hand = this._hand;
  16907. if ( hand ) {
  16908. for ( const inputjoint of inputSource.hand.values() ) {
  16909. // Initialize hand with joints when connected
  16910. this._getHandJoint( hand, inputjoint );
  16911. }
  16912. }
  16913. }
  16914. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16915. return this;
  16916. }
  16917. /**
  16918. * Disconnects the controller from the given XR input source.
  16919. *
  16920. * @param {XRInputSource} inputSource - The input source.
  16921. * @return {WebXRController} A reference to this instance.
  16922. */
  16923. disconnect( inputSource ) {
  16924. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16925. if ( this._targetRay !== null ) {
  16926. this._targetRay.visible = false;
  16927. }
  16928. if ( this._grip !== null ) {
  16929. this._grip.visible = false;
  16930. }
  16931. if ( this._hand !== null ) {
  16932. this._hand.visible = false;
  16933. }
  16934. return this;
  16935. }
  16936. /**
  16937. * Updates the controller with the given input source, XR frame and reference space.
  16938. * This updates the transformations of the groups that represent the different
  16939. * coordinate systems of the controller.
  16940. *
  16941. * @param {XRInputSource} inputSource - The input source.
  16942. * @param {XRFrame} frame - The XR frame.
  16943. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16944. * @return {WebXRController} A reference to this instance.
  16945. */
  16946. update( inputSource, frame, referenceSpace ) {
  16947. let inputPose = null;
  16948. let gripPose = null;
  16949. let handPose = null;
  16950. const targetRay = this._targetRay;
  16951. const grip = this._grip;
  16952. const hand = this._hand;
  16953. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16954. if ( hand && inputSource.hand ) {
  16955. handPose = true;
  16956. for ( const inputjoint of inputSource.hand.values() ) {
  16957. // Update the joints groups with the XRJoint poses
  16958. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16959. // The transform of this joint will be updated with the joint pose on each frame
  16960. const joint = this._getHandJoint( hand, inputjoint );
  16961. if ( jointPose !== null ) {
  16962. joint.matrix.fromArray( jointPose.transform.matrix );
  16963. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16964. joint.matrixWorldNeedsUpdate = true;
  16965. joint.jointRadius = jointPose.radius;
  16966. }
  16967. joint.visible = jointPose !== null;
  16968. }
  16969. // Custom events
  16970. // Check pinchz
  16971. const indexTip = hand.joints[ 'index-finger-tip' ];
  16972. const thumbTip = hand.joints[ 'thumb-tip' ];
  16973. const distance = indexTip.position.distanceTo( thumbTip.position );
  16974. const distanceToPinch = 0.02;
  16975. const threshold = 0.005;
  16976. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16977. hand.inputState.pinching = false;
  16978. this.dispatchEvent( {
  16979. type: 'pinchend',
  16980. handedness: inputSource.handedness,
  16981. target: this
  16982. } );
  16983. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16984. hand.inputState.pinching = true;
  16985. this.dispatchEvent( {
  16986. type: 'pinchstart',
  16987. handedness: inputSource.handedness,
  16988. target: this
  16989. } );
  16990. }
  16991. } else {
  16992. if ( grip !== null && inputSource.gripSpace ) {
  16993. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16994. if ( gripPose !== null ) {
  16995. grip.matrix.fromArray( gripPose.transform.matrix );
  16996. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16997. grip.matrixWorldNeedsUpdate = true;
  16998. if ( gripPose.linearVelocity ) {
  16999. grip.hasLinearVelocity = true;
  17000. grip.linearVelocity.copy( gripPose.linearVelocity );
  17001. } else {
  17002. grip.hasLinearVelocity = false;
  17003. }
  17004. if ( gripPose.angularVelocity ) {
  17005. grip.hasAngularVelocity = true;
  17006. grip.angularVelocity.copy( gripPose.angularVelocity );
  17007. } else {
  17008. grip.hasAngularVelocity = false;
  17009. }
  17010. }
  17011. }
  17012. }
  17013. if ( targetRay !== null ) {
  17014. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17015. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17016. if ( inputPose === null && gripPose !== null ) {
  17017. inputPose = gripPose;
  17018. }
  17019. if ( inputPose !== null ) {
  17020. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17021. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17022. targetRay.matrixWorldNeedsUpdate = true;
  17023. if ( inputPose.linearVelocity ) {
  17024. targetRay.hasLinearVelocity = true;
  17025. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17026. } else {
  17027. targetRay.hasLinearVelocity = false;
  17028. }
  17029. if ( inputPose.angularVelocity ) {
  17030. targetRay.hasAngularVelocity = true;
  17031. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17032. } else {
  17033. targetRay.hasAngularVelocity = false;
  17034. }
  17035. this.dispatchEvent( _moveEvent );
  17036. }
  17037. }
  17038. }
  17039. if ( targetRay !== null ) {
  17040. targetRay.visible = ( inputPose !== null );
  17041. }
  17042. if ( grip !== null ) {
  17043. grip.visible = ( gripPose !== null );
  17044. }
  17045. if ( hand !== null ) {
  17046. hand.visible = ( handPose !== null );
  17047. }
  17048. return this;
  17049. }
  17050. /**
  17051. * Returns a group representing the hand joint for the given input joint.
  17052. *
  17053. * @private
  17054. * @param {Group} hand - The group representing the hand space.
  17055. * @param {XRJointSpace} inputjoint - The hand joint data.
  17056. * @return {Group} A group representing the hand joint for the given input joint.
  17057. */
  17058. _getHandJoint( hand, inputjoint ) {
  17059. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17060. const joint = new Group();
  17061. joint.matrixAutoUpdate = false;
  17062. joint.visible = false;
  17063. hand.joints[ inputjoint.jointName ] = joint;
  17064. hand.add( joint );
  17065. }
  17066. return hand.joints[ inputjoint.jointName ];
  17067. }
  17068. }
  17069. /**
  17070. * This class can be used to define an exponential squared fog,
  17071. * which gives a clear view near the camera and a faster than exponentially
  17072. * densening fog farther from the camera.
  17073. *
  17074. * ```js
  17075. * const scene = new THREE.Scene();
  17076. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17077. * ```
  17078. */
  17079. class FogExp2 {
  17080. /**
  17081. * Constructs a new fog.
  17082. *
  17083. * @param {number|Color} color - The fog's color.
  17084. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17085. */
  17086. constructor( color, density = 0.00025 ) {
  17087. /**
  17088. * This flag can be used for type testing.
  17089. *
  17090. * @type {boolean}
  17091. * @readonly
  17092. * @default true
  17093. */
  17094. this.isFogExp2 = true;
  17095. /**
  17096. * The name of the fog.
  17097. *
  17098. * @type {string}
  17099. */
  17100. this.name = '';
  17101. /**
  17102. * The fog's color.
  17103. *
  17104. * @type {Color}
  17105. */
  17106. this.color = new Color( color );
  17107. /**
  17108. * Defines how fast the fog will grow dense.
  17109. *
  17110. * @type {number}
  17111. * @default 0.00025
  17112. */
  17113. this.density = density;
  17114. }
  17115. /**
  17116. * Returns a new fog with copied values from this instance.
  17117. *
  17118. * @return {FogExp2} A clone of this instance.
  17119. */
  17120. clone() {
  17121. return new FogExp2( this.color, this.density );
  17122. }
  17123. /**
  17124. * Serializes the fog into JSON.
  17125. *
  17126. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17127. * @return {Object} A JSON object representing the serialized fog
  17128. */
  17129. toJSON( /* meta */ ) {
  17130. return {
  17131. type: 'FogExp2',
  17132. name: this.name,
  17133. color: this.color.getHex(),
  17134. density: this.density
  17135. };
  17136. }
  17137. }
  17138. /**
  17139. * This class can be used to define a linear fog that grows linearly denser
  17140. * with the distance.
  17141. *
  17142. * ```js
  17143. * const scene = new THREE.Scene();
  17144. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17145. * ```
  17146. */
  17147. class Fog {
  17148. /**
  17149. * Constructs a new fog.
  17150. *
  17151. * @param {number|Color} color - The fog's color.
  17152. * @param {number} [near=1] - The minimum distance to start applying fog.
  17153. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17154. */
  17155. constructor( color, near = 1, far = 1000 ) {
  17156. /**
  17157. * This flag can be used for type testing.
  17158. *
  17159. * @type {boolean}
  17160. * @readonly
  17161. * @default true
  17162. */
  17163. this.isFog = true;
  17164. /**
  17165. * The name of the fog.
  17166. *
  17167. * @type {string}
  17168. */
  17169. this.name = '';
  17170. /**
  17171. * The fog's color.
  17172. *
  17173. * @type {Color}
  17174. */
  17175. this.color = new Color( color );
  17176. /**
  17177. * The minimum distance to start applying fog. Objects that are less than
  17178. * `near` units from the active camera won't be affected by fog.
  17179. *
  17180. * @type {number}
  17181. * @default 1
  17182. */
  17183. this.near = near;
  17184. /**
  17185. * The maximum distance at which fog stops being calculated and applied.
  17186. * Objects that are more than `far` units away from the active camera won't
  17187. * be affected by fog.
  17188. *
  17189. * @type {number}
  17190. * @default 1000
  17191. */
  17192. this.far = far;
  17193. }
  17194. /**
  17195. * Returns a new fog with copied values from this instance.
  17196. *
  17197. * @return {Fog} A clone of this instance.
  17198. */
  17199. clone() {
  17200. return new Fog( this.color, this.near, this.far );
  17201. }
  17202. /**
  17203. * Serializes the fog into JSON.
  17204. *
  17205. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17206. * @return {Object} A JSON object representing the serialized fog
  17207. */
  17208. toJSON( /* meta */ ) {
  17209. return {
  17210. type: 'Fog',
  17211. name: this.name,
  17212. color: this.color.getHex(),
  17213. near: this.near,
  17214. far: this.far
  17215. };
  17216. }
  17217. }
  17218. /**
  17219. * Scenes allow you to set up what is to be rendered and where by three.js.
  17220. * This is where you place 3D objects like meshes, lines or lights.
  17221. *
  17222. * @augments Object3D
  17223. */
  17224. class Scene extends Object3D {
  17225. /**
  17226. * Constructs a new scene.
  17227. */
  17228. constructor() {
  17229. super();
  17230. /**
  17231. * This flag can be used for type testing.
  17232. *
  17233. * @type {boolean}
  17234. * @readonly
  17235. * @default true
  17236. */
  17237. this.isScene = true;
  17238. this.type = 'Scene';
  17239. /**
  17240. * Defines the background of the scene. Valid inputs are:
  17241. *
  17242. * - A color for defining a uniform colored background.
  17243. * - A texture for defining a (flat) textured background.
  17244. * - Cube textures or equirectangular textures for defining a skybox.
  17245. *
  17246. * @type {?(Color|Texture)}
  17247. * @default null
  17248. */
  17249. this.background = null;
  17250. /**
  17251. * Sets the environment map for all physical materials in the scene. However,
  17252. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17253. * material property.
  17254. *
  17255. * @type {?Texture}
  17256. * @default null
  17257. */
  17258. this.environment = null;
  17259. /**
  17260. * A fog instance defining the type of fog that affects everything
  17261. * rendered in the scene.
  17262. *
  17263. * @type {?(Fog|FogExp2)}
  17264. * @default null
  17265. */
  17266. this.fog = null;
  17267. /**
  17268. * Sets the blurriness of the background. Only influences environment maps
  17269. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17270. * and `1`.
  17271. *
  17272. * @type {number}
  17273. * @default 0
  17274. */
  17275. this.backgroundBlurriness = 0;
  17276. /**
  17277. * Attenuates the color of the background. Only applies to background textures.
  17278. *
  17279. * @type {number}
  17280. * @default 1
  17281. */
  17282. this.backgroundIntensity = 1;
  17283. /**
  17284. * The rotation of the background in radians. Only influences environment maps
  17285. * assigned to {@link Scene#background}.
  17286. *
  17287. * @type {Euler}
  17288. * @default (0,0,0)
  17289. */
  17290. this.backgroundRotation = new Euler();
  17291. /**
  17292. * Attenuates the color of the environment. Only influences environment maps
  17293. * assigned to {@link Scene#environment}.
  17294. *
  17295. * @type {number}
  17296. * @default 1
  17297. */
  17298. this.environmentIntensity = 1;
  17299. /**
  17300. * The rotation of the environment map in radians. Only influences physical materials
  17301. * in the scene when {@link Scene#environment} is used.
  17302. *
  17303. * @type {Euler}
  17304. * @default (0,0,0)
  17305. */
  17306. this.environmentRotation = new Euler();
  17307. /**
  17308. * Forces everything in the scene to be rendered with the defined material. It is possible
  17309. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17310. *
  17311. * @type {?Material}
  17312. * @default null
  17313. */
  17314. this.overrideMaterial = null;
  17315. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17316. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17317. }
  17318. }
  17319. copy( source, recursive ) {
  17320. super.copy( source, recursive );
  17321. if ( source.background !== null ) this.background = source.background.clone();
  17322. if ( source.environment !== null ) this.environment = source.environment.clone();
  17323. if ( source.fog !== null ) this.fog = source.fog.clone();
  17324. this.backgroundBlurriness = source.backgroundBlurriness;
  17325. this.backgroundIntensity = source.backgroundIntensity;
  17326. this.backgroundRotation.copy( source.backgroundRotation );
  17327. this.environmentIntensity = source.environmentIntensity;
  17328. this.environmentRotation.copy( source.environmentRotation );
  17329. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17330. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17331. return this;
  17332. }
  17333. toJSON( meta ) {
  17334. const data = super.toJSON( meta );
  17335. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17336. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17337. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17338. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17339. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17340. data.object.environmentRotation = this.environmentRotation.toArray();
  17341. return data;
  17342. }
  17343. }
  17344. /**
  17345. * "Interleaved" means that multiple attributes, possibly of different types,
  17346. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17347. *
  17348. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17349. */
  17350. class InterleavedBuffer {
  17351. /**
  17352. * Constructs a new interleaved buffer.
  17353. *
  17354. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17355. * @param {number} stride - The number of typed-array elements per vertex.
  17356. */
  17357. constructor( array, stride ) {
  17358. /**
  17359. * This flag can be used for type testing.
  17360. *
  17361. * @type {boolean}
  17362. * @readonly
  17363. * @default true
  17364. */
  17365. this.isInterleavedBuffer = true;
  17366. /**
  17367. * A typed array with a shared buffer storing attribute data.
  17368. *
  17369. * @type {TypedArray}
  17370. */
  17371. this.array = array;
  17372. /**
  17373. * The number of typed-array elements per vertex.
  17374. *
  17375. * @type {number}
  17376. */
  17377. this.stride = stride;
  17378. /**
  17379. * The total number of elements in the array
  17380. *
  17381. * @type {number}
  17382. * @readonly
  17383. */
  17384. this.count = array !== undefined ? array.length / stride : 0;
  17385. /**
  17386. * Defines the intended usage pattern of the data store for optimization purposes.
  17387. *
  17388. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17389. * instantiate a new one and set the desired usage before the next render.
  17390. *
  17391. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17392. * @default StaticDrawUsage
  17393. */
  17394. this.usage = StaticDrawUsage;
  17395. /**
  17396. * This can be used to only update some components of stored vectors (for example, just the
  17397. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17398. *
  17399. * @type {Array<Object>}
  17400. */
  17401. this.updateRanges = [];
  17402. /**
  17403. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17404. *
  17405. * @type {number}
  17406. */
  17407. this.version = 0;
  17408. /**
  17409. * The UUID of the interleaved buffer.
  17410. *
  17411. * @type {string}
  17412. * @readonly
  17413. */
  17414. this.uuid = generateUUID();
  17415. }
  17416. /**
  17417. * A callback function that is executed after the renderer has transferred the attribute array
  17418. * data to the GPU.
  17419. */
  17420. onUploadCallback() {}
  17421. /**
  17422. * Flag to indicate that this attribute has changed and should be re-sent to
  17423. * the GPU. Set this to `true` when you modify the value of the array.
  17424. *
  17425. * @type {number}
  17426. * @default false
  17427. * @param {boolean} value
  17428. */
  17429. set needsUpdate( value ) {
  17430. if ( value === true ) this.version ++;
  17431. }
  17432. /**
  17433. * Sets the usage of this interleaved buffer.
  17434. *
  17435. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17436. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17437. */
  17438. setUsage( value ) {
  17439. this.usage = value;
  17440. return this;
  17441. }
  17442. /**
  17443. * Adds a range of data in the data array to be updated on the GPU.
  17444. *
  17445. * @param {number} start - Position at which to start update.
  17446. * @param {number} count - The number of components to update.
  17447. */
  17448. addUpdateRange( start, count ) {
  17449. this.updateRanges.push( { start, count } );
  17450. }
  17451. /**
  17452. * Clears the update ranges.
  17453. */
  17454. clearUpdateRanges() {
  17455. this.updateRanges.length = 0;
  17456. }
  17457. /**
  17458. * Copies the values of the given interleaved buffer to this instance.
  17459. *
  17460. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17461. * @return {InterleavedBuffer} A reference to this instance.
  17462. */
  17463. copy( source ) {
  17464. this.array = new source.array.constructor( source.array );
  17465. this.count = source.count;
  17466. this.stride = source.stride;
  17467. this.usage = source.usage;
  17468. return this;
  17469. }
  17470. /**
  17471. * Copies a vector from the given interleaved buffer to this one. The start
  17472. * and destination position in the attribute buffers are represented by the
  17473. * given indices.
  17474. *
  17475. * @param {number} index1 - The destination index into this interleaved buffer.
  17476. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17477. * @param {number} index2 - The source index into the given interleaved buffer.
  17478. * @return {InterleavedBuffer} A reference to this instance.
  17479. */
  17480. copyAt( index1, interleavedBuffer, index2 ) {
  17481. index1 *= this.stride;
  17482. index2 *= interleavedBuffer.stride;
  17483. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17484. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17485. }
  17486. return this;
  17487. }
  17488. /**
  17489. * Sets the given array data in the interleaved buffer.
  17490. *
  17491. * @param {(TypedArray|Array)} value - The array data to set.
  17492. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17493. * @return {InterleavedBuffer} A reference to this instance.
  17494. */
  17495. set( value, offset = 0 ) {
  17496. this.array.set( value, offset );
  17497. return this;
  17498. }
  17499. /**
  17500. * Returns a new interleaved buffer with copied values from this instance.
  17501. *
  17502. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17503. * @return {InterleavedBuffer} A clone of this instance.
  17504. */
  17505. clone( data ) {
  17506. if ( data.arrayBuffers === undefined ) {
  17507. data.arrayBuffers = {};
  17508. }
  17509. if ( this.array.buffer._uuid === undefined ) {
  17510. this.array.buffer._uuid = generateUUID();
  17511. }
  17512. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17513. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17514. }
  17515. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17516. const ib = new this.constructor( array, this.stride );
  17517. ib.setUsage( this.usage );
  17518. return ib;
  17519. }
  17520. /**
  17521. * Sets the given callback function that is executed after the Renderer has transferred
  17522. * the array data to the GPU. Can be used to perform clean-up operations after
  17523. * the upload when data are not needed anymore on the CPU side.
  17524. *
  17525. * @param {Function} callback - The `onUpload()` callback.
  17526. * @return {InterleavedBuffer} A reference to this instance.
  17527. */
  17528. onUpload( callback ) {
  17529. this.onUploadCallback = callback;
  17530. return this;
  17531. }
  17532. /**
  17533. * Serializes the interleaved buffer into JSON.
  17534. *
  17535. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17536. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17537. */
  17538. toJSON( data ) {
  17539. if ( data.arrayBuffers === undefined ) {
  17540. data.arrayBuffers = {};
  17541. }
  17542. // generate UUID for array buffer if necessary
  17543. if ( this.array.buffer._uuid === undefined ) {
  17544. this.array.buffer._uuid = generateUUID();
  17545. }
  17546. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17547. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17548. }
  17549. //
  17550. return {
  17551. uuid: this.uuid,
  17552. buffer: this.array.buffer._uuid,
  17553. type: this.array.constructor.name,
  17554. stride: this.stride
  17555. };
  17556. }
  17557. }
  17558. const _vector$7 = /*@__PURE__*/ new Vector3();
  17559. /**
  17560. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17561. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17562. * different offsets into the buffer.
  17563. */
  17564. class InterleavedBufferAttribute {
  17565. /**
  17566. * Constructs a new interleaved buffer attribute.
  17567. *
  17568. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17569. * @param {number} itemSize - The item size.
  17570. * @param {number} offset - The attribute offset into the buffer.
  17571. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17572. */
  17573. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17574. /**
  17575. * This flag can be used for type testing.
  17576. *
  17577. * @type {boolean}
  17578. * @readonly
  17579. * @default true
  17580. */
  17581. this.isInterleavedBufferAttribute = true;
  17582. /**
  17583. * The name of the buffer attribute.
  17584. *
  17585. * @type {string}
  17586. */
  17587. this.name = '';
  17588. /**
  17589. * The buffer holding the interleaved data.
  17590. *
  17591. * @type {InterleavedBuffer}
  17592. */
  17593. this.data = interleavedBuffer;
  17594. /**
  17595. * The item size, see {@link BufferAttribute#itemSize}.
  17596. *
  17597. * @type {number}
  17598. */
  17599. this.itemSize = itemSize;
  17600. /**
  17601. * The attribute offset into the buffer.
  17602. *
  17603. * @type {number}
  17604. */
  17605. this.offset = offset;
  17606. /**
  17607. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17608. *
  17609. * @type {InterleavedBuffer}
  17610. */
  17611. this.normalized = normalized;
  17612. }
  17613. /**
  17614. * The item count of this buffer attribute.
  17615. *
  17616. * @type {number}
  17617. * @readonly
  17618. */
  17619. get count() {
  17620. return this.data.count;
  17621. }
  17622. /**
  17623. * The array holding the interleaved buffer attribute data.
  17624. *
  17625. * @type {TypedArray}
  17626. */
  17627. get array() {
  17628. return this.data.array;
  17629. }
  17630. /**
  17631. * Flag to indicate that this attribute has changed and should be re-sent to
  17632. * the GPU. Set this to `true` when you modify the value of the array.
  17633. *
  17634. * @type {number}
  17635. * @default false
  17636. * @param {boolean} value
  17637. */
  17638. set needsUpdate( value ) {
  17639. this.data.needsUpdate = value;
  17640. }
  17641. /**
  17642. * Applies the given 4x4 matrix to the given attribute. Only works with
  17643. * item size `3`.
  17644. *
  17645. * @param {Matrix4} m - The matrix to apply.
  17646. * @return {InterleavedBufferAttribute} A reference to this instance.
  17647. */
  17648. applyMatrix4( m ) {
  17649. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17650. _vector$7.fromBufferAttribute( this, i );
  17651. _vector$7.applyMatrix4( m );
  17652. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17653. }
  17654. return this;
  17655. }
  17656. /**
  17657. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17658. * item size `3`.
  17659. *
  17660. * @param {Matrix3} m - The normal matrix to apply.
  17661. * @return {InterleavedBufferAttribute} A reference to this instance.
  17662. */
  17663. applyNormalMatrix( m ) {
  17664. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17665. _vector$7.fromBufferAttribute( this, i );
  17666. _vector$7.applyNormalMatrix( m );
  17667. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17668. }
  17669. return this;
  17670. }
  17671. /**
  17672. * Applies the given 4x4 matrix to the given attribute. Only works with
  17673. * item size `3` and with direction vectors.
  17674. *
  17675. * @param {Matrix4} m - The matrix to apply.
  17676. * @return {InterleavedBufferAttribute} A reference to this instance.
  17677. */
  17678. transformDirection( m ) {
  17679. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17680. _vector$7.fromBufferAttribute( this, i );
  17681. _vector$7.transformDirection( m );
  17682. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17683. }
  17684. return this;
  17685. }
  17686. /**
  17687. * Returns the given component of the vector at the given index.
  17688. *
  17689. * @param {number} index - The index into the buffer attribute.
  17690. * @param {number} component - The component index.
  17691. * @return {number} The returned value.
  17692. */
  17693. getComponent( index, component ) {
  17694. let value = this.array[ index * this.data.stride + this.offset + component ];
  17695. if ( this.normalized ) value = denormalize( value, this.array );
  17696. return value;
  17697. }
  17698. /**
  17699. * Sets the given value to the given component of the vector at the given index.
  17700. *
  17701. * @param {number} index - The index into the buffer attribute.
  17702. * @param {number} component - The component index.
  17703. * @param {number} value - The value to set.
  17704. * @return {InterleavedBufferAttribute} A reference to this instance.
  17705. */
  17706. setComponent( index, component, value ) {
  17707. if ( this.normalized ) value = normalize( value, this.array );
  17708. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17709. return this;
  17710. }
  17711. /**
  17712. * Sets the x component of the vector at the given index.
  17713. *
  17714. * @param {number} index - The index into the buffer attribute.
  17715. * @param {number} x - The value to set.
  17716. * @return {InterleavedBufferAttribute} A reference to this instance.
  17717. */
  17718. setX( index, x ) {
  17719. if ( this.normalized ) x = normalize( x, this.array );
  17720. this.data.array[ index * this.data.stride + this.offset ] = x;
  17721. return this;
  17722. }
  17723. /**
  17724. * Sets the y component of the vector at the given index.
  17725. *
  17726. * @param {number} index - The index into the buffer attribute.
  17727. * @param {number} y - The value to set.
  17728. * @return {InterleavedBufferAttribute} A reference to this instance.
  17729. */
  17730. setY( index, y ) {
  17731. if ( this.normalized ) y = normalize( y, this.array );
  17732. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17733. return this;
  17734. }
  17735. /**
  17736. * Sets the z component of the vector at the given index.
  17737. *
  17738. * @param {number} index - The index into the buffer attribute.
  17739. * @param {number} z - The value to set.
  17740. * @return {InterleavedBufferAttribute} A reference to this instance.
  17741. */
  17742. setZ( index, z ) {
  17743. if ( this.normalized ) z = normalize( z, this.array );
  17744. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17745. return this;
  17746. }
  17747. /**
  17748. * Sets the w component of the vector at the given index.
  17749. *
  17750. * @param {number} index - The index into the buffer attribute.
  17751. * @param {number} w - The value to set.
  17752. * @return {InterleavedBufferAttribute} A reference to this instance.
  17753. */
  17754. setW( index, w ) {
  17755. if ( this.normalized ) w = normalize( w, this.array );
  17756. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17757. return this;
  17758. }
  17759. /**
  17760. * Returns the x component of the vector at the given index.
  17761. *
  17762. * @param {number} index - The index into the buffer attribute.
  17763. * @return {number} The x component.
  17764. */
  17765. getX( index ) {
  17766. let x = this.data.array[ index * this.data.stride + this.offset ];
  17767. if ( this.normalized ) x = denormalize( x, this.array );
  17768. return x;
  17769. }
  17770. /**
  17771. * Returns the y component of the vector at the given index.
  17772. *
  17773. * @param {number} index - The index into the buffer attribute.
  17774. * @return {number} The y component.
  17775. */
  17776. getY( index ) {
  17777. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17778. if ( this.normalized ) y = denormalize( y, this.array );
  17779. return y;
  17780. }
  17781. /**
  17782. * Returns the z component of the vector at the given index.
  17783. *
  17784. * @param {number} index - The index into the buffer attribute.
  17785. * @return {number} The z component.
  17786. */
  17787. getZ( index ) {
  17788. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17789. if ( this.normalized ) z = denormalize( z, this.array );
  17790. return z;
  17791. }
  17792. /**
  17793. * Returns the w component of the vector at the given index.
  17794. *
  17795. * @param {number} index - The index into the buffer attribute.
  17796. * @return {number} The w component.
  17797. */
  17798. getW( index ) {
  17799. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17800. if ( this.normalized ) w = denormalize( w, this.array );
  17801. return w;
  17802. }
  17803. /**
  17804. * Sets the x and y component of the vector at the given index.
  17805. *
  17806. * @param {number} index - The index into the buffer attribute.
  17807. * @param {number} x - The value for the x component to set.
  17808. * @param {number} y - The value for the y component to set.
  17809. * @return {InterleavedBufferAttribute} A reference to this instance.
  17810. */
  17811. setXY( index, x, y ) {
  17812. index = index * this.data.stride + this.offset;
  17813. if ( this.normalized ) {
  17814. x = normalize( x, this.array );
  17815. y = normalize( y, this.array );
  17816. }
  17817. this.data.array[ index + 0 ] = x;
  17818. this.data.array[ index + 1 ] = y;
  17819. return this;
  17820. }
  17821. /**
  17822. * Sets the x, y and z component of the vector at the given index.
  17823. *
  17824. * @param {number} index - The index into the buffer attribute.
  17825. * @param {number} x - The value for the x component to set.
  17826. * @param {number} y - The value for the y component to set.
  17827. * @param {number} z - The value for the z component to set.
  17828. * @return {InterleavedBufferAttribute} A reference to this instance.
  17829. */
  17830. setXYZ( index, x, y, z ) {
  17831. index = index * this.data.stride + this.offset;
  17832. if ( this.normalized ) {
  17833. x = normalize( x, this.array );
  17834. y = normalize( y, this.array );
  17835. z = normalize( z, this.array );
  17836. }
  17837. this.data.array[ index + 0 ] = x;
  17838. this.data.array[ index + 1 ] = y;
  17839. this.data.array[ index + 2 ] = z;
  17840. return this;
  17841. }
  17842. /**
  17843. * Sets the x, y, z and w component of the vector at the given index.
  17844. *
  17845. * @param {number} index - The index into the buffer attribute.
  17846. * @param {number} x - The value for the x component to set.
  17847. * @param {number} y - The value for the y component to set.
  17848. * @param {number} z - The value for the z component to set.
  17849. * @param {number} w - The value for the w component to set.
  17850. * @return {InterleavedBufferAttribute} A reference to this instance.
  17851. */
  17852. setXYZW( index, x, y, z, w ) {
  17853. index = index * this.data.stride + this.offset;
  17854. if ( this.normalized ) {
  17855. x = normalize( x, this.array );
  17856. y = normalize( y, this.array );
  17857. z = normalize( z, this.array );
  17858. w = normalize( w, this.array );
  17859. }
  17860. this.data.array[ index + 0 ] = x;
  17861. this.data.array[ index + 1 ] = y;
  17862. this.data.array[ index + 2 ] = z;
  17863. this.data.array[ index + 3 ] = w;
  17864. return this;
  17865. }
  17866. /**
  17867. * Returns a new buffer attribute with copied values from this instance.
  17868. *
  17869. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17870. *
  17871. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17872. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17873. */
  17874. clone( data ) {
  17875. if ( data === undefined ) {
  17876. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17877. const array = [];
  17878. for ( let i = 0; i < this.count; i ++ ) {
  17879. const index = i * this.data.stride + this.offset;
  17880. for ( let j = 0; j < this.itemSize; j ++ ) {
  17881. array.push( this.data.array[ index + j ] );
  17882. }
  17883. }
  17884. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17885. } else {
  17886. if ( data.interleavedBuffers === undefined ) {
  17887. data.interleavedBuffers = {};
  17888. }
  17889. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17890. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17891. }
  17892. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17893. }
  17894. }
  17895. /**
  17896. * Serializes the buffer attribute into JSON.
  17897. *
  17898. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17899. *
  17900. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17901. * @return {Object} A JSON object representing the serialized buffer attribute.
  17902. */
  17903. toJSON( data ) {
  17904. if ( data === undefined ) {
  17905. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17906. const array = [];
  17907. for ( let i = 0; i < this.count; i ++ ) {
  17908. const index = i * this.data.stride + this.offset;
  17909. for ( let j = 0; j < this.itemSize; j ++ ) {
  17910. array.push( this.data.array[ index + j ] );
  17911. }
  17912. }
  17913. // de-interleave data and save it as an ordinary buffer attribute for now
  17914. return {
  17915. itemSize: this.itemSize,
  17916. type: this.array.constructor.name,
  17917. array: array,
  17918. normalized: this.normalized
  17919. };
  17920. } else {
  17921. // save as true interleaved attribute
  17922. if ( data.interleavedBuffers === undefined ) {
  17923. data.interleavedBuffers = {};
  17924. }
  17925. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17926. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17927. }
  17928. return {
  17929. isInterleavedBufferAttribute: true,
  17930. itemSize: this.itemSize,
  17931. data: this.data.uuid,
  17932. offset: this.offset,
  17933. normalized: this.normalized
  17934. };
  17935. }
  17936. }
  17937. }
  17938. /**
  17939. * A material for rendering instances of {@link Sprite}.
  17940. *
  17941. * ```js
  17942. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17943. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17944. *
  17945. * const sprite = new THREE.Sprite( material );
  17946. * sprite.scale.set(200, 200, 1)
  17947. * scene.add( sprite );
  17948. * ```
  17949. *
  17950. * @augments Material
  17951. */
  17952. class SpriteMaterial extends Material {
  17953. /**
  17954. * Constructs a new sprite material.
  17955. *
  17956. * @param {Object} [parameters] - An object with one or more properties
  17957. * defining the material's appearance. Any property of the material
  17958. * (including any property from inherited materials) can be passed
  17959. * in here. Color values can be passed any type of value accepted
  17960. * by {@link Color#set}.
  17961. */
  17962. constructor( parameters ) {
  17963. super();
  17964. /**
  17965. * This flag can be used for type testing.
  17966. *
  17967. * @type {boolean}
  17968. * @readonly
  17969. * @default true
  17970. */
  17971. this.isSpriteMaterial = true;
  17972. this.type = 'SpriteMaterial';
  17973. /**
  17974. * Color of the material.
  17975. *
  17976. * @type {Color}
  17977. * @default (1,1,1)
  17978. */
  17979. this.color = new Color( 0xffffff );
  17980. /**
  17981. * The color map. May optionally include an alpha channel, typically combined
  17982. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17983. * color is modulated by the diffuse `color`.
  17984. *
  17985. * @type {?Texture}
  17986. * @default null
  17987. */
  17988. this.map = null;
  17989. /**
  17990. * The alpha map is a grayscale texture that controls the opacity across the
  17991. * surface (black: fully transparent; white: fully opaque).
  17992. *
  17993. * Only the color of the texture is used, ignoring the alpha channel if one
  17994. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17995. * when sampling this texture due to the extra bit of precision provided for
  17996. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17997. * luminance/alpha textures will also still work as expected.
  17998. *
  17999. * @type {?Texture}
  18000. * @default null
  18001. */
  18002. this.alphaMap = null;
  18003. /**
  18004. * The rotation of the sprite in radians.
  18005. *
  18006. * @type {number}
  18007. * @default 0
  18008. */
  18009. this.rotation = 0;
  18010. /**
  18011. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18012. *
  18013. * @type {boolean}
  18014. * @default true
  18015. */
  18016. this.sizeAttenuation = true;
  18017. /**
  18018. * Overwritten since sprite materials are transparent
  18019. * by default.
  18020. *
  18021. * @type {boolean}
  18022. * @default true
  18023. */
  18024. this.transparent = true;
  18025. /**
  18026. * Whether the material is affected by fog or not.
  18027. *
  18028. * @type {boolean}
  18029. * @default true
  18030. */
  18031. this.fog = true;
  18032. this.setValues( parameters );
  18033. }
  18034. copy( source ) {
  18035. super.copy( source );
  18036. this.color.copy( source.color );
  18037. this.map = source.map;
  18038. this.alphaMap = source.alphaMap;
  18039. this.rotation = source.rotation;
  18040. this.sizeAttenuation = source.sizeAttenuation;
  18041. this.fog = source.fog;
  18042. return this;
  18043. }
  18044. }
  18045. let _geometry;
  18046. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18047. const _worldScale = /*@__PURE__*/ new Vector3();
  18048. const _mvPosition = /*@__PURE__*/ new Vector3();
  18049. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18050. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18051. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18052. const _vA = /*@__PURE__*/ new Vector3();
  18053. const _vB = /*@__PURE__*/ new Vector3();
  18054. const _vC = /*@__PURE__*/ new Vector3();
  18055. const _uvA = /*@__PURE__*/ new Vector2();
  18056. const _uvB = /*@__PURE__*/ new Vector2();
  18057. const _uvC = /*@__PURE__*/ new Vector2();
  18058. /**
  18059. * A sprite is a plane that always faces towards the camera, generally with a
  18060. * partially transparent texture applied.
  18061. *
  18062. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18063. * have no effect.
  18064. *
  18065. * ```js
  18066. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18067. * const material = new THREE.SpriteMaterial( { map: map } );
  18068. *
  18069. * const sprite = new THREE.Sprite( material );
  18070. * scene.add( sprite );
  18071. * ```
  18072. *
  18073. * @augments Object3D
  18074. */
  18075. class Sprite extends Object3D {
  18076. /**
  18077. * Constructs a new sprite.
  18078. *
  18079. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18080. */
  18081. constructor( material = new SpriteMaterial() ) {
  18082. super();
  18083. /**
  18084. * This flag can be used for type testing.
  18085. *
  18086. * @type {boolean}
  18087. * @readonly
  18088. * @default true
  18089. */
  18090. this.isSprite = true;
  18091. this.type = 'Sprite';
  18092. if ( _geometry === undefined ) {
  18093. _geometry = new BufferGeometry();
  18094. const float32Array = new Float32Array( [
  18095. -0.5, -0.5, 0, 0, 0,
  18096. 0.5, -0.5, 0, 1, 0,
  18097. 0.5, 0.5, 0, 1, 1,
  18098. -0.5, 0.5, 0, 0, 1
  18099. ] );
  18100. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18101. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18102. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18103. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18104. }
  18105. /**
  18106. * The sprite geometry.
  18107. *
  18108. * @type {BufferGeometry}
  18109. */
  18110. this.geometry = _geometry;
  18111. /**
  18112. * The sprite material.
  18113. *
  18114. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18115. */
  18116. this.material = material;
  18117. /**
  18118. * The sprite's anchor point, and the point around which the sprite rotates.
  18119. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18120. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18121. *
  18122. * @type {Vector2}
  18123. * @default (0.5,0.5)
  18124. */
  18125. this.center = new Vector2( 0.5, 0.5 );
  18126. /**
  18127. * The number of instances of this sprite.
  18128. * Can only be used with {@link WebGPURenderer}.
  18129. *
  18130. * @type {number}
  18131. * @default 1
  18132. */
  18133. this.count = 1;
  18134. }
  18135. /**
  18136. * Computes intersection points between a casted ray and this sprite.
  18137. *
  18138. * @param {Raycaster} raycaster - The raycaster.
  18139. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18140. */
  18141. raycast( raycaster, intersects ) {
  18142. if ( raycaster.camera === null ) {
  18143. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18144. }
  18145. _worldScale.setFromMatrixScale( this.matrixWorld );
  18146. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18147. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18148. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18149. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18150. _worldScale.multiplyScalar( - _mvPosition.z );
  18151. }
  18152. const rotation = this.material.rotation;
  18153. let sin, cos;
  18154. if ( rotation !== 0 ) {
  18155. cos = Math.cos( rotation );
  18156. sin = Math.sin( rotation );
  18157. }
  18158. const center = this.center;
  18159. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18160. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18161. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18162. _uvA.set( 0, 0 );
  18163. _uvB.set( 1, 0 );
  18164. _uvC.set( 1, 1 );
  18165. // check first triangle
  18166. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18167. if ( intersect === null ) {
  18168. // check second triangle
  18169. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18170. _uvB.set( 0, 1 );
  18171. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18172. if ( intersect === null ) {
  18173. return;
  18174. }
  18175. }
  18176. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18177. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18178. intersects.push( {
  18179. distance: distance,
  18180. point: _intersectPoint.clone(),
  18181. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18182. face: null,
  18183. object: this
  18184. } );
  18185. }
  18186. copy( source, recursive ) {
  18187. super.copy( source, recursive );
  18188. if ( source.center !== undefined ) this.center.copy( source.center );
  18189. this.material = source.material;
  18190. return this;
  18191. }
  18192. }
  18193. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18194. // compute position in camera space
  18195. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18196. // to check if rotation is not zero
  18197. if ( sin !== undefined ) {
  18198. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18199. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18200. } else {
  18201. _rotatedPosition.copy( _alignedPosition );
  18202. }
  18203. vertexPosition.copy( mvPosition );
  18204. vertexPosition.x += _rotatedPosition.x;
  18205. vertexPosition.y += _rotatedPosition.y;
  18206. // transform to world space
  18207. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18208. }
  18209. const _v1$2 = /*@__PURE__*/ new Vector3();
  18210. const _v2$1 = /*@__PURE__*/ new Vector3();
  18211. /**
  18212. * A component for providing a basic Level of Detail (LOD) mechanism.
  18213. *
  18214. * Every LOD level is associated with an object, and rendering can be switched
  18215. * between them at the distances specified. Typically you would create, say,
  18216. * three meshes, one for far away (low detail), one for mid range (medium
  18217. * detail) and one for close up (high detail).
  18218. *
  18219. * ```js
  18220. * const lod = new THREE.LOD();
  18221. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18222. *
  18223. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18224. * for( let i = 0; i < 3; i++ ) {
  18225. *
  18226. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18227. * const mesh = new THREE.Mesh( geometry, material );
  18228. * lod.addLevel( mesh, i * 75 );
  18229. *
  18230. * }
  18231. *
  18232. * scene.add( lod );
  18233. * ```
  18234. *
  18235. * @augments Object3D
  18236. */
  18237. class LOD extends Object3D {
  18238. /**
  18239. * Constructs a new LOD.
  18240. */
  18241. constructor() {
  18242. super();
  18243. /**
  18244. * This flag can be used for type testing.
  18245. *
  18246. * @type {boolean}
  18247. * @readonly
  18248. * @default true
  18249. */
  18250. this.isLOD = true;
  18251. /**
  18252. * The current LOD index.
  18253. *
  18254. * @private
  18255. * @type {number}
  18256. * @default 0
  18257. */
  18258. this._currentLevel = 0;
  18259. this.type = 'LOD';
  18260. Object.defineProperties( this, {
  18261. /**
  18262. * This array holds the LOD levels.
  18263. *
  18264. * @name LOD#levels
  18265. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18266. */
  18267. levels: {
  18268. enumerable: true,
  18269. value: []
  18270. }
  18271. } );
  18272. /**
  18273. * Whether the LOD object is updated automatically by the renderer per frame
  18274. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18275. * render loop by yourself.
  18276. *
  18277. * @type {boolean}
  18278. * @default true
  18279. */
  18280. this.autoUpdate = true;
  18281. }
  18282. copy( source ) {
  18283. super.copy( source, false );
  18284. const levels = source.levels;
  18285. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18286. const level = levels[ i ];
  18287. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18288. }
  18289. this.autoUpdate = source.autoUpdate;
  18290. return this;
  18291. }
  18292. /**
  18293. * Adds a mesh that will display at a certain distance and greater. Typically
  18294. * the further away the distance, the lower the detail on the mesh.
  18295. *
  18296. * @param {Object3D} object - The 3D object to display at this level.
  18297. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18298. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18299. * @return {LOD} A reference to this instance.
  18300. */
  18301. addLevel( object, distance = 0, hysteresis = 0 ) {
  18302. distance = Math.abs( distance );
  18303. const levels = this.levels;
  18304. let l;
  18305. for ( l = 0; l < levels.length; l ++ ) {
  18306. if ( distance < levels[ l ].distance ) {
  18307. break;
  18308. }
  18309. }
  18310. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18311. this.add( object );
  18312. return this;
  18313. }
  18314. /**
  18315. * Removes an existing level, based on the distance from the camera.
  18316. * Returns `true` when the level has been removed. Otherwise `false`.
  18317. *
  18318. * @param {number} distance - Distance of the level to remove.
  18319. * @return {boolean} Whether the level has been removed or not.
  18320. */
  18321. removeLevel( distance ) {
  18322. const levels = this.levels;
  18323. for ( let i = 0; i < levels.length; i ++ ) {
  18324. if ( levels[ i ].distance === distance ) {
  18325. const removedElements = levels.splice( i, 1 );
  18326. this.remove( removedElements[ 0 ].object );
  18327. return true;
  18328. }
  18329. }
  18330. return false;
  18331. }
  18332. /**
  18333. * Returns the currently active LOD level index.
  18334. *
  18335. * @return {number} The current active LOD level index.
  18336. */
  18337. getCurrentLevel() {
  18338. return this._currentLevel;
  18339. }
  18340. /**
  18341. * Returns a reference to the first 3D object that is greater than
  18342. * the given distance.
  18343. *
  18344. * @param {number} distance - The LOD distance.
  18345. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18346. */
  18347. getObjectForDistance( distance ) {
  18348. const levels = this.levels;
  18349. if ( levels.length > 0 ) {
  18350. let i, l;
  18351. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18352. let levelDistance = levels[ i ].distance;
  18353. if ( levels[ i ].object.visible ) {
  18354. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18355. }
  18356. if ( distance < levelDistance ) {
  18357. break;
  18358. }
  18359. }
  18360. return levels[ i - 1 ].object;
  18361. }
  18362. return null;
  18363. }
  18364. /**
  18365. * Computes intersection points between a casted ray and this LOD.
  18366. *
  18367. * @param {Raycaster} raycaster - The raycaster.
  18368. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18369. */
  18370. raycast( raycaster, intersects ) {
  18371. const levels = this.levels;
  18372. if ( levels.length > 0 ) {
  18373. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18374. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18375. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18376. }
  18377. }
  18378. /**
  18379. * Updates the LOD by computing which LOD level should be visible according
  18380. * to the current distance of the given camera.
  18381. *
  18382. * @param {Camera} camera - The camera the scene is rendered with.
  18383. */
  18384. update( camera ) {
  18385. const levels = this.levels;
  18386. if ( levels.length > 1 ) {
  18387. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18388. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18389. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18390. levels[ 0 ].object.visible = true;
  18391. let i, l;
  18392. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18393. let levelDistance = levels[ i ].distance;
  18394. if ( levels[ i ].object.visible ) {
  18395. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18396. }
  18397. if ( distance >= levelDistance ) {
  18398. levels[ i - 1 ].object.visible = false;
  18399. levels[ i ].object.visible = true;
  18400. } else {
  18401. break;
  18402. }
  18403. }
  18404. this._currentLevel = i - 1;
  18405. for ( ; i < l; i ++ ) {
  18406. levels[ i ].object.visible = false;
  18407. }
  18408. }
  18409. }
  18410. toJSON( meta ) {
  18411. const data = super.toJSON( meta );
  18412. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18413. data.object.levels = [];
  18414. const levels = this.levels;
  18415. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18416. const level = levels[ i ];
  18417. data.object.levels.push( {
  18418. object: level.object.uuid,
  18419. distance: level.distance,
  18420. hysteresis: level.hysteresis
  18421. } );
  18422. }
  18423. return data;
  18424. }
  18425. }
  18426. const _basePosition = /*@__PURE__*/ new Vector3();
  18427. const _skinIndex = /*@__PURE__*/ new Vector4();
  18428. const _skinWeight = /*@__PURE__*/ new Vector4();
  18429. const _vector3 = /*@__PURE__*/ new Vector3();
  18430. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18431. const _vertex = /*@__PURE__*/ new Vector3();
  18432. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18433. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18434. const _ray$2 = /*@__PURE__*/ new Ray();
  18435. /**
  18436. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18437. * vertices of the geometry with skinning/skeleton animation.
  18438. *
  18439. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18440. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18441. * vertex to a certain extend.
  18442. *
  18443. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18444. * or {@link FBXLoader } import respective models.
  18445. *
  18446. * @augments Mesh
  18447. * @demo scenes/bones-browser.html
  18448. */
  18449. class SkinnedMesh extends Mesh {
  18450. /**
  18451. * Constructs a new skinned mesh.
  18452. *
  18453. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18454. * @param {Material|Array<Material>} [material] - The mesh material.
  18455. */
  18456. constructor( geometry, material ) {
  18457. super( geometry, material );
  18458. /**
  18459. * This flag can be used for type testing.
  18460. *
  18461. * @type {boolean}
  18462. * @readonly
  18463. * @default true
  18464. */
  18465. this.isSkinnedMesh = true;
  18466. this.type = 'SkinnedMesh';
  18467. /**
  18468. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18469. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18470. * across multiple skinned meshes.
  18471. *
  18472. * @type {(AttachedBindMode|DetachedBindMode)}
  18473. * @default AttachedBindMode
  18474. */
  18475. this.bindMode = AttachedBindMode;
  18476. /**
  18477. * The base matrix that is used for the bound bone transforms.
  18478. *
  18479. * @type {Matrix4}
  18480. */
  18481. this.bindMatrix = new Matrix4();
  18482. /**
  18483. * The base matrix that is used for resetting the bound bone transforms.
  18484. *
  18485. * @type {Matrix4}
  18486. */
  18487. this.bindMatrixInverse = new Matrix4();
  18488. /**
  18489. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18490. *
  18491. * @type {?Box3}
  18492. * @default null
  18493. */
  18494. this.boundingBox = null;
  18495. /**
  18496. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18497. *
  18498. * @type {?Sphere}
  18499. * @default null
  18500. */
  18501. this.boundingSphere = null;
  18502. }
  18503. /**
  18504. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18505. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18506. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18507. * the current animation state.
  18508. */
  18509. computeBoundingBox() {
  18510. const geometry = this.geometry;
  18511. if ( this.boundingBox === null ) {
  18512. this.boundingBox = new Box3();
  18513. }
  18514. this.boundingBox.makeEmpty();
  18515. const positionAttribute = geometry.getAttribute( 'position' );
  18516. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18517. this.getVertexPosition( i, _vertex );
  18518. this.boundingBox.expandByPoint( _vertex );
  18519. }
  18520. }
  18521. /**
  18522. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18523. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18524. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18525. * per frame in order to reflect the current animation state.
  18526. */
  18527. computeBoundingSphere() {
  18528. const geometry = this.geometry;
  18529. if ( this.boundingSphere === null ) {
  18530. this.boundingSphere = new Sphere();
  18531. }
  18532. this.boundingSphere.makeEmpty();
  18533. const positionAttribute = geometry.getAttribute( 'position' );
  18534. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18535. this.getVertexPosition( i, _vertex );
  18536. this.boundingSphere.expandByPoint( _vertex );
  18537. }
  18538. }
  18539. copy( source, recursive ) {
  18540. super.copy( source, recursive );
  18541. this.bindMode = source.bindMode;
  18542. this.bindMatrix.copy( source.bindMatrix );
  18543. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18544. this.skeleton = source.skeleton;
  18545. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18546. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18547. return this;
  18548. }
  18549. raycast( raycaster, intersects ) {
  18550. const material = this.material;
  18551. const matrixWorld = this.matrixWorld;
  18552. if ( material === undefined ) return;
  18553. // test with bounding sphere in world space
  18554. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18555. _sphere$5.copy( this.boundingSphere );
  18556. _sphere$5.applyMatrix4( matrixWorld );
  18557. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18558. // convert ray to local space of skinned mesh
  18559. _inverseMatrix$2.copy( matrixWorld ).invert();
  18560. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18561. // test with bounding box in local space
  18562. if ( this.boundingBox !== null ) {
  18563. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18564. }
  18565. // test for intersections with geometry
  18566. this._computeIntersections( raycaster, intersects, _ray$2 );
  18567. }
  18568. getVertexPosition( index, target ) {
  18569. super.getVertexPosition( index, target );
  18570. this.applyBoneTransform( index, target );
  18571. return target;
  18572. }
  18573. /**
  18574. * Binds the given skeleton to the skinned mesh.
  18575. *
  18576. * @param {Skeleton} skeleton - The skeleton to bind.
  18577. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18578. * the skinned mesh's world matrix will be used instead.
  18579. */
  18580. bind( skeleton, bindMatrix ) {
  18581. this.skeleton = skeleton;
  18582. if ( bindMatrix === undefined ) {
  18583. this.updateMatrixWorld( true );
  18584. this.skeleton.calculateInverses();
  18585. bindMatrix = this.matrixWorld;
  18586. }
  18587. this.bindMatrix.copy( bindMatrix );
  18588. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18589. }
  18590. /**
  18591. * This method sets the skinned mesh in the rest pose).
  18592. */
  18593. pose() {
  18594. this.skeleton.pose();
  18595. }
  18596. /**
  18597. * Normalizes the skin weights which are defined as a buffer attribute
  18598. * in the skinned mesh's geometry.
  18599. */
  18600. normalizeSkinWeights() {
  18601. const vector = new Vector4();
  18602. const skinWeight = this.geometry.attributes.skinWeight;
  18603. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18604. vector.fromBufferAttribute( skinWeight, i );
  18605. const scale = 1.0 / vector.manhattanLength();
  18606. if ( scale !== Infinity ) {
  18607. vector.multiplyScalar( scale );
  18608. } else {
  18609. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18610. }
  18611. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18612. }
  18613. }
  18614. updateMatrixWorld( force ) {
  18615. super.updateMatrixWorld( force );
  18616. if ( this.bindMode === AttachedBindMode ) {
  18617. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18618. } else if ( this.bindMode === DetachedBindMode ) {
  18619. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18620. } else {
  18621. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18622. }
  18623. }
  18624. /**
  18625. * Applies the bone transform associated with the given index to the given
  18626. * vertex position. Returns the updated vector.
  18627. *
  18628. * @param {number} index - The vertex index.
  18629. * @param {Vector3} target - The target object that is used to store the method's result.
  18630. * the skinned mesh's world matrix will be used instead.
  18631. * @return {Vector3} The updated vertex position.
  18632. */
  18633. applyBoneTransform( index, target ) {
  18634. const skeleton = this.skeleton;
  18635. const geometry = this.geometry;
  18636. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18637. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18638. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18639. target.set( 0, 0, 0 );
  18640. for ( let i = 0; i < 4; i ++ ) {
  18641. const weight = _skinWeight.getComponent( i );
  18642. if ( weight !== 0 ) {
  18643. const boneIndex = _skinIndex.getComponent( i );
  18644. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18645. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18646. }
  18647. }
  18648. return target.applyMatrix4( this.bindMatrixInverse );
  18649. }
  18650. }
  18651. /**
  18652. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18653. * the {@link SkinnedMesh}.
  18654. *
  18655. * ```js
  18656. * const root = new THREE.Bone();
  18657. * const child = new THREE.Bone();
  18658. *
  18659. * root.add( child );
  18660. * child.position.y = 5;
  18661. * ```
  18662. *
  18663. * @augments Object3D
  18664. */
  18665. class Bone extends Object3D {
  18666. /**
  18667. * Constructs a new bone.
  18668. */
  18669. constructor() {
  18670. super();
  18671. /**
  18672. * This flag can be used for type testing.
  18673. *
  18674. * @type {boolean}
  18675. * @readonly
  18676. * @default true
  18677. */
  18678. this.isBone = true;
  18679. this.type = 'Bone';
  18680. }
  18681. }
  18682. /**
  18683. * Creates a texture directly from raw buffer data.
  18684. *
  18685. * The interpretation of the data depends on type and format: If the type is
  18686. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18687. * texel data. If the format is `RGBAFormat`, data needs four values for
  18688. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18689. *
  18690. * @augments Texture
  18691. */
  18692. class DataTexture extends Texture {
  18693. /**
  18694. * Constructs a new data texture.
  18695. *
  18696. * @param {?TypedArray} [data=null] - The buffer data.
  18697. * @param {number} [width=1] - The width of the texture.
  18698. * @param {number} [height=1] - The height of the texture.
  18699. * @param {number} [format=RGBAFormat] - The texture format.
  18700. * @param {number} [type=UnsignedByteType] - The texture type.
  18701. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18702. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18703. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18704. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18705. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18706. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18707. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18708. */
  18709. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18710. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18711. /**
  18712. * This flag can be used for type testing.
  18713. *
  18714. * @type {boolean}
  18715. * @readonly
  18716. * @default true
  18717. */
  18718. this.isDataTexture = true;
  18719. /**
  18720. * The image definition of a data texture.
  18721. *
  18722. * @type {{data:TypedArray,width:number,height:number}}
  18723. */
  18724. this.image = { data: data, width: width, height: height };
  18725. /**
  18726. * Whether to generate mipmaps (if possible) for a texture.
  18727. *
  18728. * Overwritten and set to `false` by default.
  18729. *
  18730. * @type {boolean}
  18731. * @default false
  18732. */
  18733. this.generateMipmaps = false;
  18734. /**
  18735. * If set to `true`, the texture is flipped along the vertical axis when
  18736. * uploaded to the GPU.
  18737. *
  18738. * Overwritten and set to `false` by default.
  18739. *
  18740. * @type {boolean}
  18741. * @default false
  18742. */
  18743. this.flipY = false;
  18744. /**
  18745. * Specifies the alignment requirements for the start of each pixel row in memory.
  18746. *
  18747. * Overwritten and set to `1` by default.
  18748. *
  18749. * @type {boolean}
  18750. * @default 1
  18751. */
  18752. this.unpackAlignment = 1;
  18753. }
  18754. }
  18755. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18756. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18757. /**
  18758. * Class for representing the armatures in `three.js`. The skeleton
  18759. * is defined by a hierarchy of bones.
  18760. *
  18761. * ```js
  18762. * const bones = [];
  18763. *
  18764. * const shoulder = new THREE.Bone();
  18765. * const elbow = new THREE.Bone();
  18766. * const hand = new THREE.Bone();
  18767. *
  18768. * shoulder.add( elbow );
  18769. * elbow.add( hand );
  18770. *
  18771. * bones.push( shoulder , elbow, hand);
  18772. *
  18773. * shoulder.position.y = -5;
  18774. * elbow.position.y = 0;
  18775. * hand.position.y = 5;
  18776. *
  18777. * const armSkeleton = new THREE.Skeleton( bones );
  18778. * ```
  18779. */
  18780. class Skeleton {
  18781. /**
  18782. * Constructs a new skeleton.
  18783. *
  18784. * @param {Array<Bone>} [bones] - An array of bones.
  18785. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18786. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18787. */
  18788. constructor( bones = [], boneInverses = [] ) {
  18789. this.uuid = generateUUID();
  18790. /**
  18791. * An array of bones defining the skeleton.
  18792. *
  18793. * @type {Array<Bone>}
  18794. */
  18795. this.bones = bones.slice( 0 );
  18796. /**
  18797. * An array of bone inverse matrices.
  18798. *
  18799. * @type {Array<Matrix4>}
  18800. */
  18801. this.boneInverses = boneInverses;
  18802. /**
  18803. * An array buffer holding the bone data.
  18804. * Input data for {@link Skeleton#boneTexture}.
  18805. *
  18806. * @type {?Float32Array}
  18807. * @default null
  18808. */
  18809. this.boneMatrices = null;
  18810. /**
  18811. * An array buffer holding the bone data of the previous frame.
  18812. * Required for computing velocity. Maintained in {@link SkinningNode}.
  18813. *
  18814. * @type {?Float32Array}
  18815. * @default null
  18816. */
  18817. this.previousBoneMatrices = null;
  18818. /**
  18819. * A texture holding the bone data for use
  18820. * in the vertex shader.
  18821. *
  18822. * @type {?DataTexture}
  18823. * @default null
  18824. */
  18825. this.boneTexture = null;
  18826. this.init();
  18827. }
  18828. /**
  18829. * Initializes the skeleton. This method gets automatically called by the constructor
  18830. * but depending on how the skeleton is created it might be necessary to call this method
  18831. * manually.
  18832. */
  18833. init() {
  18834. const bones = this.bones;
  18835. const boneInverses = this.boneInverses;
  18836. this.boneMatrices = new Float32Array( bones.length * 16 );
  18837. // calculate inverse bone matrices if necessary
  18838. if ( boneInverses.length === 0 ) {
  18839. this.calculateInverses();
  18840. } else {
  18841. // handle special case
  18842. if ( bones.length !== boneInverses.length ) {
  18843. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18844. this.boneInverses = [];
  18845. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18846. this.boneInverses.push( new Matrix4() );
  18847. }
  18848. }
  18849. }
  18850. }
  18851. /**
  18852. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18853. * and fills it with new matrices.
  18854. */
  18855. calculateInverses() {
  18856. this.boneInverses.length = 0;
  18857. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18858. const inverse = new Matrix4();
  18859. if ( this.bones[ i ] ) {
  18860. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18861. }
  18862. this.boneInverses.push( inverse );
  18863. }
  18864. }
  18865. /**
  18866. * Resets the skeleton to the base pose.
  18867. */
  18868. pose() {
  18869. // recover the bind-time world matrices
  18870. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18871. const bone = this.bones[ i ];
  18872. if ( bone ) {
  18873. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18874. }
  18875. }
  18876. // compute the local matrices, positions, rotations and scales
  18877. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18878. const bone = this.bones[ i ];
  18879. if ( bone ) {
  18880. if ( bone.parent && bone.parent.isBone ) {
  18881. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18882. bone.matrix.multiply( bone.matrixWorld );
  18883. } else {
  18884. bone.matrix.copy( bone.matrixWorld );
  18885. }
  18886. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18887. }
  18888. }
  18889. }
  18890. /**
  18891. * Resets the skeleton to the base pose.
  18892. */
  18893. update() {
  18894. const bones = this.bones;
  18895. const boneInverses = this.boneInverses;
  18896. const boneMatrices = this.boneMatrices;
  18897. const boneTexture = this.boneTexture;
  18898. // flatten bone matrices to array
  18899. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18900. // compute the offset between the current and the original transform
  18901. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18902. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18903. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18904. }
  18905. if ( boneTexture !== null ) {
  18906. boneTexture.needsUpdate = true;
  18907. }
  18908. }
  18909. /**
  18910. * Returns a new skeleton with copied values from this instance.
  18911. *
  18912. * @return {Skeleton} A clone of this instance.
  18913. */
  18914. clone() {
  18915. return new Skeleton( this.bones, this.boneInverses );
  18916. }
  18917. /**
  18918. * Computes a data texture for passing bone data to the vertex shader.
  18919. *
  18920. * @return {Skeleton} A reference of this instance.
  18921. */
  18922. computeBoneTexture() {
  18923. // layout (1 matrix = 4 pixels)
  18924. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18925. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18926. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18927. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18928. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18929. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18930. size = Math.ceil( size / 4 ) * 4;
  18931. size = Math.max( size, 4 );
  18932. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18933. boneMatrices.set( this.boneMatrices ); // copy current values
  18934. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18935. boneTexture.needsUpdate = true;
  18936. this.boneMatrices = boneMatrices;
  18937. this.boneTexture = boneTexture;
  18938. return this;
  18939. }
  18940. /**
  18941. * Searches through the skeleton's bone array and returns the first with a
  18942. * matching name.
  18943. *
  18944. * @param {string} name - The name of the bone.
  18945. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18946. */
  18947. getBoneByName( name ) {
  18948. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18949. const bone = this.bones[ i ];
  18950. if ( bone.name === name ) {
  18951. return bone;
  18952. }
  18953. }
  18954. return undefined;
  18955. }
  18956. /**
  18957. * Frees the GPU-related resources allocated by this instance. Call this
  18958. * method whenever this instance is no longer used in your app.
  18959. */
  18960. dispose( ) {
  18961. if ( this.boneTexture !== null ) {
  18962. this.boneTexture.dispose();
  18963. this.boneTexture = null;
  18964. }
  18965. }
  18966. /**
  18967. * Setups the skeleton by the given JSON and bones.
  18968. *
  18969. * @param {Object} json - The skeleton as serialized JSON.
  18970. * @param {Object<string, Bone>} bones - An array of bones.
  18971. * @return {Skeleton} A reference of this instance.
  18972. */
  18973. fromJSON( json, bones ) {
  18974. this.uuid = json.uuid;
  18975. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18976. const uuid = json.bones[ i ];
  18977. let bone = bones[ uuid ];
  18978. if ( bone === undefined ) {
  18979. warn( 'Skeleton: No bone found with UUID:', uuid );
  18980. bone = new Bone();
  18981. }
  18982. this.bones.push( bone );
  18983. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18984. }
  18985. this.init();
  18986. return this;
  18987. }
  18988. /**
  18989. * Serializes the skeleton into JSON.
  18990. *
  18991. * @return {Object} A JSON object representing the serialized skeleton.
  18992. * @see {@link ObjectLoader#parse}
  18993. */
  18994. toJSON() {
  18995. const data = {
  18996. metadata: {
  18997. version: 4.7,
  18998. type: 'Skeleton',
  18999. generator: 'Skeleton.toJSON'
  19000. },
  19001. bones: [],
  19002. boneInverses: []
  19003. };
  19004. data.uuid = this.uuid;
  19005. const bones = this.bones;
  19006. const boneInverses = this.boneInverses;
  19007. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19008. const bone = bones[ i ];
  19009. data.bones.push( bone.uuid );
  19010. const boneInverse = boneInverses[ i ];
  19011. data.boneInverses.push( boneInverse.toArray() );
  19012. }
  19013. return data;
  19014. }
  19015. }
  19016. /**
  19017. * An instanced version of a buffer attribute.
  19018. *
  19019. * @augments BufferAttribute
  19020. */
  19021. class InstancedBufferAttribute extends BufferAttribute {
  19022. /**
  19023. * Constructs a new instanced buffer attribute.
  19024. *
  19025. * @param {TypedArray} array - The array holding the attribute data.
  19026. * @param {number} itemSize - The item size.
  19027. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19028. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19029. */
  19030. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19031. super( array, itemSize, normalized );
  19032. /**
  19033. * This flag can be used for type testing.
  19034. *
  19035. * @type {boolean}
  19036. * @readonly
  19037. * @default true
  19038. */
  19039. this.isInstancedBufferAttribute = true;
  19040. /**
  19041. * Defines how often a value of this buffer attribute should be repeated. A
  19042. * value of one means that each value of the instanced attribute is used for
  19043. * a single instance. A value of two means that each value is used for two
  19044. * consecutive instances (and so on).
  19045. *
  19046. * @type {number}
  19047. * @default 1
  19048. */
  19049. this.meshPerAttribute = meshPerAttribute;
  19050. }
  19051. copy( source ) {
  19052. super.copy( source );
  19053. this.meshPerAttribute = source.meshPerAttribute;
  19054. return this;
  19055. }
  19056. toJSON() {
  19057. const data = super.toJSON();
  19058. data.meshPerAttribute = this.meshPerAttribute;
  19059. data.isInstancedBufferAttribute = true;
  19060. return data;
  19061. }
  19062. }
  19063. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19064. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19065. const _instanceIntersects = [];
  19066. const _box3 = /*@__PURE__*/ new Box3();
  19067. const _identity = /*@__PURE__*/ new Matrix4();
  19068. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19069. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19070. /**
  19071. * A special version of a mesh with instanced rendering support. Use
  19072. * this class if you have to render a large number of objects with the same
  19073. * geometry and material(s) but with different world transformations. The usage
  19074. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19075. * improve the overall rendering performance in your application.
  19076. *
  19077. * @augments Mesh
  19078. */
  19079. class InstancedMesh extends Mesh {
  19080. /**
  19081. * Constructs a new instanced mesh.
  19082. *
  19083. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19084. * @param {Material|Array<Material>} [material] - The mesh material.
  19085. * @param {number} count - The number of instances.
  19086. */
  19087. constructor( geometry, material, count ) {
  19088. super( geometry, material );
  19089. /**
  19090. * This flag can be used for type testing.
  19091. *
  19092. * @type {boolean}
  19093. * @readonly
  19094. * @default true
  19095. */
  19096. this.isInstancedMesh = true;
  19097. /**
  19098. * Represents the local transformation of all instances. You have to set its
  19099. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19100. * via {@link InstancedMesh#setMatrixAt}.
  19101. *
  19102. * @type {InstancedBufferAttribute}
  19103. */
  19104. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19105. /**
  19106. * Represents the local transformation of all instances of the previous frame.
  19107. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19108. *
  19109. * @type {?InstancedBufferAttribute}
  19110. * @default null
  19111. */
  19112. this.previousInstanceMatrix = null;
  19113. /**
  19114. * Represents the color of all instances. You have to set its
  19115. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19116. * via {@link InstancedMesh#setColorAt}.
  19117. *
  19118. * @type {?InstancedBufferAttribute}
  19119. * @default null
  19120. */
  19121. this.instanceColor = null;
  19122. /**
  19123. * Represents the morph target weights of all instances. You have to set its
  19124. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19125. * via {@link InstancedMesh#setMorphAt}.
  19126. *
  19127. * @type {?DataTexture}
  19128. * @default null
  19129. */
  19130. this.morphTexture = null;
  19131. /**
  19132. * The number of instances.
  19133. *
  19134. * @type {number}
  19135. */
  19136. this.count = count;
  19137. /**
  19138. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19139. *
  19140. * @type {?Box3}
  19141. * @default null
  19142. */
  19143. this.boundingBox = null;
  19144. /**
  19145. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19146. *
  19147. * @type {?Sphere}
  19148. * @default null
  19149. */
  19150. this.boundingSphere = null;
  19151. for ( let i = 0; i < count; i ++ ) {
  19152. this.setMatrixAt( i, _identity );
  19153. }
  19154. }
  19155. /**
  19156. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19157. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19158. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19159. */
  19160. computeBoundingBox() {
  19161. const geometry = this.geometry;
  19162. const count = this.count;
  19163. if ( this.boundingBox === null ) {
  19164. this.boundingBox = new Box3();
  19165. }
  19166. if ( geometry.boundingBox === null ) {
  19167. geometry.computeBoundingBox();
  19168. }
  19169. this.boundingBox.makeEmpty();
  19170. for ( let i = 0; i < count; i ++ ) {
  19171. this.getMatrixAt( i, _instanceLocalMatrix );
  19172. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19173. this.boundingBox.union( _box3 );
  19174. }
  19175. }
  19176. /**
  19177. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19178. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19179. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19180. */
  19181. computeBoundingSphere() {
  19182. const geometry = this.geometry;
  19183. const count = this.count;
  19184. if ( this.boundingSphere === null ) {
  19185. this.boundingSphere = new Sphere();
  19186. }
  19187. if ( geometry.boundingSphere === null ) {
  19188. geometry.computeBoundingSphere();
  19189. }
  19190. this.boundingSphere.makeEmpty();
  19191. for ( let i = 0; i < count; i ++ ) {
  19192. this.getMatrixAt( i, _instanceLocalMatrix );
  19193. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19194. this.boundingSphere.union( _sphere$4 );
  19195. }
  19196. }
  19197. copy( source, recursive ) {
  19198. super.copy( source, recursive );
  19199. this.instanceMatrix.copy( source.instanceMatrix );
  19200. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19201. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19202. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19203. this.count = source.count;
  19204. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19205. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19206. return this;
  19207. }
  19208. /**
  19209. * Gets the color of the defined instance.
  19210. *
  19211. * @param {number} index - The instance index.
  19212. * @param {Color} color - The target object that is used to store the method's result.
  19213. */
  19214. getColorAt( index, color ) {
  19215. color.fromArray( this.instanceColor.array, index * 3 );
  19216. }
  19217. /**
  19218. * Gets the local transformation matrix of the defined instance.
  19219. *
  19220. * @param {number} index - The instance index.
  19221. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19222. */
  19223. getMatrixAt( index, matrix ) {
  19224. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19225. }
  19226. /**
  19227. * Gets the morph target weights of the defined instance.
  19228. *
  19229. * @param {number} index - The instance index.
  19230. * @param {Mesh} object - The target object that is used to store the method's result.
  19231. */
  19232. getMorphAt( index, object ) {
  19233. const objectInfluences = object.morphTargetInfluences;
  19234. const array = this.morphTexture.source.data.data;
  19235. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19236. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19237. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19238. objectInfluences[ i ] = array[ dataIndex + i ];
  19239. }
  19240. }
  19241. raycast( raycaster, intersects ) {
  19242. const matrixWorld = this.matrixWorld;
  19243. const raycastTimes = this.count;
  19244. _mesh$1.geometry = this.geometry;
  19245. _mesh$1.material = this.material;
  19246. if ( _mesh$1.material === undefined ) return;
  19247. // test with bounding sphere first
  19248. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19249. _sphere$4.copy( this.boundingSphere );
  19250. _sphere$4.applyMatrix4( matrixWorld );
  19251. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19252. // now test each instance
  19253. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19254. // calculate the world matrix for each instance
  19255. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19256. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19257. // the mesh represents this single instance
  19258. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19259. _mesh$1.raycast( raycaster, _instanceIntersects );
  19260. // process the result of raycast
  19261. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19262. const intersect = _instanceIntersects[ i ];
  19263. intersect.instanceId = instanceId;
  19264. intersect.object = this;
  19265. intersects.push( intersect );
  19266. }
  19267. _instanceIntersects.length = 0;
  19268. }
  19269. }
  19270. /**
  19271. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19272. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19273. *
  19274. * @param {number} index - The instance index.
  19275. * @param {Color} color - The instance color.
  19276. */
  19277. setColorAt( index, color ) {
  19278. if ( this.instanceColor === null ) {
  19279. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19280. }
  19281. color.toArray( this.instanceColor.array, index * 3 );
  19282. }
  19283. /**
  19284. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19285. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19286. *
  19287. * @param {number} index - The instance index.
  19288. * @param {Matrix4} matrix - The local transformation.
  19289. */
  19290. setMatrixAt( index, matrix ) {
  19291. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19292. }
  19293. /**
  19294. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19295. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19296. *
  19297. * @param {number} index - The instance index.
  19298. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19299. * of a single instance.
  19300. */
  19301. setMorphAt( index, object ) {
  19302. const objectInfluences = object.morphTargetInfluences;
  19303. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19304. if ( this.morphTexture === null ) {
  19305. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19306. }
  19307. const array = this.morphTexture.source.data.data;
  19308. let morphInfluencesSum = 0;
  19309. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19310. morphInfluencesSum += objectInfluences[ i ];
  19311. }
  19312. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19313. const dataIndex = len * index;
  19314. array[ dataIndex ] = morphBaseInfluence;
  19315. array.set( objectInfluences, dataIndex + 1 );
  19316. }
  19317. updateMorphTargets() {
  19318. }
  19319. /**
  19320. * Frees the GPU-related resources allocated by this instance. Call this
  19321. * method whenever this instance is no longer used in your app.
  19322. */
  19323. dispose() {
  19324. this.dispatchEvent( { type: 'dispose' } );
  19325. if ( this.morphTexture !== null ) {
  19326. this.morphTexture.dispose();
  19327. this.morphTexture = null;
  19328. }
  19329. }
  19330. }
  19331. const _vector1 = /*@__PURE__*/ new Vector3();
  19332. const _vector2 = /*@__PURE__*/ new Vector3();
  19333. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19334. /**
  19335. * A two dimensional surface that extends infinitely in 3D space, represented
  19336. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19337. * by a unit length normal vector and a constant.
  19338. */
  19339. class Plane {
  19340. /**
  19341. * Constructs a new plane.
  19342. *
  19343. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19344. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19345. */
  19346. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19347. /**
  19348. * This flag can be used for type testing.
  19349. *
  19350. * @type {boolean}
  19351. * @readonly
  19352. * @default true
  19353. */
  19354. this.isPlane = true;
  19355. /**
  19356. * A unit length vector defining the normal of the plane.
  19357. *
  19358. * @type {Vector3}
  19359. */
  19360. this.normal = normal;
  19361. /**
  19362. * The signed distance from the origin to the plane.
  19363. *
  19364. * @type {number}
  19365. * @default 0
  19366. */
  19367. this.constant = constant;
  19368. }
  19369. /**
  19370. * Sets the plane components by copying the given values.
  19371. *
  19372. * @param {Vector3} normal - The normal.
  19373. * @param {number} constant - The constant.
  19374. * @return {Plane} A reference to this plane.
  19375. */
  19376. set( normal, constant ) {
  19377. this.normal.copy( normal );
  19378. this.constant = constant;
  19379. return this;
  19380. }
  19381. /**
  19382. * Sets the plane components by defining `x`, `y`, `z` as the
  19383. * plane normal and `w` as the constant.
  19384. *
  19385. * @param {number} x - The value for the normal's x component.
  19386. * @param {number} y - The value for the normal's y component.
  19387. * @param {number} z - The value for the normal's z component.
  19388. * @param {number} w - The constant value.
  19389. * @return {Plane} A reference to this plane.
  19390. */
  19391. setComponents( x, y, z, w ) {
  19392. this.normal.set( x, y, z );
  19393. this.constant = w;
  19394. return this;
  19395. }
  19396. /**
  19397. * Sets the plane from the given normal and coplanar point (that is a point
  19398. * that lies onto the plane).
  19399. *
  19400. * @param {Vector3} normal - The normal.
  19401. * @param {Vector3} point - A coplanar point.
  19402. * @return {Plane} A reference to this plane.
  19403. */
  19404. setFromNormalAndCoplanarPoint( normal, point ) {
  19405. this.normal.copy( normal );
  19406. this.constant = - point.dot( this.normal );
  19407. return this;
  19408. }
  19409. /**
  19410. * Sets the plane from three coplanar points. The winding order is
  19411. * assumed to be counter-clockwise, and determines the direction of
  19412. * the plane normal.
  19413. *
  19414. * @param {Vector3} a - The first coplanar point.
  19415. * @param {Vector3} b - The second coplanar point.
  19416. * @param {Vector3} c - The third coplanar point.
  19417. * @return {Plane} A reference to this plane.
  19418. */
  19419. setFromCoplanarPoints( a, b, c ) {
  19420. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19421. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19422. this.setFromNormalAndCoplanarPoint( normal, a );
  19423. return this;
  19424. }
  19425. /**
  19426. * Copies the values of the given plane to this instance.
  19427. *
  19428. * @param {Plane} plane - The plane to copy.
  19429. * @return {Plane} A reference to this plane.
  19430. */
  19431. copy( plane ) {
  19432. this.normal.copy( plane.normal );
  19433. this.constant = plane.constant;
  19434. return this;
  19435. }
  19436. /**
  19437. * Normalizes the plane normal and adjusts the constant accordingly.
  19438. *
  19439. * @return {Plane} A reference to this plane.
  19440. */
  19441. normalize() {
  19442. // Note: will lead to a divide by zero if the plane is invalid.
  19443. const inverseNormalLength = 1.0 / this.normal.length();
  19444. this.normal.multiplyScalar( inverseNormalLength );
  19445. this.constant *= inverseNormalLength;
  19446. return this;
  19447. }
  19448. /**
  19449. * Negates both the plane normal and the constant.
  19450. *
  19451. * @return {Plane} A reference to this plane.
  19452. */
  19453. negate() {
  19454. this.constant *= -1;
  19455. this.normal.negate();
  19456. return this;
  19457. }
  19458. /**
  19459. * Returns the signed distance from the given point to this plane.
  19460. *
  19461. * @param {Vector3} point - The point to compute the distance for.
  19462. * @return {number} The signed distance.
  19463. */
  19464. distanceToPoint( point ) {
  19465. return this.normal.dot( point ) + this.constant;
  19466. }
  19467. /**
  19468. * Returns the signed distance from the given sphere to this plane.
  19469. *
  19470. * @param {Sphere} sphere - The sphere to compute the distance for.
  19471. * @return {number} The signed distance.
  19472. */
  19473. distanceToSphere( sphere ) {
  19474. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19475. }
  19476. /**
  19477. * Projects a the given point onto the plane.
  19478. *
  19479. * @param {Vector3} point - The point to project.
  19480. * @param {Vector3} target - The target vector that is used to store the method's result.
  19481. * @return {Vector3} The projected point on the plane.
  19482. */
  19483. projectPoint( point, target ) {
  19484. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19485. }
  19486. /**
  19487. * Returns the intersection point of the passed line and the plane. Returns
  19488. * `null` if the line does not intersect. Returns the line's starting point if
  19489. * the line is coplanar with the plane.
  19490. *
  19491. * @param {Line3} line - The line to compute the intersection for.
  19492. * @param {Vector3} target - The target vector that is used to store the method's result.
  19493. * @return {?Vector3} The intersection point.
  19494. */
  19495. intersectLine( line, target ) {
  19496. const direction = line.delta( _vector1 );
  19497. const denominator = this.normal.dot( direction );
  19498. if ( denominator === 0 ) {
  19499. // line is coplanar, return origin
  19500. if ( this.distanceToPoint( line.start ) === 0 ) {
  19501. return target.copy( line.start );
  19502. }
  19503. // Unsure if this is the correct method to handle this case.
  19504. return null;
  19505. }
  19506. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19507. if ( t < 0 || t > 1 ) {
  19508. return null;
  19509. }
  19510. return target.copy( line.start ).addScaledVector( direction, t );
  19511. }
  19512. /**
  19513. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19514. *
  19515. * @param {Line3} line - The line to test.
  19516. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19517. */
  19518. intersectsLine( line ) {
  19519. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19520. const startSign = this.distanceToPoint( line.start );
  19521. const endSign = this.distanceToPoint( line.end );
  19522. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19523. }
  19524. /**
  19525. * Returns `true` if the given bounding box intersects with the plane.
  19526. *
  19527. * @param {Box3} box - The bounding box to test.
  19528. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19529. */
  19530. intersectsBox( box ) {
  19531. return box.intersectsPlane( this );
  19532. }
  19533. /**
  19534. * Returns `true` if the given bounding sphere intersects with the plane.
  19535. *
  19536. * @param {Sphere} sphere - The bounding sphere to test.
  19537. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19538. */
  19539. intersectsSphere( sphere ) {
  19540. return sphere.intersectsPlane( this );
  19541. }
  19542. /**
  19543. * Returns a coplanar vector to the plane, by calculating the
  19544. * projection of the normal at the origin onto the plane.
  19545. *
  19546. * @param {Vector3} target - The target vector that is used to store the method's result.
  19547. * @return {Vector3} The coplanar point.
  19548. */
  19549. coplanarPoint( target ) {
  19550. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19551. }
  19552. /**
  19553. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19554. *
  19555. * The optional normal matrix can be pre-computed like so:
  19556. * ```js
  19557. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19558. * ```
  19559. *
  19560. * @param {Matrix4} matrix - The transformation matrix.
  19561. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19562. * @return {Plane} A reference to this plane.
  19563. */
  19564. applyMatrix4( matrix, optionalNormalMatrix ) {
  19565. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19566. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19567. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19568. this.constant = - referencePoint.dot( normal );
  19569. return this;
  19570. }
  19571. /**
  19572. * Translates the plane by the distance defined by the given offset vector.
  19573. * Note that this only affects the plane constant and will not affect the normal vector.
  19574. *
  19575. * @param {Vector3} offset - The offset vector.
  19576. * @return {Plane} A reference to this plane.
  19577. */
  19578. translate( offset ) {
  19579. this.constant -= offset.dot( this.normal );
  19580. return this;
  19581. }
  19582. /**
  19583. * Returns `true` if this plane is equal with the given one.
  19584. *
  19585. * @param {Plane} plane - The plane to test for equality.
  19586. * @return {boolean} Whether this plane is equal with the given one.
  19587. */
  19588. equals( plane ) {
  19589. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19590. }
  19591. /**
  19592. * Returns a new plane with copied values from this instance.
  19593. *
  19594. * @return {Plane} A clone of this instance.
  19595. */
  19596. clone() {
  19597. return new this.constructor().copy( this );
  19598. }
  19599. }
  19600. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19601. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19602. const _vector$6 = /*@__PURE__*/ new Vector3();
  19603. /**
  19604. * Frustums are used to determine what is inside the camera's field of view.
  19605. * They help speed up the rendering process - objects which lie outside a camera's
  19606. * frustum can safely be excluded from rendering.
  19607. *
  19608. * This class is mainly intended for use internally by a renderer.
  19609. */
  19610. class Frustum {
  19611. /**
  19612. * Constructs a new frustum.
  19613. *
  19614. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19615. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19616. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19617. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19618. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19619. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19620. */
  19621. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19622. /**
  19623. * This array holds the planes that enclose the frustum.
  19624. *
  19625. * @type {Array<Plane>}
  19626. */
  19627. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19628. }
  19629. /**
  19630. * Sets the frustum planes by copying the given planes.
  19631. *
  19632. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19633. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19634. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19635. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19636. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19637. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19638. * @return {Frustum} A reference to this frustum.
  19639. */
  19640. set( p0, p1, p2, p3, p4, p5 ) {
  19641. const planes = this.planes;
  19642. planes[ 0 ].copy( p0 );
  19643. planes[ 1 ].copy( p1 );
  19644. planes[ 2 ].copy( p2 );
  19645. planes[ 3 ].copy( p3 );
  19646. planes[ 4 ].copy( p4 );
  19647. planes[ 5 ].copy( p5 );
  19648. return this;
  19649. }
  19650. /**
  19651. * Copies the values of the given frustum to this instance.
  19652. *
  19653. * @param {Frustum} frustum - The frustum to copy.
  19654. * @return {Frustum} A reference to this frustum.
  19655. */
  19656. copy( frustum ) {
  19657. const planes = this.planes;
  19658. for ( let i = 0; i < 6; i ++ ) {
  19659. planes[ i ].copy( frustum.planes[ i ] );
  19660. }
  19661. return this;
  19662. }
  19663. /**
  19664. * Sets the frustum planes from the given projection matrix.
  19665. *
  19666. * @param {Matrix4} m - The projection matrix.
  19667. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19668. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19669. * @return {Frustum} A reference to this frustum.
  19670. */
  19671. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19672. const planes = this.planes;
  19673. const me = m.elements;
  19674. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19675. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19676. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19677. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19678. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19679. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19680. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19681. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19682. if ( reversedDepth ) {
  19683. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19684. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19685. } else {
  19686. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19687. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19688. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19689. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19690. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19691. } else {
  19692. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19693. }
  19694. }
  19695. return this;
  19696. }
  19697. /**
  19698. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19699. *
  19700. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19701. *
  19702. * @param {Object3D} object - The 3D object to test.
  19703. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19704. */
  19705. intersectsObject( object ) {
  19706. if ( object.boundingSphere !== undefined ) {
  19707. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19708. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19709. } else {
  19710. const geometry = object.geometry;
  19711. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19712. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19713. }
  19714. return this.intersectsSphere( _sphere$3 );
  19715. }
  19716. /**
  19717. * Returns `true` if the given sprite is intersecting this frustum.
  19718. *
  19719. * @param {Sprite} sprite - The sprite to test.
  19720. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19721. */
  19722. intersectsSprite( sprite ) {
  19723. _sphere$3.center.set( 0, 0, 0 );
  19724. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19725. _sphere$3.radius = 0.7071067811865476 + offset;
  19726. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19727. return this.intersectsSphere( _sphere$3 );
  19728. }
  19729. /**
  19730. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19731. *
  19732. * @param {Sphere} sphere - The bounding sphere to test.
  19733. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19734. */
  19735. intersectsSphere( sphere ) {
  19736. const planes = this.planes;
  19737. const center = sphere.center;
  19738. const negRadius = - sphere.radius;
  19739. for ( let i = 0; i < 6; i ++ ) {
  19740. const distance = planes[ i ].distanceToPoint( center );
  19741. if ( distance < negRadius ) {
  19742. return false;
  19743. }
  19744. }
  19745. return true;
  19746. }
  19747. /**
  19748. * Returns `true` if the given bounding box is intersecting this frustum.
  19749. *
  19750. * @param {Box3} box - The bounding box to test.
  19751. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19752. */
  19753. intersectsBox( box ) {
  19754. const planes = this.planes;
  19755. for ( let i = 0; i < 6; i ++ ) {
  19756. const plane = planes[ i ];
  19757. // corner at max distance
  19758. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19759. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19760. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19761. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19762. return false;
  19763. }
  19764. }
  19765. return true;
  19766. }
  19767. /**
  19768. * Returns `true` if the given point lies within the frustum.
  19769. *
  19770. * @param {Vector3} point - The point to test.
  19771. * @return {boolean} Whether the point lies within this frustum or not.
  19772. */
  19773. containsPoint( point ) {
  19774. const planes = this.planes;
  19775. for ( let i = 0; i < 6; i ++ ) {
  19776. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19777. return false;
  19778. }
  19779. }
  19780. return true;
  19781. }
  19782. /**
  19783. * Returns a new frustum with copied values from this instance.
  19784. *
  19785. * @return {Frustum} A clone of this instance.
  19786. */
  19787. clone() {
  19788. return new this.constructor().copy( this );
  19789. }
  19790. }
  19791. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19792. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19793. /**
  19794. * FrustumArray is used to determine if an object is visible in at least one camera
  19795. * from an array of cameras. This is particularly useful for multi-view renderers.
  19796. */
  19797. class FrustumArray {
  19798. /**
  19799. * Constructs a new frustum array.
  19800. *
  19801. */
  19802. constructor() {
  19803. /**
  19804. * The coordinate system to use.
  19805. *
  19806. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19807. * @default WebGLCoordinateSystem
  19808. */
  19809. this.coordinateSystem = WebGLCoordinateSystem;
  19810. }
  19811. /**
  19812. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19813. * from the camera array.
  19814. *
  19815. * @param {Object3D} object - The 3D object to test.
  19816. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19817. * @return {boolean} Whether the 3D object is visible in any camera.
  19818. */
  19819. intersectsObject( object, cameraArray ) {
  19820. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19821. return false;
  19822. }
  19823. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19824. const camera = cameraArray.cameras[ i ];
  19825. _projScreenMatrix$2.multiplyMatrices(
  19826. camera.projectionMatrix,
  19827. camera.matrixWorldInverse
  19828. );
  19829. _frustum$1.setFromProjectionMatrix(
  19830. _projScreenMatrix$2,
  19831. camera.coordinateSystem,
  19832. camera.reversedDepth
  19833. );
  19834. if ( _frustum$1.intersectsObject( object ) ) {
  19835. return true; // Object is visible in at least one camera
  19836. }
  19837. }
  19838. return false; // Not visible in any camera
  19839. }
  19840. /**
  19841. * Returns `true` if the given sprite is intersecting any frustum
  19842. * from the camera array.
  19843. *
  19844. * @param {Sprite} sprite - The sprite to test.
  19845. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19846. * @return {boolean} Whether the sprite is visible in any camera.
  19847. */
  19848. intersectsSprite( sprite, cameraArray ) {
  19849. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19850. return false;
  19851. }
  19852. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19853. const camera = cameraArray.cameras[ i ];
  19854. _projScreenMatrix$2.multiplyMatrices(
  19855. camera.projectionMatrix,
  19856. camera.matrixWorldInverse
  19857. );
  19858. _frustum$1.setFromProjectionMatrix(
  19859. _projScreenMatrix$2,
  19860. camera.coordinateSystem,
  19861. camera.reversedDepth
  19862. );
  19863. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19864. return true; // Sprite is visible in at least one camera
  19865. }
  19866. }
  19867. return false; // Not visible in any camera
  19868. }
  19869. /**
  19870. * Returns `true` if the given bounding sphere is intersecting any frustum
  19871. * from the camera array.
  19872. *
  19873. * @param {Sphere} sphere - The bounding sphere to test.
  19874. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19875. * @return {boolean} Whether the sphere is visible in any camera.
  19876. */
  19877. intersectsSphere( sphere, cameraArray ) {
  19878. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19879. return false;
  19880. }
  19881. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19882. const camera = cameraArray.cameras[ i ];
  19883. _projScreenMatrix$2.multiplyMatrices(
  19884. camera.projectionMatrix,
  19885. camera.matrixWorldInverse
  19886. );
  19887. _frustum$1.setFromProjectionMatrix(
  19888. _projScreenMatrix$2,
  19889. camera.coordinateSystem,
  19890. camera.reversedDepth
  19891. );
  19892. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19893. return true; // Sphere is visible in at least one camera
  19894. }
  19895. }
  19896. return false; // Not visible in any camera
  19897. }
  19898. /**
  19899. * Returns `true` if the given bounding box is intersecting any frustum
  19900. * from the camera array.
  19901. *
  19902. * @param {Box3} box - The bounding box to test.
  19903. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19904. * @return {boolean} Whether the box is visible in any camera.
  19905. */
  19906. intersectsBox( box, cameraArray ) {
  19907. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19908. return false;
  19909. }
  19910. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19911. const camera = cameraArray.cameras[ i ];
  19912. _projScreenMatrix$2.multiplyMatrices(
  19913. camera.projectionMatrix,
  19914. camera.matrixWorldInverse
  19915. );
  19916. _frustum$1.setFromProjectionMatrix(
  19917. _projScreenMatrix$2,
  19918. camera.coordinateSystem,
  19919. camera.reversedDepth
  19920. );
  19921. if ( _frustum$1.intersectsBox( box ) ) {
  19922. return true; // Box is visible in at least one camera
  19923. }
  19924. }
  19925. return false; // Not visible in any camera
  19926. }
  19927. /**
  19928. * Returns `true` if the given point lies within any frustum
  19929. * from the camera array.
  19930. *
  19931. * @param {Vector3} point - The point to test.
  19932. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19933. * @return {boolean} Whether the point is visible in any camera.
  19934. */
  19935. containsPoint( point, cameraArray ) {
  19936. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19937. return false;
  19938. }
  19939. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19940. const camera = cameraArray.cameras[ i ];
  19941. _projScreenMatrix$2.multiplyMatrices(
  19942. camera.projectionMatrix,
  19943. camera.matrixWorldInverse
  19944. );
  19945. _frustum$1.setFromProjectionMatrix(
  19946. _projScreenMatrix$2,
  19947. camera.coordinateSystem,
  19948. camera.reversedDepth
  19949. );
  19950. if ( _frustum$1.containsPoint( point ) ) {
  19951. return true; // Point is visible in at least one camera
  19952. }
  19953. }
  19954. return false; // Not visible in any camera
  19955. }
  19956. /**
  19957. * Returns a new frustum array with copied values from this instance.
  19958. *
  19959. * @return {FrustumArray} A clone of this instance.
  19960. */
  19961. clone() {
  19962. return new FrustumArray();
  19963. }
  19964. }
  19965. function ascIdSort( a, b ) {
  19966. return a - b;
  19967. }
  19968. function sortOpaque( a, b ) {
  19969. return a.z - b.z;
  19970. }
  19971. function sortTransparent( a, b ) {
  19972. return b.z - a.z;
  19973. }
  19974. class MultiDrawRenderList {
  19975. constructor() {
  19976. this.index = 0;
  19977. this.pool = [];
  19978. this.list = [];
  19979. }
  19980. push( start, count, z, index ) {
  19981. const pool = this.pool;
  19982. const list = this.list;
  19983. if ( this.index >= pool.length ) {
  19984. pool.push( {
  19985. start: -1,
  19986. count: -1,
  19987. z: -1,
  19988. index: -1,
  19989. } );
  19990. }
  19991. const item = pool[ this.index ];
  19992. list.push( item );
  19993. this.index ++;
  19994. item.start = start;
  19995. item.count = count;
  19996. item.z = z;
  19997. item.index = index;
  19998. }
  19999. reset() {
  20000. this.list.length = 0;
  20001. this.index = 0;
  20002. }
  20003. }
  20004. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20005. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20006. const _frustum = /*@__PURE__*/ new Frustum();
  20007. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20008. const _box$1 = /*@__PURE__*/ new Box3();
  20009. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20010. const _vector$5 = /*@__PURE__*/ new Vector3();
  20011. const _forward$1 = /*@__PURE__*/ new Vector3();
  20012. const _temp = /*@__PURE__*/ new Vector3();
  20013. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20014. const _mesh = /*@__PURE__*/ new Mesh();
  20015. const _batchIntersects = [];
  20016. // copies data from attribute "src" into "target" starting at "targetOffset"
  20017. function copyAttributeData( src, target, targetOffset = 0 ) {
  20018. const itemSize = target.itemSize;
  20019. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20020. // use the component getters and setters if the array data cannot
  20021. // be copied directly
  20022. const vertexCount = src.count;
  20023. for ( let i = 0; i < vertexCount; i ++ ) {
  20024. for ( let c = 0; c < itemSize; c ++ ) {
  20025. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20026. }
  20027. }
  20028. } else {
  20029. // faster copy approach using typed array set function
  20030. target.array.set( src.array, targetOffset * itemSize );
  20031. }
  20032. target.needsUpdate = true;
  20033. }
  20034. // safely copies array contents to a potentially smaller array
  20035. function copyArrayContents( src, target ) {
  20036. if ( src.constructor !== target.constructor ) {
  20037. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20038. const len = Math.min( src.length, target.length );
  20039. for ( let i = 0; i < len; i ++ ) {
  20040. target[ i ] = src[ i ];
  20041. }
  20042. } else {
  20043. // if the arrays use the same data layout we can use a fast block copy
  20044. const len = Math.min( src.length, target.length );
  20045. target.set( new src.constructor( src.buffer, 0, len ) );
  20046. }
  20047. }
  20048. /**
  20049. * A special version of a mesh with multi draw batch rendering support. Use
  20050. * this class if you have to render a large number of objects with the same
  20051. * material but with different geometries or world transformations. The usage of
  20052. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20053. * rendering performance in your application.
  20054. *
  20055. * ```js
  20056. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20057. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20058. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20059. *
  20060. * // initialize and add geometries into the batched mesh
  20061. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20062. * const boxGeometryId = batchedMesh.addGeometry( box );
  20063. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20064. *
  20065. * // create instances of those geometries
  20066. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20067. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20068. *
  20069. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20070. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20071. *
  20072. * // position the geometries
  20073. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20074. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20075. *
  20076. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20077. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20078. *
  20079. * scene.add( batchedMesh );
  20080. * ```
  20081. *
  20082. * @augments Mesh
  20083. */
  20084. class BatchedMesh extends Mesh {
  20085. /**
  20086. * Constructs a new batched mesh.
  20087. *
  20088. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20089. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20090. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20091. * @param {Material|Array<Material>} [material] - The mesh material.
  20092. */
  20093. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20094. super( new BufferGeometry(), material );
  20095. /**
  20096. * This flag can be used for type testing.
  20097. *
  20098. * @type {boolean}
  20099. * @readonly
  20100. * @default true
  20101. */
  20102. this.isBatchedMesh = true;
  20103. /**
  20104. * When set ot `true`, the individual objects of a batch are frustum culled.
  20105. *
  20106. * @type {boolean}
  20107. * @default true
  20108. */
  20109. this.perObjectFrustumCulled = true;
  20110. /**
  20111. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20112. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20113. * rendered front to back.
  20114. *
  20115. * @type {boolean}
  20116. * @default true
  20117. */
  20118. this.sortObjects = true;
  20119. /**
  20120. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20121. *
  20122. * @type {?Box3}
  20123. * @default null
  20124. */
  20125. this.boundingBox = null;
  20126. /**
  20127. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20128. *
  20129. * @type {?Sphere}
  20130. * @default null
  20131. */
  20132. this.boundingSphere = null;
  20133. /**
  20134. * Takes a sort a function that is run before render. The function takes a list of instances to
  20135. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20136. * sort with.
  20137. *
  20138. * @type {?Function}
  20139. * @default null
  20140. */
  20141. this.customSort = null;
  20142. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20143. this._instanceInfo = [];
  20144. this._geometryInfo = [];
  20145. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20146. this._availableInstanceIds = [];
  20147. this._availableGeometryIds = [];
  20148. // used to track where the next point is that geometry should be inserted
  20149. this._nextIndexStart = 0;
  20150. this._nextVertexStart = 0;
  20151. this._geometryCount = 0;
  20152. // flags
  20153. this._visibilityChanged = true;
  20154. this._geometryInitialized = false;
  20155. // cached user options
  20156. this._maxInstanceCount = maxInstanceCount;
  20157. this._maxVertexCount = maxVertexCount;
  20158. this._maxIndexCount = maxIndexCount;
  20159. // buffers for multi draw
  20160. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20161. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20162. this._multiDrawCount = 0;
  20163. this._multiDrawInstances = null;
  20164. // Local matrix per geometry by using data texture
  20165. this._matricesTexture = null;
  20166. this._indirectTexture = null;
  20167. this._colorsTexture = null;
  20168. this._initMatricesTexture();
  20169. this._initIndirectTexture();
  20170. }
  20171. /**
  20172. * The maximum number of individual instances that can be stored in the batch.
  20173. *
  20174. * @type {number}
  20175. * @readonly
  20176. */
  20177. get maxInstanceCount() {
  20178. return this._maxInstanceCount;
  20179. }
  20180. /**
  20181. * The instance count.
  20182. *
  20183. * @type {number}
  20184. * @readonly
  20185. */
  20186. get instanceCount() {
  20187. return this._instanceInfo.length - this._availableInstanceIds.length;
  20188. }
  20189. /**
  20190. * The number of unused vertices.
  20191. *
  20192. * @type {number}
  20193. * @readonly
  20194. */
  20195. get unusedVertexCount() {
  20196. return this._maxVertexCount - this._nextVertexStart;
  20197. }
  20198. /**
  20199. * The number of unused indices.
  20200. *
  20201. * @type {number}
  20202. * @readonly
  20203. */
  20204. get unusedIndexCount() {
  20205. return this._maxIndexCount - this._nextIndexStart;
  20206. }
  20207. _initMatricesTexture() {
  20208. // layout (1 matrix = 4 pixels)
  20209. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20210. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20211. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20212. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20213. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20214. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20215. size = Math.ceil( size / 4 ) * 4;
  20216. size = Math.max( size, 4 );
  20217. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20218. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20219. this._matricesTexture = matricesTexture;
  20220. }
  20221. _initIndirectTexture() {
  20222. let size = Math.sqrt( this._maxInstanceCount );
  20223. size = Math.ceil( size );
  20224. const indirectArray = new Uint32Array( size * size );
  20225. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20226. this._indirectTexture = indirectTexture;
  20227. }
  20228. _initColorsTexture() {
  20229. let size = Math.sqrt( this._maxInstanceCount );
  20230. size = Math.ceil( size );
  20231. // 4 floats per RGBA pixel initialized to white
  20232. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20233. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20234. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20235. this._colorsTexture = colorsTexture;
  20236. }
  20237. _initializeGeometry( reference ) {
  20238. const geometry = this.geometry;
  20239. const maxVertexCount = this._maxVertexCount;
  20240. const maxIndexCount = this._maxIndexCount;
  20241. if ( this._geometryInitialized === false ) {
  20242. for ( const attributeName in reference.attributes ) {
  20243. const srcAttribute = reference.getAttribute( attributeName );
  20244. const { array, itemSize, normalized } = srcAttribute;
  20245. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20246. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20247. geometry.setAttribute( attributeName, dstAttribute );
  20248. }
  20249. if ( reference.getIndex() !== null ) {
  20250. // Reserve last u16 index for primitive restart.
  20251. const indexArray = maxVertexCount > 65535
  20252. ? new Uint32Array( maxIndexCount )
  20253. : new Uint16Array( maxIndexCount );
  20254. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20255. }
  20256. this._geometryInitialized = true;
  20257. }
  20258. }
  20259. // Make sure the geometry is compatible with the existing combined geometry attributes
  20260. _validateGeometry( geometry ) {
  20261. // check to ensure the geometries are using consistent attributes and indices
  20262. const batchGeometry = this.geometry;
  20263. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20264. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20265. }
  20266. for ( const attributeName in batchGeometry.attributes ) {
  20267. if ( ! geometry.hasAttribute( attributeName ) ) {
  20268. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20269. }
  20270. const srcAttribute = geometry.getAttribute( attributeName );
  20271. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20272. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20273. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20274. }
  20275. }
  20276. }
  20277. /**
  20278. * Validates the instance defined by the given ID.
  20279. *
  20280. * @param {number} instanceId - The instance to validate.
  20281. */
  20282. validateInstanceId( instanceId ) {
  20283. const instanceInfo = this._instanceInfo;
  20284. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20285. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20286. }
  20287. }
  20288. /**
  20289. * Validates the geometry defined by the given ID.
  20290. *
  20291. * @param {number} geometryId - The geometry to validate.
  20292. */
  20293. validateGeometryId( geometryId ) {
  20294. const geometryInfoList = this._geometryInfo;
  20295. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20296. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20297. }
  20298. }
  20299. /**
  20300. * Takes a sort a function that is run before render. The function takes a list of instances to
  20301. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20302. *
  20303. * @param {Function} func - The custom sort function.
  20304. * @return {BatchedMesh} A reference to this batched mesh.
  20305. */
  20306. setCustomSort( func ) {
  20307. this.customSort = func;
  20308. return this;
  20309. }
  20310. /**
  20311. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20312. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20313. * otherwise they are `null`.
  20314. */
  20315. computeBoundingBox() {
  20316. if ( this.boundingBox === null ) {
  20317. this.boundingBox = new Box3();
  20318. }
  20319. const boundingBox = this.boundingBox;
  20320. const instanceInfo = this._instanceInfo;
  20321. boundingBox.makeEmpty();
  20322. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20323. if ( instanceInfo[ i ].active === false ) continue;
  20324. const geometryId = instanceInfo[ i ].geometryIndex;
  20325. this.getMatrixAt( i, _matrix$1 );
  20326. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20327. boundingBox.union( _box$1 );
  20328. }
  20329. }
  20330. /**
  20331. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20332. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20333. * otherwise they are `null`.
  20334. */
  20335. computeBoundingSphere() {
  20336. if ( this.boundingSphere === null ) {
  20337. this.boundingSphere = new Sphere();
  20338. }
  20339. const boundingSphere = this.boundingSphere;
  20340. const instanceInfo = this._instanceInfo;
  20341. boundingSphere.makeEmpty();
  20342. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20343. if ( instanceInfo[ i ].active === false ) continue;
  20344. const geometryId = instanceInfo[ i ].geometryIndex;
  20345. this.getMatrixAt( i, _matrix$1 );
  20346. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20347. boundingSphere.union( _sphere$2 );
  20348. }
  20349. }
  20350. /**
  20351. * Adds a new instance to the batch using the geometry of the given ID and returns
  20352. * a new id referring to the new instance to be used by other functions.
  20353. *
  20354. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20355. * @return {number} The instance ID.
  20356. */
  20357. addInstance( geometryId ) {
  20358. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20359. // ensure we're not over geometry
  20360. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20361. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20362. }
  20363. const instanceInfo = {
  20364. visible: true,
  20365. active: true,
  20366. geometryIndex: geometryId,
  20367. };
  20368. let drawId = null;
  20369. // Prioritize using previously freed instance ids
  20370. if ( this._availableInstanceIds.length > 0 ) {
  20371. this._availableInstanceIds.sort( ascIdSort );
  20372. drawId = this._availableInstanceIds.shift();
  20373. this._instanceInfo[ drawId ] = instanceInfo;
  20374. } else {
  20375. drawId = this._instanceInfo.length;
  20376. this._instanceInfo.push( instanceInfo );
  20377. }
  20378. const matricesTexture = this._matricesTexture;
  20379. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20380. matricesTexture.needsUpdate = true;
  20381. const colorsTexture = this._colorsTexture;
  20382. if ( colorsTexture ) {
  20383. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20384. colorsTexture.needsUpdate = true;
  20385. }
  20386. this._visibilityChanged = true;
  20387. return drawId;
  20388. }
  20389. /**
  20390. * Adds the given geometry to the batch and returns the associated
  20391. * geometry id referring to it to be used in other functions.
  20392. *
  20393. * @param {BufferGeometry} geometry - The geometry to add.
  20394. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20395. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20396. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20397. * Defaults to the length of the given geometry vertex buffer.
  20398. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20399. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20400. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20401. * the length of the given geometry index buffer.
  20402. * @return {number} The geometry ID.
  20403. */
  20404. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20405. this._initializeGeometry( geometry );
  20406. this._validateGeometry( geometry );
  20407. const geometryInfo = {
  20408. // geometry information
  20409. vertexStart: -1,
  20410. vertexCount: -1,
  20411. reservedVertexCount: -1,
  20412. indexStart: -1,
  20413. indexCount: -1,
  20414. reservedIndexCount: -1,
  20415. // draw range information
  20416. start: -1,
  20417. count: -1,
  20418. // state
  20419. boundingBox: null,
  20420. boundingSphere: null,
  20421. active: true,
  20422. };
  20423. const geometryInfoList = this._geometryInfo;
  20424. geometryInfo.vertexStart = this._nextVertexStart;
  20425. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20426. const index = geometry.getIndex();
  20427. const hasIndex = index !== null;
  20428. if ( hasIndex ) {
  20429. geometryInfo.indexStart = this._nextIndexStart;
  20430. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20431. }
  20432. if (
  20433. geometryInfo.indexStart !== -1 &&
  20434. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20435. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20436. ) {
  20437. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20438. }
  20439. // update id
  20440. let geometryId;
  20441. if ( this._availableGeometryIds.length > 0 ) {
  20442. this._availableGeometryIds.sort( ascIdSort );
  20443. geometryId = this._availableGeometryIds.shift();
  20444. geometryInfoList[ geometryId ] = geometryInfo;
  20445. } else {
  20446. geometryId = this._geometryCount;
  20447. this._geometryCount ++;
  20448. geometryInfoList.push( geometryInfo );
  20449. }
  20450. // update the geometry
  20451. this.setGeometryAt( geometryId, geometry );
  20452. // increment the next geometry position
  20453. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20454. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20455. return geometryId;
  20456. }
  20457. /**
  20458. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20459. * is not enough space reserved for geometry. Calling this will change all instances that are
  20460. * rendering that geometry.
  20461. *
  20462. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20463. * @param {BufferGeometry} geometry - The new geometry.
  20464. * @return {number} The geometry ID.
  20465. */
  20466. setGeometryAt( geometryId, geometry ) {
  20467. if ( geometryId >= this._geometryCount ) {
  20468. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20469. }
  20470. this._validateGeometry( geometry );
  20471. const batchGeometry = this.geometry;
  20472. const hasIndex = batchGeometry.getIndex() !== null;
  20473. const dstIndex = batchGeometry.getIndex();
  20474. const srcIndex = geometry.getIndex();
  20475. const geometryInfo = this._geometryInfo[ geometryId ];
  20476. if (
  20477. hasIndex &&
  20478. srcIndex.count > geometryInfo.reservedIndexCount ||
  20479. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20480. ) {
  20481. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20482. }
  20483. // copy geometry buffer data over
  20484. const vertexStart = geometryInfo.vertexStart;
  20485. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20486. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20487. for ( const attributeName in batchGeometry.attributes ) {
  20488. // copy attribute data
  20489. const srcAttribute = geometry.getAttribute( attributeName );
  20490. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20491. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20492. // fill the rest in with zeroes
  20493. const itemSize = srcAttribute.itemSize;
  20494. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20495. const index = vertexStart + i;
  20496. for ( let c = 0; c < itemSize; c ++ ) {
  20497. dstAttribute.setComponent( index, c, 0 );
  20498. }
  20499. }
  20500. dstAttribute.needsUpdate = true;
  20501. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20502. }
  20503. // copy index
  20504. if ( hasIndex ) {
  20505. const indexStart = geometryInfo.indexStart;
  20506. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20507. geometryInfo.indexCount = geometry.getIndex().count;
  20508. // copy index data over
  20509. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20510. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20511. }
  20512. // fill the rest in with zeroes
  20513. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20514. dstIndex.setX( indexStart + i, vertexStart );
  20515. }
  20516. dstIndex.needsUpdate = true;
  20517. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20518. }
  20519. // update the draw range
  20520. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20521. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20522. // store the bounding boxes
  20523. geometryInfo.boundingBox = null;
  20524. if ( geometry.boundingBox !== null ) {
  20525. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20526. }
  20527. geometryInfo.boundingSphere = null;
  20528. if ( geometry.boundingSphere !== null ) {
  20529. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20530. }
  20531. this._visibilityChanged = true;
  20532. return geometryId;
  20533. }
  20534. /**
  20535. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20536. * this geometry will also be removed as a side effect.
  20537. *
  20538. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20539. * @return {BatchedMesh} A reference to this batched mesh.
  20540. */
  20541. deleteGeometry( geometryId ) {
  20542. const geometryInfoList = this._geometryInfo;
  20543. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20544. return this;
  20545. }
  20546. // delete any instances associated with this geometry
  20547. const instanceInfo = this._instanceInfo;
  20548. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20549. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20550. this.deleteInstance( i );
  20551. }
  20552. }
  20553. geometryInfoList[ geometryId ].active = false;
  20554. this._availableGeometryIds.push( geometryId );
  20555. this._visibilityChanged = true;
  20556. return this;
  20557. }
  20558. /**
  20559. * Deletes an existing instance from the batch using the given ID.
  20560. *
  20561. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20562. * @return {BatchedMesh} A reference to this batched mesh.
  20563. */
  20564. deleteInstance( instanceId ) {
  20565. this.validateInstanceId( instanceId );
  20566. this._instanceInfo[ instanceId ].active = false;
  20567. this._availableInstanceIds.push( instanceId );
  20568. this._visibilityChanged = true;
  20569. return this;
  20570. }
  20571. /**
  20572. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20573. * previously deleted geometry, freeing up space to add new geometry.
  20574. *
  20575. * @return {BatchedMesh} A reference to this batched mesh.
  20576. */
  20577. optimize() {
  20578. // track the next indices to copy data to
  20579. let nextVertexStart = 0;
  20580. let nextIndexStart = 0;
  20581. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20582. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20583. const geometryInfoList = this._geometryInfo;
  20584. const indices = geometryInfoList
  20585. .map( ( e, i ) => i )
  20586. .sort( ( a, b ) => {
  20587. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20588. } );
  20589. const geometry = this.geometry;
  20590. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20591. // if a geometry range is inactive then don't copy anything
  20592. const index = indices[ i ];
  20593. const geometryInfo = geometryInfoList[ index ];
  20594. if ( geometryInfo.active === false ) {
  20595. continue;
  20596. }
  20597. // if a geometry contains an index buffer then shift it, as well
  20598. if ( geometry.index !== null ) {
  20599. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20600. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20601. const index = geometry.index;
  20602. const array = index.array;
  20603. // shift the index pointers based on how the vertex data will shift
  20604. // adjusting the index must happen first so the original vertex start value is available
  20605. const elementDelta = nextVertexStart - vertexStart;
  20606. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20607. array[ j ] = array[ j ] + elementDelta;
  20608. }
  20609. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20610. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20611. index.needsUpdate = true;
  20612. geometryInfo.indexStart = nextIndexStart;
  20613. }
  20614. nextIndexStart += geometryInfo.reservedIndexCount;
  20615. }
  20616. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20617. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20618. const { vertexStart, reservedVertexCount } = geometryInfo;
  20619. const attributes = geometry.attributes;
  20620. for ( const key in attributes ) {
  20621. const attribute = attributes[ key ];
  20622. const { array, itemSize } = attribute;
  20623. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20624. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20625. attribute.needsUpdate = true;
  20626. }
  20627. geometryInfo.vertexStart = nextVertexStart;
  20628. }
  20629. nextVertexStart += geometryInfo.reservedVertexCount;
  20630. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20631. // step the next geometry points to the shifted position
  20632. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20633. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20634. }
  20635. this._visibilityChanged = true;
  20636. return this;
  20637. }
  20638. /**
  20639. * Returns the bounding box for the given geometry.
  20640. *
  20641. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20642. * @param {Box3} target - The target object that is used to store the method's result.
  20643. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20644. */
  20645. getBoundingBoxAt( geometryId, target ) {
  20646. if ( geometryId >= this._geometryCount ) {
  20647. return null;
  20648. }
  20649. // compute bounding box
  20650. const geometry = this.geometry;
  20651. const geometryInfo = this._geometryInfo[ geometryId ];
  20652. if ( geometryInfo.boundingBox === null ) {
  20653. const box = new Box3();
  20654. const index = geometry.index;
  20655. const position = geometry.attributes.position;
  20656. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20657. let iv = i;
  20658. if ( index ) {
  20659. iv = index.getX( iv );
  20660. }
  20661. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20662. }
  20663. geometryInfo.boundingBox = box;
  20664. }
  20665. target.copy( geometryInfo.boundingBox );
  20666. return target;
  20667. }
  20668. /**
  20669. * Returns the bounding sphere for the given geometry.
  20670. *
  20671. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20672. * @param {Sphere} target - The target object that is used to store the method's result.
  20673. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20674. */
  20675. getBoundingSphereAt( geometryId, target ) {
  20676. if ( geometryId >= this._geometryCount ) {
  20677. return null;
  20678. }
  20679. // compute bounding sphere
  20680. const geometry = this.geometry;
  20681. const geometryInfo = this._geometryInfo[ geometryId ];
  20682. if ( geometryInfo.boundingSphere === null ) {
  20683. const sphere = new Sphere();
  20684. this.getBoundingBoxAt( geometryId, _box$1 );
  20685. _box$1.getCenter( sphere.center );
  20686. const index = geometry.index;
  20687. const position = geometry.attributes.position;
  20688. let maxRadiusSq = 0;
  20689. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20690. let iv = i;
  20691. if ( index ) {
  20692. iv = index.getX( iv );
  20693. }
  20694. _vector$5.fromBufferAttribute( position, iv );
  20695. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20696. }
  20697. sphere.radius = Math.sqrt( maxRadiusSq );
  20698. geometryInfo.boundingSphere = sphere;
  20699. }
  20700. target.copy( geometryInfo.boundingSphere );
  20701. return target;
  20702. }
  20703. /**
  20704. * Sets the given local transformation matrix to the defined instance.
  20705. * Negatively scaled matrices are not supported.
  20706. *
  20707. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20708. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20709. * @return {BatchedMesh} A reference to this batched mesh.
  20710. */
  20711. setMatrixAt( instanceId, matrix ) {
  20712. this.validateInstanceId( instanceId );
  20713. const matricesTexture = this._matricesTexture;
  20714. const matricesArray = this._matricesTexture.image.data;
  20715. matrix.toArray( matricesArray, instanceId * 16 );
  20716. matricesTexture.needsUpdate = true;
  20717. return this;
  20718. }
  20719. /**
  20720. * Returns the local transformation matrix of the defined instance.
  20721. *
  20722. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20723. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20724. * @return {Matrix4} The instance's local transformation matrix.
  20725. */
  20726. getMatrixAt( instanceId, matrix ) {
  20727. this.validateInstanceId( instanceId );
  20728. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20729. }
  20730. /**
  20731. * Sets the given color to the defined instance.
  20732. *
  20733. * @param {number} instanceId - The ID of an instance to set the color of.
  20734. * @param {Color} color - The color to set the instance to.
  20735. * @return {BatchedMesh} A reference to this batched mesh.
  20736. */
  20737. setColorAt( instanceId, color ) {
  20738. this.validateInstanceId( instanceId );
  20739. if ( this._colorsTexture === null ) {
  20740. this._initColorsTexture();
  20741. }
  20742. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20743. this._colorsTexture.needsUpdate = true;
  20744. return this;
  20745. }
  20746. /**
  20747. * Returns the color of the defined instance.
  20748. *
  20749. * @param {number} instanceId - The ID of an instance to get the color of.
  20750. * @param {Color} color - The target object that is used to store the method's result.
  20751. * @return {Color} The instance's color.
  20752. */
  20753. getColorAt( instanceId, color ) {
  20754. this.validateInstanceId( instanceId );
  20755. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20756. }
  20757. /**
  20758. * Sets the visibility of the instance.
  20759. *
  20760. * @param {number} instanceId - The id of the instance to set the visibility of.
  20761. * @param {boolean} visible - Whether the instance is visible or not.
  20762. * @return {BatchedMesh} A reference to this batched mesh.
  20763. */
  20764. setVisibleAt( instanceId, visible ) {
  20765. this.validateInstanceId( instanceId );
  20766. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20767. return this;
  20768. }
  20769. this._instanceInfo[ instanceId ].visible = visible;
  20770. this._visibilityChanged = true;
  20771. return this;
  20772. }
  20773. /**
  20774. * Returns the visibility state of the defined instance.
  20775. *
  20776. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20777. * @return {boolean} Whether the instance is visible or not.
  20778. */
  20779. getVisibleAt( instanceId ) {
  20780. this.validateInstanceId( instanceId );
  20781. return this._instanceInfo[ instanceId ].visible;
  20782. }
  20783. /**
  20784. * Sets the geometry ID of the instance at the given index.
  20785. *
  20786. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20787. * @param {number} geometryId - The geometry ID to be use by the instance.
  20788. * @return {BatchedMesh} A reference to this batched mesh.
  20789. */
  20790. setGeometryIdAt( instanceId, geometryId ) {
  20791. this.validateInstanceId( instanceId );
  20792. this.validateGeometryId( geometryId );
  20793. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20794. return this;
  20795. }
  20796. /**
  20797. * Returns the geometry ID of the defined instance.
  20798. *
  20799. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20800. * @return {number} The instance's geometry ID.
  20801. */
  20802. getGeometryIdAt( instanceId ) {
  20803. this.validateInstanceId( instanceId );
  20804. return this._instanceInfo[ instanceId ].geometryIndex;
  20805. }
  20806. /**
  20807. * Get the range representing the subset of triangles related to the attached geometry,
  20808. * indicating the starting offset and count, or `null` if invalid.
  20809. *
  20810. * @param {number} geometryId - The id of the geometry to get the range of.
  20811. * @param {Object} [target] - The target object that is used to store the method's result.
  20812. * @return {{
  20813. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20814. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20815. * start:number,count:number
  20816. * }} The result object with range data.
  20817. */
  20818. getGeometryRangeAt( geometryId, target = {} ) {
  20819. this.validateGeometryId( geometryId );
  20820. const geometryInfo = this._geometryInfo[ geometryId ];
  20821. target.vertexStart = geometryInfo.vertexStart;
  20822. target.vertexCount = geometryInfo.vertexCount;
  20823. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20824. target.indexStart = geometryInfo.indexStart;
  20825. target.indexCount = geometryInfo.indexCount;
  20826. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20827. target.start = geometryInfo.start;
  20828. target.count = geometryInfo.count;
  20829. return target;
  20830. }
  20831. /**
  20832. * Resizes the necessary buffers to support the provided number of instances.
  20833. * If the provided arguments shrink the number of instances but there are not enough
  20834. * unused Ids at the end of the list then an error is thrown.
  20835. *
  20836. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20837. */
  20838. setInstanceCount( maxInstanceCount ) {
  20839. // shrink the available instances as much as possible
  20840. const availableInstanceIds = this._availableInstanceIds;
  20841. const instanceInfo = this._instanceInfo;
  20842. availableInstanceIds.sort( ascIdSort );
  20843. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20844. instanceInfo.pop();
  20845. availableInstanceIds.pop();
  20846. }
  20847. // throw an error if it can't be shrunk to the desired size
  20848. if ( maxInstanceCount < instanceInfo.length ) {
  20849. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20850. }
  20851. // copy the multi draw counts
  20852. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20853. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20854. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20855. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20856. this._multiDrawCounts = multiDrawCounts;
  20857. this._multiDrawStarts = multiDrawStarts;
  20858. this._maxInstanceCount = maxInstanceCount;
  20859. // update texture data for instance sampling
  20860. const indirectTexture = this._indirectTexture;
  20861. const matricesTexture = this._matricesTexture;
  20862. const colorsTexture = this._colorsTexture;
  20863. indirectTexture.dispose();
  20864. this._initIndirectTexture();
  20865. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20866. matricesTexture.dispose();
  20867. this._initMatricesTexture();
  20868. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20869. if ( colorsTexture ) {
  20870. colorsTexture.dispose();
  20871. this._initColorsTexture();
  20872. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20873. }
  20874. }
  20875. /**
  20876. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20877. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20878. * end of the geometry attributes then an error is thrown.
  20879. *
  20880. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20881. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20882. */
  20883. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20884. // Check if we can shrink to the requested vertex attribute size
  20885. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20886. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20887. if ( requiredVertexLength > maxVertexCount ) {
  20888. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20889. }
  20890. // Check if we can shrink to the requested index attribute size
  20891. if ( this.geometry.index ) {
  20892. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20893. if ( requiredIndexLength > maxIndexCount ) {
  20894. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20895. }
  20896. }
  20897. //
  20898. // dispose of the previous geometry
  20899. const oldGeometry = this.geometry;
  20900. oldGeometry.dispose();
  20901. // recreate the geometry needed based on the previous variant
  20902. this._maxVertexCount = maxVertexCount;
  20903. this._maxIndexCount = maxIndexCount;
  20904. if ( this._geometryInitialized ) {
  20905. this._geometryInitialized = false;
  20906. this.geometry = new BufferGeometry();
  20907. this._initializeGeometry( oldGeometry );
  20908. }
  20909. // copy data from the previous geometry
  20910. const geometry = this.geometry;
  20911. if ( oldGeometry.index ) {
  20912. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20913. }
  20914. for ( const key in oldGeometry.attributes ) {
  20915. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20916. }
  20917. }
  20918. raycast( raycaster, intersects ) {
  20919. const instanceInfo = this._instanceInfo;
  20920. const geometryInfoList = this._geometryInfo;
  20921. const matrixWorld = this.matrixWorld;
  20922. const batchGeometry = this.geometry;
  20923. // iterate over each geometry
  20924. _mesh.material = this.material;
  20925. _mesh.geometry.index = batchGeometry.index;
  20926. _mesh.geometry.attributes = batchGeometry.attributes;
  20927. if ( _mesh.geometry.boundingBox === null ) {
  20928. _mesh.geometry.boundingBox = new Box3();
  20929. }
  20930. if ( _mesh.geometry.boundingSphere === null ) {
  20931. _mesh.geometry.boundingSphere = new Sphere();
  20932. }
  20933. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20934. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20935. continue;
  20936. }
  20937. const geometryId = instanceInfo[ i ].geometryIndex;
  20938. const geometryInfo = geometryInfoList[ geometryId ];
  20939. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20940. // get the intersects
  20941. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20942. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20943. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20944. _mesh.raycast( raycaster, _batchIntersects );
  20945. // add batch id to the intersects
  20946. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20947. const intersect = _batchIntersects[ j ];
  20948. intersect.object = this;
  20949. intersect.batchId = i;
  20950. intersects.push( intersect );
  20951. }
  20952. _batchIntersects.length = 0;
  20953. }
  20954. _mesh.material = null;
  20955. _mesh.geometry.index = null;
  20956. _mesh.geometry.attributes = {};
  20957. _mesh.geometry.setDrawRange( 0, Infinity );
  20958. }
  20959. copy( source ) {
  20960. super.copy( source );
  20961. this.geometry = source.geometry.clone();
  20962. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20963. this.sortObjects = source.sortObjects;
  20964. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20965. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20966. this._geometryInfo = source._geometryInfo.map( info => ( {
  20967. ...info,
  20968. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20969. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20970. } ) );
  20971. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20972. this._availableInstanceIds = source._availableInstanceIds.slice();
  20973. this._availableGeometryIds = source._availableGeometryIds.slice();
  20974. this._nextIndexStart = source._nextIndexStart;
  20975. this._nextVertexStart = source._nextVertexStart;
  20976. this._geometryCount = source._geometryCount;
  20977. this._maxInstanceCount = source._maxInstanceCount;
  20978. this._maxVertexCount = source._maxVertexCount;
  20979. this._maxIndexCount = source._maxIndexCount;
  20980. this._geometryInitialized = source._geometryInitialized;
  20981. this._multiDrawCounts = source._multiDrawCounts.slice();
  20982. this._multiDrawStarts = source._multiDrawStarts.slice();
  20983. this._indirectTexture = source._indirectTexture.clone();
  20984. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20985. this._matricesTexture = source._matricesTexture.clone();
  20986. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20987. if ( this._colorsTexture !== null ) {
  20988. this._colorsTexture = source._colorsTexture.clone();
  20989. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20990. }
  20991. return this;
  20992. }
  20993. /**
  20994. * Frees the GPU-related resources allocated by this instance. Call this
  20995. * method whenever this instance is no longer used in your app.
  20996. */
  20997. dispose() {
  20998. // Assuming the geometry is not shared with other meshes
  20999. this.geometry.dispose();
  21000. this._matricesTexture.dispose();
  21001. this._matricesTexture = null;
  21002. this._indirectTexture.dispose();
  21003. this._indirectTexture = null;
  21004. if ( this._colorsTexture !== null ) {
  21005. this._colorsTexture.dispose();
  21006. this._colorsTexture = null;
  21007. }
  21008. }
  21009. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21010. // if visibility has not changed and frustum culling and object sorting is not required
  21011. // then skip iterating over all items
  21012. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21013. return;
  21014. }
  21015. // the indexed version of the multi draw function requires specifying the start
  21016. // offset in bytes.
  21017. const index = geometry.getIndex();
  21018. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21019. const instanceInfo = this._instanceInfo;
  21020. const multiDrawStarts = this._multiDrawStarts;
  21021. const multiDrawCounts = this._multiDrawCounts;
  21022. const geometryInfoList = this._geometryInfo;
  21023. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21024. const indirectTexture = this._indirectTexture;
  21025. const indirectArray = indirectTexture.image.data;
  21026. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21027. // prepare the frustum in the local frame
  21028. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21029. _matrix$1
  21030. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21031. .multiply( this.matrixWorld );
  21032. _frustum.setFromProjectionMatrix(
  21033. _matrix$1,
  21034. camera.coordinateSystem,
  21035. camera.reversedDepth
  21036. );
  21037. }
  21038. let multiDrawCount = 0;
  21039. if ( this.sortObjects ) {
  21040. // get the camera position in the local frame
  21041. _matrix$1.copy( this.matrixWorld ).invert();
  21042. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21043. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21044. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21045. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21046. const geometryId = instanceInfo[ i ].geometryIndex;
  21047. // get the bounds in world space
  21048. this.getMatrixAt( i, _matrix$1 );
  21049. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21050. // determine whether the batched geometry is within the frustum
  21051. let culled = false;
  21052. if ( perObjectFrustumCulled ) {
  21053. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21054. }
  21055. if ( ! culled ) {
  21056. // get the distance from camera used for sorting
  21057. const geometryInfo = geometryInfoList[ geometryId ];
  21058. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21059. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21060. }
  21061. }
  21062. }
  21063. // Sort the draw ranges and prep for rendering
  21064. const list = _renderList.list;
  21065. const customSort = this.customSort;
  21066. if ( customSort === null ) {
  21067. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21068. } else {
  21069. customSort.call( this, list, camera );
  21070. }
  21071. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21072. const item = list[ i ];
  21073. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21074. multiDrawCounts[ multiDrawCount ] = item.count;
  21075. indirectArray[ multiDrawCount ] = item.index;
  21076. multiDrawCount ++;
  21077. }
  21078. _renderList.reset();
  21079. } else {
  21080. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21081. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21082. const geometryId = instanceInfo[ i ].geometryIndex;
  21083. // determine whether the batched geometry is within the frustum
  21084. let culled = false;
  21085. if ( perObjectFrustumCulled ) {
  21086. // get the bounds in world space
  21087. this.getMatrixAt( i, _matrix$1 );
  21088. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21089. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21090. }
  21091. if ( ! culled ) {
  21092. const geometryInfo = geometryInfoList[ geometryId ];
  21093. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21094. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21095. indirectArray[ multiDrawCount ] = i;
  21096. multiDrawCount ++;
  21097. }
  21098. }
  21099. }
  21100. }
  21101. indirectTexture.needsUpdate = true;
  21102. this._multiDrawCount = multiDrawCount;
  21103. this._visibilityChanged = false;
  21104. }
  21105. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21106. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21107. }
  21108. }
  21109. /**
  21110. * A material for rendering line primitives.
  21111. *
  21112. * Materials define the appearance of renderable 3D objects.
  21113. *
  21114. * ```js
  21115. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21116. * ```
  21117. *
  21118. * @augments Material
  21119. */
  21120. class LineBasicMaterial extends Material {
  21121. /**
  21122. * Constructs a new line basic material.
  21123. *
  21124. * @param {Object} [parameters] - An object with one or more properties
  21125. * defining the material's appearance. Any property of the material
  21126. * (including any property from inherited materials) can be passed
  21127. * in here. Color values can be passed any type of value accepted
  21128. * by {@link Color#set}.
  21129. */
  21130. constructor( parameters ) {
  21131. super();
  21132. /**
  21133. * This flag can be used for type testing.
  21134. *
  21135. * @type {boolean}
  21136. * @readonly
  21137. * @default true
  21138. */
  21139. this.isLineBasicMaterial = true;
  21140. this.type = 'LineBasicMaterial';
  21141. /**
  21142. * Color of the material.
  21143. *
  21144. * @type {Color}
  21145. * @default (1,1,1)
  21146. */
  21147. this.color = new Color( 0xffffff );
  21148. /**
  21149. * Sets the color of the lines using data from a texture. The texture map
  21150. * color is modulated by the diffuse `color`.
  21151. *
  21152. * @type {?Texture}
  21153. * @default null
  21154. */
  21155. this.map = null;
  21156. /**
  21157. * Controls line thickness or lines.
  21158. *
  21159. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21160. * ignore this setting and always render line primitives with a
  21161. * width of one pixel.
  21162. *
  21163. * @type {number}
  21164. * @default 1
  21165. */
  21166. this.linewidth = 1;
  21167. /**
  21168. * Defines appearance of line ends.
  21169. *
  21170. * Can only be used with {@link SVGRenderer}.
  21171. *
  21172. * @type {('butt'|'round'|'square')}
  21173. * @default 'round'
  21174. */
  21175. this.linecap = 'round';
  21176. /**
  21177. * Defines appearance of line joints.
  21178. *
  21179. * Can only be used with {@link SVGRenderer}.
  21180. *
  21181. * @type {('round'|'bevel'|'miter')}
  21182. * @default 'round'
  21183. */
  21184. this.linejoin = 'round';
  21185. /**
  21186. * Whether the material is affected by fog or not.
  21187. *
  21188. * @type {boolean}
  21189. * @default true
  21190. */
  21191. this.fog = true;
  21192. this.setValues( parameters );
  21193. }
  21194. copy( source ) {
  21195. super.copy( source );
  21196. this.color.copy( source.color );
  21197. this.map = source.map;
  21198. this.linewidth = source.linewidth;
  21199. this.linecap = source.linecap;
  21200. this.linejoin = source.linejoin;
  21201. this.fog = source.fog;
  21202. return this;
  21203. }
  21204. }
  21205. const _vStart = /*@__PURE__*/ new Vector3();
  21206. const _vEnd = /*@__PURE__*/ new Vector3();
  21207. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21208. const _ray$1 = /*@__PURE__*/ new Ray();
  21209. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21210. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21211. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21212. /**
  21213. * A continuous line. The line are rendered by connecting consecutive
  21214. * vertices with straight lines.
  21215. *
  21216. * ```js
  21217. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21218. *
  21219. * const points = [];
  21220. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21221. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21222. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21223. *
  21224. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21225. *
  21226. * const line = new THREE.Line( geometry, material );
  21227. * scene.add( line );
  21228. * ```
  21229. *
  21230. * @augments Object3D
  21231. */
  21232. class Line extends Object3D {
  21233. /**
  21234. * Constructs a new line.
  21235. *
  21236. * @param {BufferGeometry} [geometry] - The line geometry.
  21237. * @param {Material|Array<Material>} [material] - The line material.
  21238. */
  21239. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21240. super();
  21241. /**
  21242. * This flag can be used for type testing.
  21243. *
  21244. * @type {boolean}
  21245. * @readonly
  21246. * @default true
  21247. */
  21248. this.isLine = true;
  21249. this.type = 'Line';
  21250. /**
  21251. * The line geometry.
  21252. *
  21253. * @type {BufferGeometry}
  21254. */
  21255. this.geometry = geometry;
  21256. /**
  21257. * The line material.
  21258. *
  21259. * @type {Material|Array<Material>}
  21260. * @default LineBasicMaterial
  21261. */
  21262. this.material = material;
  21263. /**
  21264. * A dictionary representing the morph targets in the geometry. The key is the
  21265. * morph targets name, the value its attribute index. This member is `undefined`
  21266. * by default and only set when morph targets are detected in the geometry.
  21267. *
  21268. * @type {Object<string,number>|undefined}
  21269. * @default undefined
  21270. */
  21271. this.morphTargetDictionary = undefined;
  21272. /**
  21273. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21274. * is applied. This member is `undefined` by default and only set when morph targets are
  21275. * detected in the geometry.
  21276. *
  21277. * @type {Array<number>|undefined}
  21278. * @default undefined
  21279. */
  21280. this.morphTargetInfluences = undefined;
  21281. this.updateMorphTargets();
  21282. }
  21283. copy( source, recursive ) {
  21284. super.copy( source, recursive );
  21285. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21286. this.geometry = source.geometry;
  21287. return this;
  21288. }
  21289. /**
  21290. * Computes an array of distance values which are necessary for rendering dashed lines.
  21291. * For each vertex in the geometry, the method calculates the cumulative length from the
  21292. * current point to the very beginning of the line.
  21293. *
  21294. * @return {Line} A reference to this line.
  21295. */
  21296. computeLineDistances() {
  21297. const geometry = this.geometry;
  21298. // we assume non-indexed geometry
  21299. if ( geometry.index === null ) {
  21300. const positionAttribute = geometry.attributes.position;
  21301. const lineDistances = [ 0 ];
  21302. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21303. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21304. _vEnd.fromBufferAttribute( positionAttribute, i );
  21305. lineDistances[ i ] = lineDistances[ i - 1 ];
  21306. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21307. }
  21308. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21309. } else {
  21310. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21311. }
  21312. return this;
  21313. }
  21314. /**
  21315. * Computes intersection points between a casted ray and this line.
  21316. *
  21317. * @param {Raycaster} raycaster - The raycaster.
  21318. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21319. */
  21320. raycast( raycaster, intersects ) {
  21321. const geometry = this.geometry;
  21322. const matrixWorld = this.matrixWorld;
  21323. const threshold = raycaster.params.Line.threshold;
  21324. const drawRange = geometry.drawRange;
  21325. // Checking boundingSphere distance to ray
  21326. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21327. _sphere$1.copy( geometry.boundingSphere );
  21328. _sphere$1.applyMatrix4( matrixWorld );
  21329. _sphere$1.radius += threshold;
  21330. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21331. //
  21332. _inverseMatrix$1.copy( matrixWorld ).invert();
  21333. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21334. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21335. const localThresholdSq = localThreshold * localThreshold;
  21336. const step = this.isLineSegments ? 2 : 1;
  21337. const index = geometry.index;
  21338. const attributes = geometry.attributes;
  21339. const positionAttribute = attributes.position;
  21340. if ( index !== null ) {
  21341. const start = Math.max( 0, drawRange.start );
  21342. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21343. for ( let i = start, l = end - 1; i < l; i += step ) {
  21344. const a = index.getX( i );
  21345. const b = index.getX( i + 1 );
  21346. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21347. if ( intersect ) {
  21348. intersects.push( intersect );
  21349. }
  21350. }
  21351. if ( this.isLineLoop ) {
  21352. const a = index.getX( end - 1 );
  21353. const b = index.getX( start );
  21354. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21355. if ( intersect ) {
  21356. intersects.push( intersect );
  21357. }
  21358. }
  21359. } else {
  21360. const start = Math.max( 0, drawRange.start );
  21361. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21362. for ( let i = start, l = end - 1; i < l; i += step ) {
  21363. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21364. if ( intersect ) {
  21365. intersects.push( intersect );
  21366. }
  21367. }
  21368. if ( this.isLineLoop ) {
  21369. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21370. if ( intersect ) {
  21371. intersects.push( intersect );
  21372. }
  21373. }
  21374. }
  21375. }
  21376. /**
  21377. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21378. * to make sure existing morph targets can influence this 3D object.
  21379. */
  21380. updateMorphTargets() {
  21381. const geometry = this.geometry;
  21382. const morphAttributes = geometry.morphAttributes;
  21383. const keys = Object.keys( morphAttributes );
  21384. if ( keys.length > 0 ) {
  21385. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21386. if ( morphAttribute !== undefined ) {
  21387. this.morphTargetInfluences = [];
  21388. this.morphTargetDictionary = {};
  21389. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21390. const name = morphAttribute[ m ].name || String( m );
  21391. this.morphTargetInfluences.push( 0 );
  21392. this.morphTargetDictionary[ name ] = m;
  21393. }
  21394. }
  21395. }
  21396. }
  21397. }
  21398. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21399. const positionAttribute = object.geometry.attributes.position;
  21400. _vStart.fromBufferAttribute( positionAttribute, a );
  21401. _vEnd.fromBufferAttribute( positionAttribute, b );
  21402. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21403. if ( distSq > thresholdSq ) return;
  21404. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21405. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21406. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21407. return {
  21408. distance: distance,
  21409. // What do we want? intersection point on the ray or on the segment??
  21410. // point: raycaster.ray.at( distance ),
  21411. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21412. index: i,
  21413. face: null,
  21414. faceIndex: null,
  21415. barycoord: null,
  21416. object: object
  21417. };
  21418. }
  21419. const _start = /*@__PURE__*/ new Vector3();
  21420. const _end = /*@__PURE__*/ new Vector3();
  21421. /**
  21422. * A series of lines drawn between pairs of vertices.
  21423. *
  21424. * @augments Line
  21425. */
  21426. class LineSegments extends Line {
  21427. /**
  21428. * Constructs a new line segments.
  21429. *
  21430. * @param {BufferGeometry} [geometry] - The line geometry.
  21431. * @param {Material|Array<Material>} [material] - The line material.
  21432. */
  21433. constructor( geometry, material ) {
  21434. super( geometry, material );
  21435. /**
  21436. * This flag can be used for type testing.
  21437. *
  21438. * @type {boolean}
  21439. * @readonly
  21440. * @default true
  21441. */
  21442. this.isLineSegments = true;
  21443. this.type = 'LineSegments';
  21444. }
  21445. computeLineDistances() {
  21446. const geometry = this.geometry;
  21447. // we assume non-indexed geometry
  21448. if ( geometry.index === null ) {
  21449. const positionAttribute = geometry.attributes.position;
  21450. const lineDistances = [];
  21451. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21452. _start.fromBufferAttribute( positionAttribute, i );
  21453. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21454. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21455. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21456. }
  21457. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21458. } else {
  21459. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21460. }
  21461. return this;
  21462. }
  21463. }
  21464. /**
  21465. * A continuous line. This is nearly the same as {@link Line} the only difference
  21466. * is that the last vertex is connected with the first vertex in order to close
  21467. * the line to form a loop.
  21468. *
  21469. * @augments Line
  21470. */
  21471. class LineLoop extends Line {
  21472. /**
  21473. * Constructs a new line loop.
  21474. *
  21475. * @param {BufferGeometry} [geometry] - The line geometry.
  21476. * @param {Material|Array<Material>} [material] - The line material.
  21477. */
  21478. constructor( geometry, material ) {
  21479. super( geometry, material );
  21480. /**
  21481. * This flag can be used for type testing.
  21482. *
  21483. * @type {boolean}
  21484. * @readonly
  21485. * @default true
  21486. */
  21487. this.isLineLoop = true;
  21488. this.type = 'LineLoop';
  21489. }
  21490. }
  21491. /**
  21492. * A material for rendering point primitives.
  21493. *
  21494. * Materials define the appearance of renderable 3D objects.
  21495. *
  21496. * ```js
  21497. * const vertices = [];
  21498. *
  21499. * for ( let i = 0; i < 10000; i ++ ) {
  21500. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21501. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21502. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21503. *
  21504. * vertices.push( x, y, z );
  21505. * }
  21506. *
  21507. * const geometry = new THREE.BufferGeometry();
  21508. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21509. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21510. * const points = new THREE.Points( geometry, material );
  21511. * scene.add( points );
  21512. * ```
  21513. *
  21514. * @augments Material
  21515. */
  21516. class PointsMaterial extends Material {
  21517. /**
  21518. * Constructs a new points material.
  21519. *
  21520. * @param {Object} [parameters] - An object with one or more properties
  21521. * defining the material's appearance. Any property of the material
  21522. * (including any property from inherited materials) can be passed
  21523. * in here. Color values can be passed any type of value accepted
  21524. * by {@link Color#set}.
  21525. */
  21526. constructor( parameters ) {
  21527. super();
  21528. /**
  21529. * This flag can be used for type testing.
  21530. *
  21531. * @type {boolean}
  21532. * @readonly
  21533. * @default true
  21534. */
  21535. this.isPointsMaterial = true;
  21536. this.type = 'PointsMaterial';
  21537. /**
  21538. * Color of the material.
  21539. *
  21540. * @type {Color}
  21541. * @default (1,1,1)
  21542. */
  21543. this.color = new Color( 0xffffff );
  21544. /**
  21545. * The color map. May optionally include an alpha channel, typically combined
  21546. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21547. * color is modulated by the diffuse `color`.
  21548. *
  21549. * @type {?Texture}
  21550. * @default null
  21551. */
  21552. this.map = null;
  21553. /**
  21554. * The alpha map is a grayscale texture that controls the opacity across the
  21555. * surface (black: fully transparent; white: fully opaque).
  21556. *
  21557. * Only the color of the texture is used, ignoring the alpha channel if one
  21558. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21559. * when sampling this texture due to the extra bit of precision provided for
  21560. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21561. * luminance/alpha textures will also still work as expected.
  21562. *
  21563. * @type {?Texture}
  21564. * @default null
  21565. */
  21566. this.alphaMap = null;
  21567. /**
  21568. * Defines the size of the points in pixels.
  21569. *
  21570. * 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).
  21571. *
  21572. * @type {number}
  21573. * @default 1
  21574. */
  21575. this.size = 1;
  21576. /**
  21577. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21578. *
  21579. * @type {boolean}
  21580. * @default true
  21581. */
  21582. this.sizeAttenuation = true;
  21583. /**
  21584. * Whether the material is affected by fog or not.
  21585. *
  21586. * @type {boolean}
  21587. * @default true
  21588. */
  21589. this.fog = true;
  21590. this.setValues( parameters );
  21591. }
  21592. copy( source ) {
  21593. super.copy( source );
  21594. this.color.copy( source.color );
  21595. this.map = source.map;
  21596. this.alphaMap = source.alphaMap;
  21597. this.size = source.size;
  21598. this.sizeAttenuation = source.sizeAttenuation;
  21599. this.fog = source.fog;
  21600. return this;
  21601. }
  21602. }
  21603. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21604. const _ray = /*@__PURE__*/ new Ray();
  21605. const _sphere = /*@__PURE__*/ new Sphere();
  21606. const _position$2 = /*@__PURE__*/ new Vector3();
  21607. /**
  21608. * A class for displaying points or point clouds.
  21609. *
  21610. * @augments Object3D
  21611. */
  21612. class Points extends Object3D {
  21613. /**
  21614. * Constructs a new point cloud.
  21615. *
  21616. * @param {BufferGeometry} [geometry] - The points geometry.
  21617. * @param {Material|Array<Material>} [material] - The points material.
  21618. */
  21619. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21620. super();
  21621. /**
  21622. * This flag can be used for type testing.
  21623. *
  21624. * @type {boolean}
  21625. * @readonly
  21626. * @default true
  21627. */
  21628. this.isPoints = true;
  21629. this.type = 'Points';
  21630. /**
  21631. * The points geometry.
  21632. *
  21633. * @type {BufferGeometry}
  21634. */
  21635. this.geometry = geometry;
  21636. /**
  21637. * The line material.
  21638. *
  21639. * @type {Material|Array<Material>}
  21640. * @default PointsMaterial
  21641. */
  21642. this.material = material;
  21643. /**
  21644. * A dictionary representing the morph targets in the geometry. The key is the
  21645. * morph targets name, the value its attribute index. This member is `undefined`
  21646. * by default and only set when morph targets are detected in the geometry.
  21647. *
  21648. * @type {Object<string,number>|undefined}
  21649. * @default undefined
  21650. */
  21651. this.morphTargetDictionary = undefined;
  21652. /**
  21653. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21654. * is applied. This member is `undefined` by default and only set when morph targets are
  21655. * detected in the geometry.
  21656. *
  21657. * @type {Array<number>|undefined}
  21658. * @default undefined
  21659. */
  21660. this.morphTargetInfluences = undefined;
  21661. this.updateMorphTargets();
  21662. }
  21663. copy( source, recursive ) {
  21664. super.copy( source, recursive );
  21665. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21666. this.geometry = source.geometry;
  21667. return this;
  21668. }
  21669. /**
  21670. * Computes intersection points between a casted ray and this point cloud.
  21671. *
  21672. * @param {Raycaster} raycaster - The raycaster.
  21673. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21674. */
  21675. raycast( raycaster, intersects ) {
  21676. const geometry = this.geometry;
  21677. const matrixWorld = this.matrixWorld;
  21678. const threshold = raycaster.params.Points.threshold;
  21679. const drawRange = geometry.drawRange;
  21680. // Checking boundingSphere distance to ray
  21681. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21682. _sphere.copy( geometry.boundingSphere );
  21683. _sphere.applyMatrix4( matrixWorld );
  21684. _sphere.radius += threshold;
  21685. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21686. //
  21687. _inverseMatrix.copy( matrixWorld ).invert();
  21688. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21689. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21690. const localThresholdSq = localThreshold * localThreshold;
  21691. const index = geometry.index;
  21692. const attributes = geometry.attributes;
  21693. const positionAttribute = attributes.position;
  21694. if ( index !== null ) {
  21695. const start = Math.max( 0, drawRange.start );
  21696. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21697. for ( let i = start, il = end; i < il; i ++ ) {
  21698. const a = index.getX( i );
  21699. _position$2.fromBufferAttribute( positionAttribute, a );
  21700. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21701. }
  21702. } else {
  21703. const start = Math.max( 0, drawRange.start );
  21704. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21705. for ( let i = start, l = end; i < l; i ++ ) {
  21706. _position$2.fromBufferAttribute( positionAttribute, i );
  21707. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21708. }
  21709. }
  21710. }
  21711. /**
  21712. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21713. * to make sure existing morph targets can influence this 3D object.
  21714. */
  21715. updateMorphTargets() {
  21716. const geometry = this.geometry;
  21717. const morphAttributes = geometry.morphAttributes;
  21718. const keys = Object.keys( morphAttributes );
  21719. if ( keys.length > 0 ) {
  21720. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21721. if ( morphAttribute !== undefined ) {
  21722. this.morphTargetInfluences = [];
  21723. this.morphTargetDictionary = {};
  21724. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21725. const name = morphAttribute[ m ].name || String( m );
  21726. this.morphTargetInfluences.push( 0 );
  21727. this.morphTargetDictionary[ name ] = m;
  21728. }
  21729. }
  21730. }
  21731. }
  21732. }
  21733. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21734. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21735. if ( rayPointDistanceSq < localThresholdSq ) {
  21736. const intersectPoint = new Vector3();
  21737. _ray.closestPointToPoint( point, intersectPoint );
  21738. intersectPoint.applyMatrix4( matrixWorld );
  21739. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21740. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21741. intersects.push( {
  21742. distance: distance,
  21743. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21744. point: intersectPoint,
  21745. index: index,
  21746. face: null,
  21747. faceIndex: null,
  21748. barycoord: null,
  21749. object: object
  21750. } );
  21751. }
  21752. }
  21753. /**
  21754. * A texture for use with a video.
  21755. *
  21756. * ```js
  21757. * // assuming you have created a HTML video element with id="video"
  21758. * const video = document.getElementById( 'video' );
  21759. * const texture = new THREE.VideoTexture( video );
  21760. * ```
  21761. *
  21762. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21763. * set to THREE.SRGBColorSpace.
  21764. *
  21765. * Note: After the initial use of a texture, its dimensions, format, and type
  21766. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21767. *
  21768. * @augments Texture
  21769. */
  21770. class VideoTexture extends Texture {
  21771. /**
  21772. * Constructs a new video texture.
  21773. *
  21774. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21775. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21776. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21777. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21778. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21779. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21780. * @param {number} [format=RGBAFormat] - The texture format.
  21781. * @param {number} [type=UnsignedByteType] - The texture type.
  21782. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21783. */
  21784. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21785. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21786. /**
  21787. * This flag can be used for type testing.
  21788. *
  21789. * @type {boolean}
  21790. * @readonly
  21791. * @default true
  21792. */
  21793. this.isVideoTexture = true;
  21794. /**
  21795. * Whether to generate mipmaps (if possible) for a texture.
  21796. *
  21797. * Overwritten and set to `false` by default.
  21798. *
  21799. * @type {boolean}
  21800. * @default false
  21801. */
  21802. this.generateMipmaps = false;
  21803. /**
  21804. * The video frame request callback identifier, which is a positive integer.
  21805. *
  21806. * Value of 0 represents no scheduled rVFC.
  21807. *
  21808. * @private
  21809. * @type {number}
  21810. */
  21811. this._requestVideoFrameCallbackId = 0;
  21812. const scope = this;
  21813. function updateVideo() {
  21814. scope.needsUpdate = true;
  21815. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21816. }
  21817. if ( 'requestVideoFrameCallback' in video ) {
  21818. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21819. }
  21820. }
  21821. clone() {
  21822. return new this.constructor( this.image ).copy( this );
  21823. }
  21824. /**
  21825. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21826. * to `true` every time a new frame is available.
  21827. *
  21828. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21829. */
  21830. update() {
  21831. const video = this.image;
  21832. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21833. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21834. this.needsUpdate = true;
  21835. }
  21836. }
  21837. dispose() {
  21838. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21839. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21840. this._requestVideoFrameCallbackId = 0;
  21841. }
  21842. super.dispose();
  21843. }
  21844. }
  21845. /**
  21846. * This class can be used as an alternative way to define video data. Instead of using
  21847. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21848. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21849. * video frames are decoded with the WebCodecs API.
  21850. *
  21851. * ```js
  21852. * const texture = new THREE.VideoFrameTexture();
  21853. * texture.setFrame( frame );
  21854. * ```
  21855. *
  21856. * @augments VideoTexture
  21857. */
  21858. class VideoFrameTexture extends VideoTexture {
  21859. /**
  21860. * Constructs a new video frame texture.
  21861. *
  21862. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21863. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21864. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21865. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21866. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21867. * @param {number} [format=RGBAFormat] - The texture format.
  21868. * @param {number} [type=UnsignedByteType] - The texture type.
  21869. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21870. */
  21871. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21872. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21873. /**
  21874. * This flag can be used for type testing.
  21875. *
  21876. * @type {boolean}
  21877. * @readonly
  21878. * @default true
  21879. */
  21880. this.isVideoFrameTexture = true;
  21881. }
  21882. /**
  21883. * This method overwritten with an empty implementation since
  21884. * this type of texture is updated via `setFrame()`.
  21885. */
  21886. update() {}
  21887. clone() {
  21888. return new this.constructor().copy( this ); // restoring Texture.clone()
  21889. }
  21890. /**
  21891. * Sets the current frame of the video. This will automatically update the texture
  21892. * so the data can be used for rendering.
  21893. *
  21894. * @param {VideoFrame} frame - The video frame.
  21895. */
  21896. setFrame( frame ) {
  21897. this.image = frame;
  21898. this.needsUpdate = true;
  21899. }
  21900. }
  21901. /**
  21902. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21903. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21904. * as a texture for further usage.
  21905. *
  21906. * ```js
  21907. * const pixelRatio = window.devicePixelRatio;
  21908. * const textureSize = 128 * pixelRatio;
  21909. *
  21910. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21911. *
  21912. * // calculate start position for copying part of the frame data
  21913. * const vector = new Vector2();
  21914. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21915. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21916. *
  21917. * renderer.render( scene, camera );
  21918. *
  21919. * // copy part of the rendered frame into the framebuffer texture
  21920. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21921. * ```
  21922. *
  21923. * @augments Texture
  21924. */
  21925. class FramebufferTexture extends Texture {
  21926. /**
  21927. * Constructs a new framebuffer texture.
  21928. *
  21929. * @param {number} [width] - The width of the texture.
  21930. * @param {number} [height] - The height of the texture.
  21931. */
  21932. constructor( width, height ) {
  21933. super( { width, height } );
  21934. /**
  21935. * This flag can be used for type testing.
  21936. *
  21937. * @type {boolean}
  21938. * @readonly
  21939. * @default true
  21940. */
  21941. this.isFramebufferTexture = true;
  21942. /**
  21943. * How the texture is sampled when a texel covers more than one pixel.
  21944. *
  21945. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21946. *
  21947. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21948. * @default NearestFilter
  21949. */
  21950. this.magFilter = NearestFilter;
  21951. /**
  21952. * How the texture is sampled when a texel covers less than one pixel.
  21953. *
  21954. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21955. *
  21956. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21957. * @default NearestFilter
  21958. */
  21959. this.minFilter = NearestFilter;
  21960. /**
  21961. * Whether to generate mipmaps (if possible) for a texture.
  21962. *
  21963. * Overwritten and set to `false` by default.
  21964. *
  21965. * @type {boolean}
  21966. * @default false
  21967. */
  21968. this.generateMipmaps = false;
  21969. this.needsUpdate = true;
  21970. }
  21971. }
  21972. /**
  21973. * Creates a texture based on data in compressed form.
  21974. *
  21975. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21976. *
  21977. * @augments Texture
  21978. */
  21979. class CompressedTexture extends Texture {
  21980. /**
  21981. * Constructs a new compressed texture.
  21982. *
  21983. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21984. * the data and dimensions.
  21985. * @param {number} width - The width of the texture.
  21986. * @param {number} height - The height of the texture.
  21987. * @param {number} [format=RGBAFormat] - The texture format.
  21988. * @param {number} [type=UnsignedByteType] - The texture type.
  21989. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21990. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21991. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21992. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21993. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21994. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21995. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21996. */
  21997. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21998. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21999. /**
  22000. * This flag can be used for type testing.
  22001. *
  22002. * @type {boolean}
  22003. * @readonly
  22004. * @default true
  22005. */
  22006. this.isCompressedTexture = true;
  22007. /**
  22008. * The image property of a compressed texture just defines its dimensions.
  22009. *
  22010. * @type {{width:number,height:number}}
  22011. */
  22012. this.image = { width: width, height: height };
  22013. /**
  22014. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22015. *
  22016. * @type {Array<Object>}
  22017. */
  22018. this.mipmaps = mipmaps;
  22019. /**
  22020. * If set to `true`, the texture is flipped along the vertical axis when
  22021. * uploaded to the GPU.
  22022. *
  22023. * Overwritten and set to `false` by default since it is not possible to
  22024. * flip compressed textures.
  22025. *
  22026. * @type {boolean}
  22027. * @default false
  22028. * @readonly
  22029. */
  22030. this.flipY = false;
  22031. /**
  22032. * Whether to generate mipmaps (if possible) for a texture.
  22033. *
  22034. * Overwritten and set to `false` by default since it is not
  22035. * possible to generate mipmaps for compressed data. Mipmaps
  22036. * must be embedded in the compressed texture file.
  22037. *
  22038. * @type {boolean}
  22039. * @default false
  22040. * @readonly
  22041. */
  22042. this.generateMipmaps = false;
  22043. }
  22044. }
  22045. /**
  22046. * Creates a texture 2D array based on data in compressed form.
  22047. *
  22048. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22049. *
  22050. * @augments CompressedTexture
  22051. */
  22052. class CompressedArrayTexture extends CompressedTexture {
  22053. /**
  22054. * Constructs a new compressed array texture.
  22055. *
  22056. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22057. * the data and dimensions.
  22058. * @param {number} width - The width of the texture.
  22059. * @param {number} height - The height of the texture.
  22060. * @param {number} depth - The depth of the texture.
  22061. * @param {number} [format=RGBAFormat] - The min filter value.
  22062. * @param {number} [type=UnsignedByteType] - The min filter value.
  22063. */
  22064. constructor( mipmaps, width, height, depth, format, type ) {
  22065. super( mipmaps, width, height, format, type );
  22066. /**
  22067. * This flag can be used for type testing.
  22068. *
  22069. * @type {boolean}
  22070. * @readonly
  22071. * @default true
  22072. */
  22073. this.isCompressedArrayTexture = true;
  22074. /**
  22075. * The image property of a compressed texture just defines its dimensions.
  22076. *
  22077. * @name CompressedArrayTexture#image
  22078. * @type {{width:number,height:number,depth:number}}
  22079. */
  22080. this.image.depth = depth;
  22081. /**
  22082. * This defines how the texture is wrapped in the depth and corresponds to
  22083. * *W* in UVW mapping.
  22084. *
  22085. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22086. * @default ClampToEdgeWrapping
  22087. */
  22088. this.wrapR = ClampToEdgeWrapping;
  22089. /**
  22090. * A set of all layers which need to be updated in the texture.
  22091. *
  22092. * @type {Set<number>}
  22093. */
  22094. this.layerUpdates = new Set();
  22095. }
  22096. /**
  22097. * Describes that a specific layer of the texture needs to be updated.
  22098. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22099. * entire compressed texture array is sent to the GPU. Marking specific
  22100. * layers will only transmit subsets of all mipmaps associated with a
  22101. * specific depth in the array which is often much more performant.
  22102. *
  22103. * @param {number} layerIndex - The layer index that should be updated.
  22104. */
  22105. addLayerUpdate( layerIndex ) {
  22106. this.layerUpdates.add( layerIndex );
  22107. }
  22108. /**
  22109. * Resets the layer updates registry.
  22110. */
  22111. clearLayerUpdates() {
  22112. this.layerUpdates.clear();
  22113. }
  22114. }
  22115. /**
  22116. * Creates a cube texture based on data in compressed form.
  22117. *
  22118. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22119. *
  22120. * @augments CompressedTexture
  22121. */
  22122. class CompressedCubeTexture extends CompressedTexture {
  22123. /**
  22124. * Constructs a new compressed texture.
  22125. *
  22126. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22127. * @param {number} [format=RGBAFormat] - The texture format.
  22128. * @param {number} [type=UnsignedByteType] - The texture type.
  22129. */
  22130. constructor( images, format, type ) {
  22131. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22132. /**
  22133. * This flag can be used for type testing.
  22134. *
  22135. * @type {boolean}
  22136. * @readonly
  22137. * @default true
  22138. */
  22139. this.isCompressedCubeTexture = true;
  22140. /**
  22141. * This flag can be used for type testing.
  22142. *
  22143. * @type {boolean}
  22144. * @readonly
  22145. * @default true
  22146. */
  22147. this.isCubeTexture = true;
  22148. this.image = images;
  22149. }
  22150. }
  22151. /**
  22152. * Creates a texture from a canvas element.
  22153. *
  22154. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22155. * to `true` immediately since a canvas can directly be used for rendering.
  22156. *
  22157. * @augments Texture
  22158. */
  22159. class CanvasTexture extends Texture {
  22160. /**
  22161. * Constructs a new texture.
  22162. *
  22163. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22164. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22165. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22166. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22167. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22168. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22169. * @param {number} [format=RGBAFormat] - The texture format.
  22170. * @param {number} [type=UnsignedByteType] - The texture type.
  22171. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22172. */
  22173. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22174. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22175. /**
  22176. * This flag can be used for type testing.
  22177. *
  22178. * @type {boolean}
  22179. * @readonly
  22180. * @default true
  22181. */
  22182. this.isCanvasTexture = true;
  22183. this.needsUpdate = true;
  22184. }
  22185. }
  22186. /**
  22187. * This class can be used to automatically save the depth information of a
  22188. * rendering into a texture.
  22189. *
  22190. * @augments Texture
  22191. */
  22192. class DepthTexture extends Texture {
  22193. /**
  22194. * Constructs a new depth texture.
  22195. *
  22196. * @param {number} width - The width of the texture.
  22197. * @param {number} height - The height of the texture.
  22198. * @param {number} [type=UnsignedIntType] - The texture type.
  22199. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22200. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22201. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22202. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22203. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22204. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22205. * @param {number} [format=DepthFormat] - The texture format.
  22206. * @param {number} [depth=1] - The depth of the texture.
  22207. */
  22208. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22209. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22210. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22211. }
  22212. const image = { width: width, height: height, depth: depth };
  22213. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22214. /**
  22215. * This flag can be used for type testing.
  22216. *
  22217. * @type {boolean}
  22218. * @readonly
  22219. * @default true
  22220. */
  22221. this.isDepthTexture = true;
  22222. /**
  22223. * If set to `true`, the texture is flipped along the vertical axis when
  22224. * uploaded to the GPU.
  22225. *
  22226. * Overwritten and set to `false` by default.
  22227. *
  22228. * @type {boolean}
  22229. * @default false
  22230. */
  22231. this.flipY = false;
  22232. /**
  22233. * Whether to generate mipmaps (if possible) for a texture.
  22234. *
  22235. * Overwritten and set to `false` by default.
  22236. *
  22237. * @type {boolean}
  22238. * @default false
  22239. */
  22240. this.generateMipmaps = false;
  22241. /**
  22242. * Code corresponding to the depth compare function.
  22243. *
  22244. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22245. * @default null
  22246. */
  22247. this.compareFunction = null;
  22248. }
  22249. copy( source ) {
  22250. super.copy( source );
  22251. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22252. this.compareFunction = source.compareFunction;
  22253. return this;
  22254. }
  22255. toJSON( meta ) {
  22256. const data = super.toJSON( meta );
  22257. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22258. return data;
  22259. }
  22260. }
  22261. /**
  22262. * This class can be used to automatically save the depth information of a
  22263. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22264. *
  22265. * @augments DepthTexture
  22266. */
  22267. class CubeDepthTexture extends DepthTexture {
  22268. /**
  22269. * Constructs a new cube depth texture.
  22270. *
  22271. * @param {number} size - The size (width and height) of each cube face.
  22272. * @param {number} [type=UnsignedIntType] - The texture type.
  22273. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22274. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22275. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22276. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22277. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22278. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22279. * @param {number} [format=DepthFormat] - The texture format.
  22280. */
  22281. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22282. // Create 6 identical image descriptors for the cube faces
  22283. const image = { width: size, height: size, depth: 1 };
  22284. const images = [ image, image, image, image, image, image ];
  22285. // Call DepthTexture constructor with width, height
  22286. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22287. // Replace the single image with the array of 6 images
  22288. this.image = images;
  22289. /**
  22290. * This flag can be used for type testing.
  22291. *
  22292. * @type {boolean}
  22293. * @readonly
  22294. * @default true
  22295. */
  22296. this.isCubeDepthTexture = true;
  22297. /**
  22298. * Set to true for cube texture handling in WebGLTextures.
  22299. *
  22300. * @type {boolean}
  22301. * @readonly
  22302. * @default true
  22303. */
  22304. this.isCubeTexture = true;
  22305. }
  22306. /**
  22307. * Alias for {@link CubeDepthTexture#image}.
  22308. *
  22309. * @type {Array<Image>}
  22310. */
  22311. get images() {
  22312. return this.image;
  22313. }
  22314. set images( value ) {
  22315. this.image = value;
  22316. }
  22317. }
  22318. /**
  22319. * Represents a texture created externally with the same renderer context.
  22320. *
  22321. * This may be a texture from a protected media stream, device camera feed,
  22322. * or other data feeds like a depth sensor.
  22323. *
  22324. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22325. * the {@link WebGPURenderer} WebGPU backend.
  22326. *
  22327. * @augments Texture
  22328. */
  22329. class ExternalTexture extends Texture {
  22330. /**
  22331. * Creates a new raw texture.
  22332. *
  22333. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22334. */
  22335. constructor( sourceTexture = null ) {
  22336. super();
  22337. /**
  22338. * The external source texture.
  22339. *
  22340. * @type {?(WebGLTexture|GPUTexture)}
  22341. * @default null
  22342. */
  22343. this.sourceTexture = sourceTexture;
  22344. /**
  22345. * This flag can be used for type testing.
  22346. *
  22347. * @type {boolean}
  22348. * @readonly
  22349. * @default true
  22350. */
  22351. this.isExternalTexture = true;
  22352. }
  22353. copy( source ) {
  22354. super.copy( source );
  22355. this.sourceTexture = source.sourceTexture;
  22356. return this;
  22357. }
  22358. }
  22359. /**
  22360. * A geometry class for representing a capsule.
  22361. *
  22362. * ```js
  22363. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22364. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22365. * const capsule = new THREE.Mesh( geometry, material );
  22366. * scene.add( capsule );
  22367. * ```
  22368. *
  22369. * @augments BufferGeometry
  22370. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22371. */
  22372. class CapsuleGeometry extends BufferGeometry {
  22373. /**
  22374. * Constructs a new capsule geometry.
  22375. *
  22376. * @param {number} [radius=1] - Radius of the capsule.
  22377. * @param {number} [height=1] - Height of the middle section.
  22378. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22379. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22380. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22381. */
  22382. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22383. super();
  22384. this.type = 'CapsuleGeometry';
  22385. /**
  22386. * Holds the constructor parameters that have been
  22387. * used to generate the geometry. Any modification
  22388. * after instantiation does not change the geometry.
  22389. *
  22390. * @type {Object}
  22391. */
  22392. this.parameters = {
  22393. radius: radius,
  22394. height: height,
  22395. capSegments: capSegments,
  22396. radialSegments: radialSegments,
  22397. heightSegments: heightSegments,
  22398. };
  22399. height = Math.max( 0, height );
  22400. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22401. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22402. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22403. // buffers
  22404. const indices = [];
  22405. const vertices = [];
  22406. const normals = [];
  22407. const uvs = [];
  22408. // helper variables
  22409. const halfHeight = height / 2;
  22410. const capArcLength = ( Math.PI / 2 ) * radius;
  22411. const cylinderPartLength = height;
  22412. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22413. const numVerticalSegments = capSegments * 2 + heightSegments;
  22414. const verticesPerRow = radialSegments + 1;
  22415. const normal = new Vector3();
  22416. const vertex = new Vector3();
  22417. // generate vertices, normals, and uvs
  22418. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22419. let currentArcLength = 0;
  22420. let profileY = 0;
  22421. let profileRadius = 0;
  22422. let normalYComponent = 0;
  22423. if ( iy <= capSegments ) {
  22424. // bottom cap
  22425. const segmentProgress = iy / capSegments;
  22426. const angle = ( segmentProgress * Math.PI ) / 2;
  22427. profileY = - halfHeight - radius * Math.cos( angle );
  22428. profileRadius = radius * Math.sin( angle );
  22429. normalYComponent = - radius * Math.cos( angle );
  22430. currentArcLength = segmentProgress * capArcLength;
  22431. } else if ( iy <= capSegments + heightSegments ) {
  22432. // middle section
  22433. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22434. profileY = - halfHeight + segmentProgress * height;
  22435. profileRadius = radius;
  22436. normalYComponent = 0;
  22437. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22438. } else {
  22439. // top cap
  22440. const segmentProgress =
  22441. ( iy - capSegments - heightSegments ) / capSegments;
  22442. const angle = ( segmentProgress * Math.PI ) / 2;
  22443. profileY = halfHeight + radius * Math.sin( angle );
  22444. profileRadius = radius * Math.cos( angle );
  22445. normalYComponent = radius * Math.sin( angle );
  22446. currentArcLength =
  22447. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22448. }
  22449. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22450. // special case for the poles
  22451. let uOffset = 0;
  22452. if ( iy === 0 ) {
  22453. uOffset = 0.5 / radialSegments;
  22454. } else if ( iy === numVerticalSegments ) {
  22455. uOffset = -0.5 / radialSegments;
  22456. }
  22457. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22458. const u = ix / radialSegments;
  22459. const theta = u * Math.PI * 2;
  22460. const sinTheta = Math.sin( theta );
  22461. const cosTheta = Math.cos( theta );
  22462. // vertex
  22463. vertex.x = - profileRadius * cosTheta;
  22464. vertex.y = profileY;
  22465. vertex.z = profileRadius * sinTheta;
  22466. vertices.push( vertex.x, vertex.y, vertex.z );
  22467. // normal
  22468. normal.set(
  22469. - profileRadius * cosTheta,
  22470. normalYComponent,
  22471. profileRadius * sinTheta
  22472. );
  22473. normal.normalize();
  22474. normals.push( normal.x, normal.y, normal.z );
  22475. // uv
  22476. uvs.push( u + uOffset, v );
  22477. }
  22478. if ( iy > 0 ) {
  22479. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22480. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22481. const i1 = prevIndexRow + ix;
  22482. const i2 = prevIndexRow + ix + 1;
  22483. const i3 = iy * verticesPerRow + ix;
  22484. const i4 = iy * verticesPerRow + ix + 1;
  22485. indices.push( i1, i2, i3 );
  22486. indices.push( i2, i4, i3 );
  22487. }
  22488. }
  22489. }
  22490. // build geometry
  22491. this.setIndex( indices );
  22492. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22493. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22494. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22495. }
  22496. copy( source ) {
  22497. super.copy( source );
  22498. this.parameters = Object.assign( {}, source.parameters );
  22499. return this;
  22500. }
  22501. /**
  22502. * Factory method for creating an instance of this class from the given
  22503. * JSON object.
  22504. *
  22505. * @param {Object} data - A JSON object representing the serialized geometry.
  22506. * @return {CapsuleGeometry} A new instance.
  22507. */
  22508. static fromJSON( data ) {
  22509. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22510. }
  22511. }
  22512. /**
  22513. * A simple shape of Euclidean geometry. It is constructed from a
  22514. * number of triangular segments that are oriented around a central point and
  22515. * extend as far out as a given radius. It is built counter-clockwise from a
  22516. * start angle and a given central angle. It can also be used to create
  22517. * regular polygons, where the number of segments determines the number of
  22518. * sides.
  22519. *
  22520. * ```js
  22521. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22522. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22523. * const circle = new THREE.Mesh( geometry, material );
  22524. * scene.add( circle )
  22525. * ```
  22526. *
  22527. * @augments BufferGeometry
  22528. * @demo scenes/geometry-browser.html#CircleGeometry
  22529. */
  22530. class CircleGeometry extends BufferGeometry {
  22531. /**
  22532. * Constructs a new circle geometry.
  22533. *
  22534. * @param {number} [radius=1] - Radius of the circle.
  22535. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22536. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22537. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22538. * of the circular sector in radians. The default value results in a complete circle.
  22539. */
  22540. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22541. super();
  22542. this.type = 'CircleGeometry';
  22543. /**
  22544. * Holds the constructor parameters that have been
  22545. * used to generate the geometry. Any modification
  22546. * after instantiation does not change the geometry.
  22547. *
  22548. * @type {Object}
  22549. */
  22550. this.parameters = {
  22551. radius: radius,
  22552. segments: segments,
  22553. thetaStart: thetaStart,
  22554. thetaLength: thetaLength
  22555. };
  22556. segments = Math.max( 3, segments );
  22557. // buffers
  22558. const indices = [];
  22559. const vertices = [];
  22560. const normals = [];
  22561. const uvs = [];
  22562. // helper variables
  22563. const vertex = new Vector3();
  22564. const uv = new Vector2();
  22565. // center point
  22566. vertices.push( 0, 0, 0 );
  22567. normals.push( 0, 0, 1 );
  22568. uvs.push( 0.5, 0.5 );
  22569. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22570. const segment = thetaStart + s / segments * thetaLength;
  22571. // vertex
  22572. vertex.x = radius * Math.cos( segment );
  22573. vertex.y = radius * Math.sin( segment );
  22574. vertices.push( vertex.x, vertex.y, vertex.z );
  22575. // normal
  22576. normals.push( 0, 0, 1 );
  22577. // uvs
  22578. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22579. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22580. uvs.push( uv.x, uv.y );
  22581. }
  22582. // indices
  22583. for ( let i = 1; i <= segments; i ++ ) {
  22584. indices.push( i, i + 1, 0 );
  22585. }
  22586. // build geometry
  22587. this.setIndex( indices );
  22588. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22589. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22590. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22591. }
  22592. copy( source ) {
  22593. super.copy( source );
  22594. this.parameters = Object.assign( {}, source.parameters );
  22595. return this;
  22596. }
  22597. /**
  22598. * Factory method for creating an instance of this class from the given
  22599. * JSON object.
  22600. *
  22601. * @param {Object} data - A JSON object representing the serialized geometry.
  22602. * @return {CircleGeometry} A new instance.
  22603. */
  22604. static fromJSON( data ) {
  22605. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22606. }
  22607. }
  22608. /**
  22609. * A geometry class for representing a cylinder.
  22610. *
  22611. * ```js
  22612. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22613. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22614. * const cylinder = new THREE.Mesh( geometry, material );
  22615. * scene.add( cylinder );
  22616. * ```
  22617. *
  22618. * @augments BufferGeometry
  22619. * @demo scenes/geometry-browser.html#CylinderGeometry
  22620. */
  22621. class CylinderGeometry extends BufferGeometry {
  22622. /**
  22623. * Constructs a new cylinder geometry.
  22624. *
  22625. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22626. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22627. * @param {number} [height=1] - Height of the cylinder.
  22628. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22629. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22630. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22631. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22632. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22633. * The default value results in a complete cylinder.
  22634. */
  22635. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22636. super();
  22637. this.type = 'CylinderGeometry';
  22638. /**
  22639. * Holds the constructor parameters that have been
  22640. * used to generate the geometry. Any modification
  22641. * after instantiation does not change the geometry.
  22642. *
  22643. * @type {Object}
  22644. */
  22645. this.parameters = {
  22646. radiusTop: radiusTop,
  22647. radiusBottom: radiusBottom,
  22648. height: height,
  22649. radialSegments: radialSegments,
  22650. heightSegments: heightSegments,
  22651. openEnded: openEnded,
  22652. thetaStart: thetaStart,
  22653. thetaLength: thetaLength
  22654. };
  22655. const scope = this;
  22656. radialSegments = Math.floor( radialSegments );
  22657. heightSegments = Math.floor( heightSegments );
  22658. // buffers
  22659. const indices = [];
  22660. const vertices = [];
  22661. const normals = [];
  22662. const uvs = [];
  22663. // helper variables
  22664. let index = 0;
  22665. const indexArray = [];
  22666. const halfHeight = height / 2;
  22667. let groupStart = 0;
  22668. // generate geometry
  22669. generateTorso();
  22670. if ( openEnded === false ) {
  22671. if ( radiusTop > 0 ) generateCap( true );
  22672. if ( radiusBottom > 0 ) generateCap( false );
  22673. }
  22674. // build geometry
  22675. this.setIndex( indices );
  22676. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22677. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22678. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22679. function generateTorso() {
  22680. const normal = new Vector3();
  22681. const vertex = new Vector3();
  22682. let groupCount = 0;
  22683. // this will be used to calculate the normal
  22684. const slope = ( radiusBottom - radiusTop ) / height;
  22685. // generate vertices, normals and uvs
  22686. for ( let y = 0; y <= heightSegments; y ++ ) {
  22687. const indexRow = [];
  22688. const v = y / heightSegments;
  22689. // calculate the radius of the current row
  22690. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22691. for ( let x = 0; x <= radialSegments; x ++ ) {
  22692. const u = x / radialSegments;
  22693. const theta = u * thetaLength + thetaStart;
  22694. const sinTheta = Math.sin( theta );
  22695. const cosTheta = Math.cos( theta );
  22696. // vertex
  22697. vertex.x = radius * sinTheta;
  22698. vertex.y = - v * height + halfHeight;
  22699. vertex.z = radius * cosTheta;
  22700. vertices.push( vertex.x, vertex.y, vertex.z );
  22701. // normal
  22702. normal.set( sinTheta, slope, cosTheta ).normalize();
  22703. normals.push( normal.x, normal.y, normal.z );
  22704. // uv
  22705. uvs.push( u, 1 - v );
  22706. // save index of vertex in respective row
  22707. indexRow.push( index ++ );
  22708. }
  22709. // now save vertices of the row in our index array
  22710. indexArray.push( indexRow );
  22711. }
  22712. // generate indices
  22713. for ( let x = 0; x < radialSegments; x ++ ) {
  22714. for ( let y = 0; y < heightSegments; y ++ ) {
  22715. // we use the index array to access the correct indices
  22716. const a = indexArray[ y ][ x ];
  22717. const b = indexArray[ y + 1 ][ x ];
  22718. const c = indexArray[ y + 1 ][ x + 1 ];
  22719. const d = indexArray[ y ][ x + 1 ];
  22720. // faces
  22721. if ( radiusTop > 0 || y !== 0 ) {
  22722. indices.push( a, b, d );
  22723. groupCount += 3;
  22724. }
  22725. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22726. indices.push( b, c, d );
  22727. groupCount += 3;
  22728. }
  22729. }
  22730. }
  22731. // add a group to the geometry. this will ensure multi material support
  22732. scope.addGroup( groupStart, groupCount, 0 );
  22733. // calculate new start value for groups
  22734. groupStart += groupCount;
  22735. }
  22736. function generateCap( top ) {
  22737. // save the index of the first center vertex
  22738. const centerIndexStart = index;
  22739. const uv = new Vector2();
  22740. const vertex = new Vector3();
  22741. let groupCount = 0;
  22742. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22743. const sign = ( top === true ) ? 1 : -1;
  22744. // first we generate the center vertex data of the cap.
  22745. // because the geometry needs one set of uvs per face,
  22746. // we must generate a center vertex per face/segment
  22747. for ( let x = 1; x <= radialSegments; x ++ ) {
  22748. // vertex
  22749. vertices.push( 0, halfHeight * sign, 0 );
  22750. // normal
  22751. normals.push( 0, sign, 0 );
  22752. // uv
  22753. uvs.push( 0.5, 0.5 );
  22754. // increase index
  22755. index ++;
  22756. }
  22757. // save the index of the last center vertex
  22758. const centerIndexEnd = index;
  22759. // now we generate the surrounding vertices, normals and uvs
  22760. for ( let x = 0; x <= radialSegments; x ++ ) {
  22761. const u = x / radialSegments;
  22762. const theta = u * thetaLength + thetaStart;
  22763. const cosTheta = Math.cos( theta );
  22764. const sinTheta = Math.sin( theta );
  22765. // vertex
  22766. vertex.x = radius * sinTheta;
  22767. vertex.y = halfHeight * sign;
  22768. vertex.z = radius * cosTheta;
  22769. vertices.push( vertex.x, vertex.y, vertex.z );
  22770. // normal
  22771. normals.push( 0, sign, 0 );
  22772. // uv
  22773. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22774. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22775. uvs.push( uv.x, uv.y );
  22776. // increase index
  22777. index ++;
  22778. }
  22779. // generate indices
  22780. for ( let x = 0; x < radialSegments; x ++ ) {
  22781. const c = centerIndexStart + x;
  22782. const i = centerIndexEnd + x;
  22783. if ( top === true ) {
  22784. // face top
  22785. indices.push( i, i + 1, c );
  22786. } else {
  22787. // face bottom
  22788. indices.push( i + 1, i, c );
  22789. }
  22790. groupCount += 3;
  22791. }
  22792. // add a group to the geometry. this will ensure multi material support
  22793. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22794. // calculate new start value for groups
  22795. groupStart += groupCount;
  22796. }
  22797. }
  22798. copy( source ) {
  22799. super.copy( source );
  22800. this.parameters = Object.assign( {}, source.parameters );
  22801. return this;
  22802. }
  22803. /**
  22804. * Factory method for creating an instance of this class from the given
  22805. * JSON object.
  22806. *
  22807. * @param {Object} data - A JSON object representing the serialized geometry.
  22808. * @return {CylinderGeometry} A new instance.
  22809. */
  22810. static fromJSON( data ) {
  22811. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22812. }
  22813. }
  22814. /**
  22815. * A geometry class for representing a cone.
  22816. *
  22817. * ```js
  22818. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22819. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22820. * const cone = new THREE.Mesh(geometry, material );
  22821. * scene.add( cone );
  22822. * ```
  22823. *
  22824. * @augments CylinderGeometry
  22825. * @demo scenes/geometry-browser.html#ConeGeometry
  22826. */
  22827. class ConeGeometry extends CylinderGeometry {
  22828. /**
  22829. * Constructs a new cone geometry.
  22830. *
  22831. * @param {number} [radius=1] - Radius of the cone base.
  22832. * @param {number} [height=1] - Height of the cone.
  22833. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22834. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22835. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22836. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22837. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22838. * The default value results in a complete cone.
  22839. */
  22840. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22841. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22842. this.type = 'ConeGeometry';
  22843. /**
  22844. * Holds the constructor parameters that have been
  22845. * used to generate the geometry. Any modification
  22846. * after instantiation does not change the geometry.
  22847. *
  22848. * @type {Object}
  22849. */
  22850. this.parameters = {
  22851. radius: radius,
  22852. height: height,
  22853. radialSegments: radialSegments,
  22854. heightSegments: heightSegments,
  22855. openEnded: openEnded,
  22856. thetaStart: thetaStart,
  22857. thetaLength: thetaLength
  22858. };
  22859. }
  22860. /**
  22861. * Factory method for creating an instance of this class from the given
  22862. * JSON object.
  22863. *
  22864. * @param {Object} data - A JSON object representing the serialized geometry.
  22865. * @return {ConeGeometry} A new instance.
  22866. */
  22867. static fromJSON( data ) {
  22868. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22869. }
  22870. }
  22871. /**
  22872. * A polyhedron is a solid in three dimensions with flat faces. This class
  22873. * will take an array of vertices, project them onto a sphere, and then
  22874. * divide them up to the desired level of detail.
  22875. *
  22876. * @augments BufferGeometry
  22877. */
  22878. class PolyhedronGeometry extends BufferGeometry {
  22879. /**
  22880. * Constructs a new polyhedron geometry.
  22881. *
  22882. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22883. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22884. * @param {number} [radius=1] - The radius of the shape.
  22885. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22886. */
  22887. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22888. super();
  22889. this.type = 'PolyhedronGeometry';
  22890. /**
  22891. * Holds the constructor parameters that have been
  22892. * used to generate the geometry. Any modification
  22893. * after instantiation does not change the geometry.
  22894. *
  22895. * @type {Object}
  22896. */
  22897. this.parameters = {
  22898. vertices: vertices,
  22899. indices: indices,
  22900. radius: radius,
  22901. detail: detail
  22902. };
  22903. // default buffer data
  22904. const vertexBuffer = [];
  22905. const uvBuffer = [];
  22906. // the subdivision creates the vertex buffer data
  22907. subdivide( detail );
  22908. // all vertices should lie on a conceptual sphere with a given radius
  22909. applyRadius( radius );
  22910. // finally, create the uv data
  22911. generateUVs();
  22912. // build non-indexed geometry
  22913. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22914. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22915. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22916. if ( detail === 0 ) {
  22917. this.computeVertexNormals(); // flat normals
  22918. } else {
  22919. this.normalizeNormals(); // smooth normals
  22920. }
  22921. // helper functions
  22922. function subdivide( detail ) {
  22923. const a = new Vector3();
  22924. const b = new Vector3();
  22925. const c = new Vector3();
  22926. // iterate over all faces and apply a subdivision with the given detail value
  22927. for ( let i = 0; i < indices.length; i += 3 ) {
  22928. // get the vertices of the face
  22929. getVertexByIndex( indices[ i + 0 ], a );
  22930. getVertexByIndex( indices[ i + 1 ], b );
  22931. getVertexByIndex( indices[ i + 2 ], c );
  22932. // perform subdivision
  22933. subdivideFace( a, b, c, detail );
  22934. }
  22935. }
  22936. function subdivideFace( a, b, c, detail ) {
  22937. const cols = detail + 1;
  22938. // we use this multidimensional array as a data structure for creating the subdivision
  22939. const v = [];
  22940. // construct all of the vertices for this subdivision
  22941. for ( let i = 0; i <= cols; i ++ ) {
  22942. v[ i ] = [];
  22943. const aj = a.clone().lerp( c, i / cols );
  22944. const bj = b.clone().lerp( c, i / cols );
  22945. const rows = cols - i;
  22946. for ( let j = 0; j <= rows; j ++ ) {
  22947. if ( j === 0 && i === cols ) {
  22948. v[ i ][ j ] = aj;
  22949. } else {
  22950. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22951. }
  22952. }
  22953. }
  22954. // construct all of the faces
  22955. for ( let i = 0; i < cols; i ++ ) {
  22956. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22957. const k = Math.floor( j / 2 );
  22958. if ( j % 2 === 0 ) {
  22959. pushVertex( v[ i ][ k + 1 ] );
  22960. pushVertex( v[ i + 1 ][ k ] );
  22961. pushVertex( v[ i ][ k ] );
  22962. } else {
  22963. pushVertex( v[ i ][ k + 1 ] );
  22964. pushVertex( v[ i + 1 ][ k + 1 ] );
  22965. pushVertex( v[ i + 1 ][ k ] );
  22966. }
  22967. }
  22968. }
  22969. }
  22970. function applyRadius( radius ) {
  22971. const vertex = new Vector3();
  22972. // iterate over the entire buffer and apply the radius to each vertex
  22973. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22974. vertex.x = vertexBuffer[ i + 0 ];
  22975. vertex.y = vertexBuffer[ i + 1 ];
  22976. vertex.z = vertexBuffer[ i + 2 ];
  22977. vertex.normalize().multiplyScalar( radius );
  22978. vertexBuffer[ i + 0 ] = vertex.x;
  22979. vertexBuffer[ i + 1 ] = vertex.y;
  22980. vertexBuffer[ i + 2 ] = vertex.z;
  22981. }
  22982. }
  22983. function generateUVs() {
  22984. const vertex = new Vector3();
  22985. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22986. vertex.x = vertexBuffer[ i + 0 ];
  22987. vertex.y = vertexBuffer[ i + 1 ];
  22988. vertex.z = vertexBuffer[ i + 2 ];
  22989. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22990. const v = inclination( vertex ) / Math.PI + 0.5;
  22991. uvBuffer.push( u, 1 - v );
  22992. }
  22993. correctUVs();
  22994. correctSeam();
  22995. }
  22996. function correctSeam() {
  22997. // handle case when face straddles the seam, see #3269
  22998. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22999. // uv data of a single face
  23000. const x0 = uvBuffer[ i + 0 ];
  23001. const x1 = uvBuffer[ i + 2 ];
  23002. const x2 = uvBuffer[ i + 4 ];
  23003. const max = Math.max( x0, x1, x2 );
  23004. const min = Math.min( x0, x1, x2 );
  23005. // 0.9 is somewhat arbitrary
  23006. if ( max > 0.9 && min < 0.1 ) {
  23007. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23008. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23009. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23010. }
  23011. }
  23012. }
  23013. function pushVertex( vertex ) {
  23014. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23015. }
  23016. function getVertexByIndex( index, vertex ) {
  23017. const stride = index * 3;
  23018. vertex.x = vertices[ stride + 0 ];
  23019. vertex.y = vertices[ stride + 1 ];
  23020. vertex.z = vertices[ stride + 2 ];
  23021. }
  23022. function correctUVs() {
  23023. const a = new Vector3();
  23024. const b = new Vector3();
  23025. const c = new Vector3();
  23026. const centroid = new Vector3();
  23027. const uvA = new Vector2();
  23028. const uvB = new Vector2();
  23029. const uvC = new Vector2();
  23030. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23031. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23032. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23033. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23034. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23035. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23036. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23037. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23038. const azi = azimuth( centroid );
  23039. correctUV( uvA, j + 0, a, azi );
  23040. correctUV( uvB, j + 2, b, azi );
  23041. correctUV( uvC, j + 4, c, azi );
  23042. }
  23043. }
  23044. function correctUV( uv, stride, vector, azimuth ) {
  23045. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23046. uvBuffer[ stride ] = uv.x - 1;
  23047. }
  23048. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23049. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23050. }
  23051. }
  23052. // Angle around the Y axis, counter-clockwise when looking from above.
  23053. function azimuth( vector ) {
  23054. return Math.atan2( vector.z, - vector.x );
  23055. }
  23056. // Angle above the XZ plane.
  23057. function inclination( vector ) {
  23058. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23059. }
  23060. }
  23061. copy( source ) {
  23062. super.copy( source );
  23063. this.parameters = Object.assign( {}, source.parameters );
  23064. return this;
  23065. }
  23066. /**
  23067. * Factory method for creating an instance of this class from the given
  23068. * JSON object.
  23069. *
  23070. * @param {Object} data - A JSON object representing the serialized geometry.
  23071. * @return {PolyhedronGeometry} A new instance.
  23072. */
  23073. static fromJSON( data ) {
  23074. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23075. }
  23076. }
  23077. /**
  23078. * A geometry class for representing a dodecahedron.
  23079. *
  23080. * ```js
  23081. * const geometry = new THREE.DodecahedronGeometry();
  23082. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23083. * const dodecahedron = new THREE.Mesh( geometry, material );
  23084. * scene.add( dodecahedron );
  23085. * ```
  23086. *
  23087. * @augments PolyhedronGeometry
  23088. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23089. */
  23090. class DodecahedronGeometry extends PolyhedronGeometry {
  23091. /**
  23092. * Constructs a new dodecahedron geometry.
  23093. *
  23094. * @param {number} [radius=1] - Radius of the dodecahedron.
  23095. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23096. */
  23097. constructor( radius = 1, detail = 0 ) {
  23098. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23099. const r = 1 / t;
  23100. const vertices = [
  23101. // (±1, ±1, ±1)
  23102. -1, -1, -1, -1, -1, 1,
  23103. -1, 1, -1, -1, 1, 1,
  23104. 1, -1, -1, 1, -1, 1,
  23105. 1, 1, -1, 1, 1, 1,
  23106. // (0, ±1/φ, ±φ)
  23107. 0, - r, - t, 0, - r, t,
  23108. 0, r, - t, 0, r, t,
  23109. // (±1/φ, ±φ, 0)
  23110. - r, - t, 0, - r, t, 0,
  23111. r, - t, 0, r, t, 0,
  23112. // (±φ, 0, ±1/φ)
  23113. - t, 0, - r, t, 0, - r,
  23114. - t, 0, r, t, 0, r
  23115. ];
  23116. const indices = [
  23117. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23118. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23119. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23120. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23121. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23122. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23123. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23124. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23125. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23126. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23127. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23128. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23129. ];
  23130. super( vertices, indices, radius, detail );
  23131. this.type = 'DodecahedronGeometry';
  23132. /**
  23133. * Holds the constructor parameters that have been
  23134. * used to generate the geometry. Any modification
  23135. * after instantiation does not change the geometry.
  23136. *
  23137. * @type {Object}
  23138. */
  23139. this.parameters = {
  23140. radius: radius,
  23141. detail: detail
  23142. };
  23143. }
  23144. /**
  23145. * Factory method for creating an instance of this class from the given
  23146. * JSON object.
  23147. *
  23148. * @param {Object} data - A JSON object representing the serialized geometry.
  23149. * @return {DodecahedronGeometry} A new instance.
  23150. */
  23151. static fromJSON( data ) {
  23152. return new DodecahedronGeometry( data.radius, data.detail );
  23153. }
  23154. }
  23155. const _v0$1 = /*@__PURE__*/ new Vector3();
  23156. const _v1$1 = /*@__PURE__*/ new Vector3();
  23157. const _normal = /*@__PURE__*/ new Vector3();
  23158. const _triangle = /*@__PURE__*/ new Triangle();
  23159. /**
  23160. * Can be used as a helper object to view the edges of a geometry.
  23161. *
  23162. * ```js
  23163. * const geometry = new THREE.BoxGeometry();
  23164. * const edges = new THREE.EdgesGeometry( geometry );
  23165. * const line = new THREE.LineSegments( edges );
  23166. * scene.add( line );
  23167. * ```
  23168. *
  23169. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23170. *
  23171. * @augments BufferGeometry
  23172. */
  23173. class EdgesGeometry extends BufferGeometry {
  23174. /**
  23175. * Constructs a new edges geometry.
  23176. *
  23177. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23178. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23179. * between the face normals of the adjoining faces exceeds this value.
  23180. */
  23181. constructor( geometry = null, thresholdAngle = 1 ) {
  23182. super();
  23183. this.type = 'EdgesGeometry';
  23184. /**
  23185. * Holds the constructor parameters that have been
  23186. * used to generate the geometry. Any modification
  23187. * after instantiation does not change the geometry.
  23188. *
  23189. * @type {Object}
  23190. */
  23191. this.parameters = {
  23192. geometry: geometry,
  23193. thresholdAngle: thresholdAngle
  23194. };
  23195. if ( geometry !== null ) {
  23196. const precisionPoints = 4;
  23197. const precision = Math.pow( 10, precisionPoints );
  23198. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23199. const indexAttr = geometry.getIndex();
  23200. const positionAttr = geometry.getAttribute( 'position' );
  23201. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23202. const indexArr = [ 0, 0, 0 ];
  23203. const vertKeys = [ 'a', 'b', 'c' ];
  23204. const hashes = new Array( 3 );
  23205. const edgeData = {};
  23206. const vertices = [];
  23207. for ( let i = 0; i < indexCount; i += 3 ) {
  23208. if ( indexAttr ) {
  23209. indexArr[ 0 ] = indexAttr.getX( i );
  23210. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23211. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23212. } else {
  23213. indexArr[ 0 ] = i;
  23214. indexArr[ 1 ] = i + 1;
  23215. indexArr[ 2 ] = i + 2;
  23216. }
  23217. const { a, b, c } = _triangle;
  23218. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23219. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23220. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23221. _triangle.getNormal( _normal );
  23222. // create hashes for the edge from the vertices
  23223. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23224. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23225. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23226. // skip degenerate triangles
  23227. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23228. continue;
  23229. }
  23230. // iterate over every edge
  23231. for ( let j = 0; j < 3; j ++ ) {
  23232. // get the first and next vertex making up the edge
  23233. const jNext = ( j + 1 ) % 3;
  23234. const vecHash0 = hashes[ j ];
  23235. const vecHash1 = hashes[ jNext ];
  23236. const v0 = _triangle[ vertKeys[ j ] ];
  23237. const v1 = _triangle[ vertKeys[ jNext ] ];
  23238. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23239. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23240. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23241. // if we found a sibling edge add it into the vertex array if
  23242. // it meets the angle threshold and delete the edge from the map.
  23243. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23244. vertices.push( v0.x, v0.y, v0.z );
  23245. vertices.push( v1.x, v1.y, v1.z );
  23246. }
  23247. edgeData[ reverseHash ] = null;
  23248. } else if ( ! ( hash in edgeData ) ) {
  23249. // if we've already got an edge here then skip adding a new one
  23250. edgeData[ hash ] = {
  23251. index0: indexArr[ j ],
  23252. index1: indexArr[ jNext ],
  23253. normal: _normal.clone(),
  23254. };
  23255. }
  23256. }
  23257. }
  23258. // iterate over all remaining, unmatched edges and add them to the vertex array
  23259. for ( const key in edgeData ) {
  23260. if ( edgeData[ key ] ) {
  23261. const { index0, index1 } = edgeData[ key ];
  23262. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23263. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23264. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23265. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23266. }
  23267. }
  23268. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23269. }
  23270. }
  23271. copy( source ) {
  23272. super.copy( source );
  23273. this.parameters = Object.assign( {}, source.parameters );
  23274. return this;
  23275. }
  23276. }
  23277. /**
  23278. * An abstract base class for creating an analytic curve object that contains methods
  23279. * for interpolation.
  23280. *
  23281. * @abstract
  23282. */
  23283. class Curve {
  23284. /**
  23285. * Constructs a new curve.
  23286. */
  23287. constructor() {
  23288. /**
  23289. * The type property is used for detecting the object type
  23290. * in context of serialization/deserialization.
  23291. *
  23292. * @type {string}
  23293. * @readonly
  23294. */
  23295. this.type = 'Curve';
  23296. /**
  23297. * This value determines the amount of divisions when calculating the
  23298. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23299. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23300. * recommended to increase the value of this property if the curve is very large.
  23301. *
  23302. * @type {number}
  23303. * @default 200
  23304. */
  23305. this.arcLengthDivisions = 200;
  23306. /**
  23307. * Must be set to `true` if the curve parameters have changed.
  23308. *
  23309. * @type {boolean}
  23310. * @default false
  23311. */
  23312. this.needsUpdate = false;
  23313. /**
  23314. * An internal cache that holds precomputed curve length values.
  23315. *
  23316. * @private
  23317. * @type {?Array<number>}
  23318. * @default null
  23319. */
  23320. this.cacheArcLengths = null;
  23321. }
  23322. /**
  23323. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23324. * for the given interpolation factor.
  23325. *
  23326. * @abstract
  23327. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23328. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23329. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23330. */
  23331. getPoint( /* t, optionalTarget */ ) {
  23332. warn( 'Curve: .getPoint() not implemented.' );
  23333. }
  23334. /**
  23335. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23336. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23337. * of the curve which equidistant samples.
  23338. *
  23339. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23340. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23341. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23342. */
  23343. getPointAt( u, optionalTarget ) {
  23344. const t = this.getUtoTmapping( u );
  23345. return this.getPoint( t, optionalTarget );
  23346. }
  23347. /**
  23348. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23349. * the curve shape.
  23350. *
  23351. * @param {number} [divisions=5] - The number of divisions.
  23352. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23353. */
  23354. getPoints( divisions = 5 ) {
  23355. const points = [];
  23356. for ( let d = 0; d <= divisions; d ++ ) {
  23357. points.push( this.getPoint( d / divisions ) );
  23358. }
  23359. return points;
  23360. }
  23361. // Get sequence of points using getPointAt( u )
  23362. /**
  23363. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23364. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23365. * curve.
  23366. *
  23367. * @param {number} [divisions=5] - The number of divisions.
  23368. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23369. */
  23370. getSpacedPoints( divisions = 5 ) {
  23371. const points = [];
  23372. for ( let d = 0; d <= divisions; d ++ ) {
  23373. points.push( this.getPointAt( d / divisions ) );
  23374. }
  23375. return points;
  23376. }
  23377. /**
  23378. * Returns the total arc length of the curve.
  23379. *
  23380. * @return {number} The length of the curve.
  23381. */
  23382. getLength() {
  23383. const lengths = this.getLengths();
  23384. return lengths[ lengths.length - 1 ];
  23385. }
  23386. /**
  23387. * Returns an array of cumulative segment lengths of the curve.
  23388. *
  23389. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23390. * @return {Array<number>} An array holding the cumulative segment lengths.
  23391. */
  23392. getLengths( divisions = this.arcLengthDivisions ) {
  23393. if ( this.cacheArcLengths &&
  23394. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23395. ! this.needsUpdate ) {
  23396. return this.cacheArcLengths;
  23397. }
  23398. this.needsUpdate = false;
  23399. const cache = [];
  23400. let current, last = this.getPoint( 0 );
  23401. let sum = 0;
  23402. cache.push( 0 );
  23403. for ( let p = 1; p <= divisions; p ++ ) {
  23404. current = this.getPoint( p / divisions );
  23405. sum += current.distanceTo( last );
  23406. cache.push( sum );
  23407. last = current;
  23408. }
  23409. this.cacheArcLengths = cache;
  23410. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23411. }
  23412. /**
  23413. * Update the cumulative segment distance cache. The method must be called
  23414. * every time curve parameters are changed. If an updated curve is part of a
  23415. * composed curve like {@link CurvePath}, this method must be called on the
  23416. * composed curve, too.
  23417. */
  23418. updateArcLengths() {
  23419. this.needsUpdate = true;
  23420. this.getLengths();
  23421. }
  23422. /**
  23423. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23424. * interpolation factor in the same range that can be ued to sample equidistant points
  23425. * from a curve.
  23426. *
  23427. * @param {number} u - The interpolation factor.
  23428. * @param {?number} distance - An optional distance on the curve.
  23429. * @return {number} The updated interpolation factor.
  23430. */
  23431. getUtoTmapping( u, distance = null ) {
  23432. const arcLengths = this.getLengths();
  23433. let i = 0;
  23434. const il = arcLengths.length;
  23435. let targetArcLength; // The targeted u distance value to get
  23436. if ( distance ) {
  23437. targetArcLength = distance;
  23438. } else {
  23439. targetArcLength = u * arcLengths[ il - 1 ];
  23440. }
  23441. // binary search for the index with largest value smaller than target u distance
  23442. let low = 0, high = il - 1, comparison;
  23443. while ( low <= high ) {
  23444. 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
  23445. comparison = arcLengths[ i ] - targetArcLength;
  23446. if ( comparison < 0 ) {
  23447. low = i + 1;
  23448. } else if ( comparison > 0 ) {
  23449. high = i - 1;
  23450. } else {
  23451. high = i;
  23452. break;
  23453. // DONE
  23454. }
  23455. }
  23456. i = high;
  23457. if ( arcLengths[ i ] === targetArcLength ) {
  23458. return i / ( il - 1 );
  23459. }
  23460. // we could get finer grain at lengths, or use simple interpolation between two points
  23461. const lengthBefore = arcLengths[ i ];
  23462. const lengthAfter = arcLengths[ i + 1 ];
  23463. const segmentLength = lengthAfter - lengthBefore;
  23464. // determine where we are between the 'before' and 'after' points
  23465. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23466. // add that fractional amount to t
  23467. const t = ( i + segmentFraction ) / ( il - 1 );
  23468. return t;
  23469. }
  23470. /**
  23471. * Returns a unit vector tangent for the given interpolation factor.
  23472. * If the derived curve does not implement its tangent derivation,
  23473. * two points a small delta apart will be used to find its gradient
  23474. * which seems to give a reasonable approximation.
  23475. *
  23476. * @param {number} t - The interpolation factor.
  23477. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23478. * @return {(Vector2|Vector3)} The tangent vector.
  23479. */
  23480. getTangent( t, optionalTarget ) {
  23481. const delta = 0.0001;
  23482. let t1 = t - delta;
  23483. let t2 = t + delta;
  23484. // Capping in case of danger
  23485. if ( t1 < 0 ) t1 = 0;
  23486. if ( t2 > 1 ) t2 = 1;
  23487. const pt1 = this.getPoint( t1 );
  23488. const pt2 = this.getPoint( t2 );
  23489. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23490. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23491. return tangent;
  23492. }
  23493. /**
  23494. * Same as {@link Curve#getTangent} but with equidistant samples.
  23495. *
  23496. * @param {number} u - The interpolation factor.
  23497. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23498. * @return {(Vector2|Vector3)} The tangent vector.
  23499. * @see {@link Curve#getPointAt}
  23500. */
  23501. getTangentAt( u, optionalTarget ) {
  23502. const t = this.getUtoTmapping( u );
  23503. return this.getTangent( t, optionalTarget );
  23504. }
  23505. /**
  23506. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23507. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23508. *
  23509. * @param {number} segments - The number of segments.
  23510. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23511. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23512. */
  23513. computeFrenetFrames( segments, closed = false ) {
  23514. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23515. const normal = new Vector3();
  23516. const tangents = [];
  23517. const normals = [];
  23518. const binormals = [];
  23519. const vec = new Vector3();
  23520. const mat = new Matrix4();
  23521. // compute the tangent vectors for each segment on the curve
  23522. for ( let i = 0; i <= segments; i ++ ) {
  23523. const u = i / segments;
  23524. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23525. }
  23526. // select an initial normal vector perpendicular to the first tangent vector,
  23527. // and in the direction of the minimum tangent xyz component
  23528. normals[ 0 ] = new Vector3();
  23529. binormals[ 0 ] = new Vector3();
  23530. let min = Number.MAX_VALUE;
  23531. const tx = Math.abs( tangents[ 0 ].x );
  23532. const ty = Math.abs( tangents[ 0 ].y );
  23533. const tz = Math.abs( tangents[ 0 ].z );
  23534. if ( tx <= min ) {
  23535. min = tx;
  23536. normal.set( 1, 0, 0 );
  23537. }
  23538. if ( ty <= min ) {
  23539. min = ty;
  23540. normal.set( 0, 1, 0 );
  23541. }
  23542. if ( tz <= min ) {
  23543. normal.set( 0, 0, 1 );
  23544. }
  23545. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23546. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23547. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23548. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23549. for ( let i = 1; i <= segments; i ++ ) {
  23550. normals[ i ] = normals[ i - 1 ].clone();
  23551. binormals[ i ] = binormals[ i - 1 ].clone();
  23552. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23553. if ( vec.length() > Number.EPSILON ) {
  23554. vec.normalize();
  23555. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23556. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23557. }
  23558. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23559. }
  23560. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23561. if ( closed === true ) {
  23562. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23563. theta /= segments;
  23564. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23565. theta = - theta;
  23566. }
  23567. for ( let i = 1; i <= segments; i ++ ) {
  23568. // twist a little...
  23569. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23570. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23571. }
  23572. }
  23573. return {
  23574. tangents: tangents,
  23575. normals: normals,
  23576. binormals: binormals
  23577. };
  23578. }
  23579. /**
  23580. * Returns a new curve with copied values from this instance.
  23581. *
  23582. * @return {Curve} A clone of this instance.
  23583. */
  23584. clone() {
  23585. return new this.constructor().copy( this );
  23586. }
  23587. /**
  23588. * Copies the values of the given curve to this instance.
  23589. *
  23590. * @param {Curve} source - The curve to copy.
  23591. * @return {Curve} A reference to this curve.
  23592. */
  23593. copy( source ) {
  23594. this.arcLengthDivisions = source.arcLengthDivisions;
  23595. return this;
  23596. }
  23597. /**
  23598. * Serializes the curve into JSON.
  23599. *
  23600. * @return {Object} A JSON object representing the serialized curve.
  23601. * @see {@link ObjectLoader#parse}
  23602. */
  23603. toJSON() {
  23604. const data = {
  23605. metadata: {
  23606. version: 4.7,
  23607. type: 'Curve',
  23608. generator: 'Curve.toJSON'
  23609. }
  23610. };
  23611. data.arcLengthDivisions = this.arcLengthDivisions;
  23612. data.type = this.type;
  23613. return data;
  23614. }
  23615. /**
  23616. * Deserializes the curve from the given JSON.
  23617. *
  23618. * @param {Object} json - The JSON holding the serialized curve.
  23619. * @return {Curve} A reference to this curve.
  23620. */
  23621. fromJSON( json ) {
  23622. this.arcLengthDivisions = json.arcLengthDivisions;
  23623. return this;
  23624. }
  23625. }
  23626. /**
  23627. * A curve representing an ellipse.
  23628. *
  23629. * ```js
  23630. * const curve = new THREE.EllipseCurve(
  23631. * 0, 0,
  23632. * 10, 10,
  23633. * 0, 2 * Math.PI,
  23634. * false,
  23635. * 0
  23636. * );
  23637. *
  23638. * const points = curve.getPoints( 50 );
  23639. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23640. *
  23641. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23642. *
  23643. * // Create the final object to add to the scene
  23644. * const ellipse = new THREE.Line( geometry, material );
  23645. * ```
  23646. *
  23647. * @augments Curve
  23648. */
  23649. class EllipseCurve extends Curve {
  23650. /**
  23651. * Constructs a new ellipse curve.
  23652. *
  23653. * @param {number} [aX=0] - The X center of the ellipse.
  23654. * @param {number} [aY=0] - The Y center of the ellipse.
  23655. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23656. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23657. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23658. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23659. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23660. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23661. */
  23662. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23663. super();
  23664. /**
  23665. * This flag can be used for type testing.
  23666. *
  23667. * @type {boolean}
  23668. * @readonly
  23669. * @default true
  23670. */
  23671. this.isEllipseCurve = true;
  23672. this.type = 'EllipseCurve';
  23673. /**
  23674. * The X center of the ellipse.
  23675. *
  23676. * @type {number}
  23677. * @default 0
  23678. */
  23679. this.aX = aX;
  23680. /**
  23681. * The Y center of the ellipse.
  23682. *
  23683. * @type {number}
  23684. * @default 0
  23685. */
  23686. this.aY = aY;
  23687. /**
  23688. * The radius of the ellipse in the x direction.
  23689. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23690. *
  23691. * @type {number}
  23692. * @default 1
  23693. */
  23694. this.xRadius = xRadius;
  23695. /**
  23696. * The radius of the ellipse in the y direction.
  23697. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23698. *
  23699. * @type {number}
  23700. * @default 1
  23701. */
  23702. this.yRadius = yRadius;
  23703. /**
  23704. * The start angle of the curve in radians starting from the positive X axis.
  23705. *
  23706. * @type {number}
  23707. * @default 0
  23708. */
  23709. this.aStartAngle = aStartAngle;
  23710. /**
  23711. * The end angle of the curve in radians starting from the positive X axis.
  23712. *
  23713. * @type {number}
  23714. * @default Math.PI*2
  23715. */
  23716. this.aEndAngle = aEndAngle;
  23717. /**
  23718. * Whether the ellipse is drawn clockwise or not.
  23719. *
  23720. * @type {boolean}
  23721. * @default false
  23722. */
  23723. this.aClockwise = aClockwise;
  23724. /**
  23725. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23726. *
  23727. * @type {number}
  23728. * @default 0
  23729. */
  23730. this.aRotation = aRotation;
  23731. }
  23732. /**
  23733. * Returns a point on the curve.
  23734. *
  23735. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23736. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23737. * @return {Vector2} The position on the curve.
  23738. */
  23739. getPoint( t, optionalTarget = new Vector2() ) {
  23740. const point = optionalTarget;
  23741. const twoPi = Math.PI * 2;
  23742. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23743. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23744. // ensures that deltaAngle is 0 .. 2 PI
  23745. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23746. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23747. if ( deltaAngle < Number.EPSILON ) {
  23748. if ( samePoints ) {
  23749. deltaAngle = 0;
  23750. } else {
  23751. deltaAngle = twoPi;
  23752. }
  23753. }
  23754. if ( this.aClockwise === true && ! samePoints ) {
  23755. if ( deltaAngle === twoPi ) {
  23756. deltaAngle = - twoPi;
  23757. } else {
  23758. deltaAngle = deltaAngle - twoPi;
  23759. }
  23760. }
  23761. const angle = this.aStartAngle + t * deltaAngle;
  23762. let x = this.aX + this.xRadius * Math.cos( angle );
  23763. let y = this.aY + this.yRadius * Math.sin( angle );
  23764. if ( this.aRotation !== 0 ) {
  23765. const cos = Math.cos( this.aRotation );
  23766. const sin = Math.sin( this.aRotation );
  23767. const tx = x - this.aX;
  23768. const ty = y - this.aY;
  23769. // Rotate the point about the center of the ellipse.
  23770. x = tx * cos - ty * sin + this.aX;
  23771. y = tx * sin + ty * cos + this.aY;
  23772. }
  23773. return point.set( x, y );
  23774. }
  23775. copy( source ) {
  23776. super.copy( source );
  23777. this.aX = source.aX;
  23778. this.aY = source.aY;
  23779. this.xRadius = source.xRadius;
  23780. this.yRadius = source.yRadius;
  23781. this.aStartAngle = source.aStartAngle;
  23782. this.aEndAngle = source.aEndAngle;
  23783. this.aClockwise = source.aClockwise;
  23784. this.aRotation = source.aRotation;
  23785. return this;
  23786. }
  23787. toJSON() {
  23788. const data = super.toJSON();
  23789. data.aX = this.aX;
  23790. data.aY = this.aY;
  23791. data.xRadius = this.xRadius;
  23792. data.yRadius = this.yRadius;
  23793. data.aStartAngle = this.aStartAngle;
  23794. data.aEndAngle = this.aEndAngle;
  23795. data.aClockwise = this.aClockwise;
  23796. data.aRotation = this.aRotation;
  23797. return data;
  23798. }
  23799. fromJSON( json ) {
  23800. super.fromJSON( json );
  23801. this.aX = json.aX;
  23802. this.aY = json.aY;
  23803. this.xRadius = json.xRadius;
  23804. this.yRadius = json.yRadius;
  23805. this.aStartAngle = json.aStartAngle;
  23806. this.aEndAngle = json.aEndAngle;
  23807. this.aClockwise = json.aClockwise;
  23808. this.aRotation = json.aRotation;
  23809. return this;
  23810. }
  23811. }
  23812. /**
  23813. * A curve representing an arc.
  23814. *
  23815. * @augments EllipseCurve
  23816. */
  23817. class ArcCurve extends EllipseCurve {
  23818. /**
  23819. * Constructs a new arc curve.
  23820. *
  23821. * @param {number} [aX=0] - The X center of the ellipse.
  23822. * @param {number} [aY=0] - The Y center of the ellipse.
  23823. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23824. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23825. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23826. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23827. */
  23828. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23829. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23830. /**
  23831. * This flag can be used for type testing.
  23832. *
  23833. * @type {boolean}
  23834. * @readonly
  23835. * @default true
  23836. */
  23837. this.isArcCurve = true;
  23838. this.type = 'ArcCurve';
  23839. }
  23840. }
  23841. function CubicPoly() {
  23842. /**
  23843. * Centripetal CatmullRom Curve - which is useful for avoiding
  23844. * cusps and self-intersections in non-uniform catmull rom curves.
  23845. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23846. *
  23847. * curve.type accepts centripetal(default), chordal and catmullrom
  23848. * curve.tension is used for catmullrom which defaults to 0.5
  23849. */
  23850. /*
  23851. Based on an optimized c++ solution in
  23852. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23853. - http://ideone.com/NoEbVM
  23854. This CubicPoly class could be used for reusing some variables and calculations,
  23855. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23856. which can be placed in CurveUtils.
  23857. */
  23858. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23859. /*
  23860. * Compute coefficients for a cubic polynomial
  23861. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23862. * such that
  23863. * p(0) = x0, p(1) = x1
  23864. * and
  23865. * p'(0) = t0, p'(1) = t1.
  23866. */
  23867. function init( x0, x1, t0, t1 ) {
  23868. c0 = x0;
  23869. c1 = t0;
  23870. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23871. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23872. }
  23873. return {
  23874. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23875. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23876. },
  23877. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23878. // compute tangents when parameterized in [t1,t2]
  23879. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23880. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23881. // rescale tangents for parametrization in [0,1]
  23882. t1 *= dt1;
  23883. t2 *= dt1;
  23884. init( x1, x2, t1, t2 );
  23885. },
  23886. calc: function ( t ) {
  23887. const t2 = t * t;
  23888. const t3 = t2 * t;
  23889. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23890. }
  23891. };
  23892. }
  23893. //
  23894. const tmp = /*@__PURE__*/ new Vector3();
  23895. const px = /*@__PURE__*/ new CubicPoly();
  23896. const py = /*@__PURE__*/ new CubicPoly();
  23897. const pz = /*@__PURE__*/ new CubicPoly();
  23898. /**
  23899. * A curve representing a Catmull-Rom spline.
  23900. *
  23901. * ```js
  23902. * //Create a closed wavey loop
  23903. * const curve = new THREE.CatmullRomCurve3( [
  23904. * new THREE.Vector3( -10, 0, 10 ),
  23905. * new THREE.Vector3( -5, 5, 5 ),
  23906. * new THREE.Vector3( 0, 0, 0 ),
  23907. * new THREE.Vector3( 5, -5, 5 ),
  23908. * new THREE.Vector3( 10, 0, 10 )
  23909. * ] );
  23910. *
  23911. * const points = curve.getPoints( 50 );
  23912. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23913. *
  23914. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23915. *
  23916. * // Create the final object to add to the scene
  23917. * const curveObject = new THREE.Line( geometry, material );
  23918. * ```
  23919. *
  23920. * @augments Curve
  23921. */
  23922. class CatmullRomCurve3 extends Curve {
  23923. /**
  23924. * Constructs a new Catmull-Rom curve.
  23925. *
  23926. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23927. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23928. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23929. * @param {number} [tension=0.5] - Tension of the curve.
  23930. */
  23931. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23932. super();
  23933. /**
  23934. * This flag can be used for type testing.
  23935. *
  23936. * @type {boolean}
  23937. * @readonly
  23938. * @default true
  23939. */
  23940. this.isCatmullRomCurve3 = true;
  23941. this.type = 'CatmullRomCurve3';
  23942. /**
  23943. * An array of 3D points defining the curve.
  23944. *
  23945. * @type {Array<Vector3>}
  23946. */
  23947. this.points = points;
  23948. /**
  23949. * Whether the curve is closed or not.
  23950. *
  23951. * @type {boolean}
  23952. * @default false
  23953. */
  23954. this.closed = closed;
  23955. /**
  23956. * The curve type.
  23957. *
  23958. * @type {('centripetal'|'chordal'|'catmullrom')}
  23959. * @default 'centripetal'
  23960. */
  23961. this.curveType = curveType;
  23962. /**
  23963. * Tension of the curve.
  23964. *
  23965. * @type {number}
  23966. * @default 0.5
  23967. */
  23968. this.tension = tension;
  23969. }
  23970. /**
  23971. * Returns a point on the curve.
  23972. *
  23973. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23974. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23975. * @return {Vector3} The position on the curve.
  23976. */
  23977. getPoint( t, optionalTarget = new Vector3() ) {
  23978. const point = optionalTarget;
  23979. const points = this.points;
  23980. const l = points.length;
  23981. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23982. let intPoint = Math.floor( p );
  23983. let weight = p - intPoint;
  23984. if ( this.closed ) {
  23985. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23986. } else if ( weight === 0 && intPoint === l - 1 ) {
  23987. intPoint = l - 2;
  23988. weight = 1;
  23989. }
  23990. let p0, p3; // 4 points (p1 & p2 defined below)
  23991. if ( this.closed || intPoint > 0 ) {
  23992. p0 = points[ ( intPoint - 1 ) % l ];
  23993. } else {
  23994. // extrapolate first point
  23995. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23996. p0 = tmp;
  23997. }
  23998. const p1 = points[ intPoint % l ];
  23999. const p2 = points[ ( intPoint + 1 ) % l ];
  24000. if ( this.closed || intPoint + 2 < l ) {
  24001. p3 = points[ ( intPoint + 2 ) % l ];
  24002. } else {
  24003. // extrapolate last point
  24004. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24005. p3 = tmp;
  24006. }
  24007. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24008. // init Centripetal / Chordal Catmull-Rom
  24009. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24010. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24011. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24012. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24013. // safety check for repeated points
  24014. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24015. if ( dt0 < 1e-4 ) dt0 = dt1;
  24016. if ( dt2 < 1e-4 ) dt2 = dt1;
  24017. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24018. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24019. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24020. } else if ( this.curveType === 'catmullrom' ) {
  24021. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24022. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24023. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24024. }
  24025. point.set(
  24026. px.calc( weight ),
  24027. py.calc( weight ),
  24028. pz.calc( weight )
  24029. );
  24030. return point;
  24031. }
  24032. copy( source ) {
  24033. super.copy( source );
  24034. this.points = [];
  24035. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24036. const point = source.points[ i ];
  24037. this.points.push( point.clone() );
  24038. }
  24039. this.closed = source.closed;
  24040. this.curveType = source.curveType;
  24041. this.tension = source.tension;
  24042. return this;
  24043. }
  24044. toJSON() {
  24045. const data = super.toJSON();
  24046. data.points = [];
  24047. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24048. const point = this.points[ i ];
  24049. data.points.push( point.toArray() );
  24050. }
  24051. data.closed = this.closed;
  24052. data.curveType = this.curveType;
  24053. data.tension = this.tension;
  24054. return data;
  24055. }
  24056. fromJSON( json ) {
  24057. super.fromJSON( json );
  24058. this.points = [];
  24059. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24060. const point = json.points[ i ];
  24061. this.points.push( new Vector3().fromArray( point ) );
  24062. }
  24063. this.closed = json.closed;
  24064. this.curveType = json.curveType;
  24065. this.tension = json.tension;
  24066. return this;
  24067. }
  24068. }
  24069. /**
  24070. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24071. *
  24072. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24073. *
  24074. * @module Interpolations
  24075. */
  24076. /**
  24077. * Computes a point on a Catmull-Rom spline.
  24078. *
  24079. * @param {number} t - The interpolation factor.
  24080. * @param {number} p0 - The first control point.
  24081. * @param {number} p1 - The second control point.
  24082. * @param {number} p2 - The third control point.
  24083. * @param {number} p3 - The fourth control point.
  24084. * @return {number} The calculated point on a Catmull-Rom spline.
  24085. */
  24086. function CatmullRom( t, p0, p1, p2, p3 ) {
  24087. const v0 = ( p2 - p0 ) * 0.5;
  24088. const v1 = ( p3 - p1 ) * 0.5;
  24089. const t2 = t * t;
  24090. const t3 = t * t2;
  24091. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24092. }
  24093. //
  24094. function QuadraticBezierP0( t, p ) {
  24095. const k = 1 - t;
  24096. return k * k * p;
  24097. }
  24098. function QuadraticBezierP1( t, p ) {
  24099. return 2 * ( 1 - t ) * t * p;
  24100. }
  24101. function QuadraticBezierP2( t, p ) {
  24102. return t * t * p;
  24103. }
  24104. /**
  24105. * Computes a point on a Quadratic Bezier curve.
  24106. *
  24107. * @param {number} t - The interpolation factor.
  24108. * @param {number} p0 - The first control point.
  24109. * @param {number} p1 - The second control point.
  24110. * @param {number} p2 - The third control point.
  24111. * @return {number} The calculated point on a Quadratic Bezier curve.
  24112. */
  24113. function QuadraticBezier( t, p0, p1, p2 ) {
  24114. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24115. QuadraticBezierP2( t, p2 );
  24116. }
  24117. //
  24118. function CubicBezierP0( t, p ) {
  24119. const k = 1 - t;
  24120. return k * k * k * p;
  24121. }
  24122. function CubicBezierP1( t, p ) {
  24123. const k = 1 - t;
  24124. return 3 * k * k * t * p;
  24125. }
  24126. function CubicBezierP2( t, p ) {
  24127. return 3 * ( 1 - t ) * t * t * p;
  24128. }
  24129. function CubicBezierP3( t, p ) {
  24130. return t * t * t * p;
  24131. }
  24132. /**
  24133. * Computes a point on a Cubic Bezier curve.
  24134. *
  24135. * @param {number} t - The interpolation factor.
  24136. * @param {number} p0 - The first control point.
  24137. * @param {number} p1 - The second control point.
  24138. * @param {number} p2 - The third control point.
  24139. * @param {number} p3 - The fourth control point.
  24140. * @return {number} The calculated point on a Cubic Bezier curve.
  24141. */
  24142. function CubicBezier( t, p0, p1, p2, p3 ) {
  24143. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24144. CubicBezierP3( t, p3 );
  24145. }
  24146. /**
  24147. * A curve representing a 2D Cubic Bezier curve.
  24148. *
  24149. * ```js
  24150. * const curve = new THREE.CubicBezierCurve(
  24151. * new THREE.Vector2( - 0, 0 ),
  24152. * new THREE.Vector2( - 5, 15 ),
  24153. * new THREE.Vector2( 20, 15 ),
  24154. * new THREE.Vector2( 10, 0 )
  24155. * );
  24156. *
  24157. * const points = curve.getPoints( 50 );
  24158. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24159. *
  24160. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24161. *
  24162. * // Create the final object to add to the scene
  24163. * const curveObject = new THREE.Line( geometry, material );
  24164. * ```
  24165. *
  24166. * @augments Curve
  24167. */
  24168. class CubicBezierCurve extends Curve {
  24169. /**
  24170. * Constructs a new Cubic Bezier curve.
  24171. *
  24172. * @param {Vector2} [v0] - The start point.
  24173. * @param {Vector2} [v1] - The first control point.
  24174. * @param {Vector2} [v2] - The second control point.
  24175. * @param {Vector2} [v3] - The end point.
  24176. */
  24177. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24178. super();
  24179. /**
  24180. * This flag can be used for type testing.
  24181. *
  24182. * @type {boolean}
  24183. * @readonly
  24184. * @default true
  24185. */
  24186. this.isCubicBezierCurve = true;
  24187. this.type = 'CubicBezierCurve';
  24188. /**
  24189. * The start point.
  24190. *
  24191. * @type {Vector2}
  24192. */
  24193. this.v0 = v0;
  24194. /**
  24195. * The first control point.
  24196. *
  24197. * @type {Vector2}
  24198. */
  24199. this.v1 = v1;
  24200. /**
  24201. * The second control point.
  24202. *
  24203. * @type {Vector2}
  24204. */
  24205. this.v2 = v2;
  24206. /**
  24207. * The end point.
  24208. *
  24209. * @type {Vector2}
  24210. */
  24211. this.v3 = v3;
  24212. }
  24213. /**
  24214. * Returns a point on the curve.
  24215. *
  24216. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24217. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24218. * @return {Vector2} The position on the curve.
  24219. */
  24220. getPoint( t, optionalTarget = new Vector2() ) {
  24221. const point = optionalTarget;
  24222. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24223. point.set(
  24224. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24225. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24226. );
  24227. return point;
  24228. }
  24229. copy( source ) {
  24230. super.copy( source );
  24231. this.v0.copy( source.v0 );
  24232. this.v1.copy( source.v1 );
  24233. this.v2.copy( source.v2 );
  24234. this.v3.copy( source.v3 );
  24235. return this;
  24236. }
  24237. toJSON() {
  24238. const data = super.toJSON();
  24239. data.v0 = this.v0.toArray();
  24240. data.v1 = this.v1.toArray();
  24241. data.v2 = this.v2.toArray();
  24242. data.v3 = this.v3.toArray();
  24243. return data;
  24244. }
  24245. fromJSON( json ) {
  24246. super.fromJSON( json );
  24247. this.v0.fromArray( json.v0 );
  24248. this.v1.fromArray( json.v1 );
  24249. this.v2.fromArray( json.v2 );
  24250. this.v3.fromArray( json.v3 );
  24251. return this;
  24252. }
  24253. }
  24254. /**
  24255. * A curve representing a 3D Cubic Bezier curve.
  24256. *
  24257. * @augments Curve
  24258. */
  24259. class CubicBezierCurve3 extends Curve {
  24260. /**
  24261. * Constructs a new Cubic Bezier curve.
  24262. *
  24263. * @param {Vector3} [v0] - The start point.
  24264. * @param {Vector3} [v1] - The first control point.
  24265. * @param {Vector3} [v2] - The second control point.
  24266. * @param {Vector3} [v3] - The end point.
  24267. */
  24268. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24269. super();
  24270. /**
  24271. * This flag can be used for type testing.
  24272. *
  24273. * @type {boolean}
  24274. * @readonly
  24275. * @default true
  24276. */
  24277. this.isCubicBezierCurve3 = true;
  24278. this.type = 'CubicBezierCurve3';
  24279. /**
  24280. * The start point.
  24281. *
  24282. * @type {Vector3}
  24283. */
  24284. this.v0 = v0;
  24285. /**
  24286. * The first control point.
  24287. *
  24288. * @type {Vector3}
  24289. */
  24290. this.v1 = v1;
  24291. /**
  24292. * The second control point.
  24293. *
  24294. * @type {Vector3}
  24295. */
  24296. this.v2 = v2;
  24297. /**
  24298. * The end point.
  24299. *
  24300. * @type {Vector3}
  24301. */
  24302. this.v3 = v3;
  24303. }
  24304. /**
  24305. * Returns a point on the curve.
  24306. *
  24307. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24308. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24309. * @return {Vector3} The position on the curve.
  24310. */
  24311. getPoint( t, optionalTarget = new Vector3() ) {
  24312. const point = optionalTarget;
  24313. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24314. point.set(
  24315. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24316. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24317. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24318. );
  24319. return point;
  24320. }
  24321. copy( source ) {
  24322. super.copy( source );
  24323. this.v0.copy( source.v0 );
  24324. this.v1.copy( source.v1 );
  24325. this.v2.copy( source.v2 );
  24326. this.v3.copy( source.v3 );
  24327. return this;
  24328. }
  24329. toJSON() {
  24330. const data = super.toJSON();
  24331. data.v0 = this.v0.toArray();
  24332. data.v1 = this.v1.toArray();
  24333. data.v2 = this.v2.toArray();
  24334. data.v3 = this.v3.toArray();
  24335. return data;
  24336. }
  24337. fromJSON( json ) {
  24338. super.fromJSON( json );
  24339. this.v0.fromArray( json.v0 );
  24340. this.v1.fromArray( json.v1 );
  24341. this.v2.fromArray( json.v2 );
  24342. this.v3.fromArray( json.v3 );
  24343. return this;
  24344. }
  24345. }
  24346. /**
  24347. * A curve representing a 2D line segment.
  24348. *
  24349. * @augments Curve
  24350. */
  24351. class LineCurve extends Curve {
  24352. /**
  24353. * Constructs a new line curve.
  24354. *
  24355. * @param {Vector2} [v1] - The start point.
  24356. * @param {Vector2} [v2] - The end point.
  24357. */
  24358. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24359. super();
  24360. /**
  24361. * This flag can be used for type testing.
  24362. *
  24363. * @type {boolean}
  24364. * @readonly
  24365. * @default true
  24366. */
  24367. this.isLineCurve = true;
  24368. this.type = 'LineCurve';
  24369. /**
  24370. * The start point.
  24371. *
  24372. * @type {Vector2}
  24373. */
  24374. this.v1 = v1;
  24375. /**
  24376. * The end point.
  24377. *
  24378. * @type {Vector2}
  24379. */
  24380. this.v2 = v2;
  24381. }
  24382. /**
  24383. * Returns a point on the line.
  24384. *
  24385. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24386. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24387. * @return {Vector2} The position on the line.
  24388. */
  24389. getPoint( t, optionalTarget = new Vector2() ) {
  24390. const point = optionalTarget;
  24391. if ( t === 1 ) {
  24392. point.copy( this.v2 );
  24393. } else {
  24394. point.copy( this.v2 ).sub( this.v1 );
  24395. point.multiplyScalar( t ).add( this.v1 );
  24396. }
  24397. return point;
  24398. }
  24399. // Line curve is linear, so we can overwrite default getPointAt
  24400. getPointAt( u, optionalTarget ) {
  24401. return this.getPoint( u, optionalTarget );
  24402. }
  24403. getTangent( t, optionalTarget = new Vector2() ) {
  24404. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24405. }
  24406. getTangentAt( u, optionalTarget ) {
  24407. return this.getTangent( u, optionalTarget );
  24408. }
  24409. copy( source ) {
  24410. super.copy( source );
  24411. this.v1.copy( source.v1 );
  24412. this.v2.copy( source.v2 );
  24413. return this;
  24414. }
  24415. toJSON() {
  24416. const data = super.toJSON();
  24417. data.v1 = this.v1.toArray();
  24418. data.v2 = this.v2.toArray();
  24419. return data;
  24420. }
  24421. fromJSON( json ) {
  24422. super.fromJSON( json );
  24423. this.v1.fromArray( json.v1 );
  24424. this.v2.fromArray( json.v2 );
  24425. return this;
  24426. }
  24427. }
  24428. /**
  24429. * A curve representing a 3D line segment.
  24430. *
  24431. * @augments Curve
  24432. */
  24433. class LineCurve3 extends Curve {
  24434. /**
  24435. * Constructs a new line curve.
  24436. *
  24437. * @param {Vector3} [v1] - The start point.
  24438. * @param {Vector3} [v2] - The end point.
  24439. */
  24440. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24441. super();
  24442. /**
  24443. * This flag can be used for type testing.
  24444. *
  24445. * @type {boolean}
  24446. * @readonly
  24447. * @default true
  24448. */
  24449. this.isLineCurve3 = true;
  24450. this.type = 'LineCurve3';
  24451. /**
  24452. * The start point.
  24453. *
  24454. * @type {Vector3}
  24455. */
  24456. this.v1 = v1;
  24457. /**
  24458. * The end point.
  24459. *
  24460. * @type {Vector2}
  24461. */
  24462. this.v2 = v2;
  24463. }
  24464. /**
  24465. * Returns a point on the line.
  24466. *
  24467. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24468. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24469. * @return {Vector3} The position on the line.
  24470. */
  24471. getPoint( t, optionalTarget = new Vector3() ) {
  24472. const point = optionalTarget;
  24473. if ( t === 1 ) {
  24474. point.copy( this.v2 );
  24475. } else {
  24476. point.copy( this.v2 ).sub( this.v1 );
  24477. point.multiplyScalar( t ).add( this.v1 );
  24478. }
  24479. return point;
  24480. }
  24481. // Line curve is linear, so we can overwrite default getPointAt
  24482. getPointAt( u, optionalTarget ) {
  24483. return this.getPoint( u, optionalTarget );
  24484. }
  24485. getTangent( t, optionalTarget = new Vector3() ) {
  24486. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24487. }
  24488. getTangentAt( u, optionalTarget ) {
  24489. return this.getTangent( u, optionalTarget );
  24490. }
  24491. copy( source ) {
  24492. super.copy( source );
  24493. this.v1.copy( source.v1 );
  24494. this.v2.copy( source.v2 );
  24495. return this;
  24496. }
  24497. toJSON() {
  24498. const data = super.toJSON();
  24499. data.v1 = this.v1.toArray();
  24500. data.v2 = this.v2.toArray();
  24501. return data;
  24502. }
  24503. fromJSON( json ) {
  24504. super.fromJSON( json );
  24505. this.v1.fromArray( json.v1 );
  24506. this.v2.fromArray( json.v2 );
  24507. return this;
  24508. }
  24509. }
  24510. /**
  24511. * A curve representing a 2D Quadratic Bezier curve.
  24512. *
  24513. * ```js
  24514. * const curve = new THREE.QuadraticBezierCurve(
  24515. * new THREE.Vector2( - 10, 0 ),
  24516. * new THREE.Vector2( 20, 15 ),
  24517. * new THREE.Vector2( 10, 0 )
  24518. * )
  24519. *
  24520. * const points = curve.getPoints( 50 );
  24521. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24522. *
  24523. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24524. *
  24525. * // Create the final object to add to the scene
  24526. * const curveObject = new THREE.Line( geometry, material );
  24527. * ```
  24528. *
  24529. * @augments Curve
  24530. */
  24531. class QuadraticBezierCurve extends Curve {
  24532. /**
  24533. * Constructs a new Quadratic Bezier curve.
  24534. *
  24535. * @param {Vector2} [v0] - The start point.
  24536. * @param {Vector2} [v1] - The control point.
  24537. * @param {Vector2} [v2] - The end point.
  24538. */
  24539. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24540. super();
  24541. /**
  24542. * This flag can be used for type testing.
  24543. *
  24544. * @type {boolean}
  24545. * @readonly
  24546. * @default true
  24547. */
  24548. this.isQuadraticBezierCurve = true;
  24549. this.type = 'QuadraticBezierCurve';
  24550. /**
  24551. * The start point.
  24552. *
  24553. * @type {Vector2}
  24554. */
  24555. this.v0 = v0;
  24556. /**
  24557. * The control point.
  24558. *
  24559. * @type {Vector2}
  24560. */
  24561. this.v1 = v1;
  24562. /**
  24563. * The end point.
  24564. *
  24565. * @type {Vector2}
  24566. */
  24567. this.v2 = v2;
  24568. }
  24569. /**
  24570. * Returns a point on the curve.
  24571. *
  24572. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24573. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24574. * @return {Vector2} The position on the curve.
  24575. */
  24576. getPoint( t, optionalTarget = new Vector2() ) {
  24577. const point = optionalTarget;
  24578. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24579. point.set(
  24580. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24581. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24582. );
  24583. return point;
  24584. }
  24585. copy( source ) {
  24586. super.copy( source );
  24587. this.v0.copy( source.v0 );
  24588. this.v1.copy( source.v1 );
  24589. this.v2.copy( source.v2 );
  24590. return this;
  24591. }
  24592. toJSON() {
  24593. const data = super.toJSON();
  24594. data.v0 = this.v0.toArray();
  24595. data.v1 = this.v1.toArray();
  24596. data.v2 = this.v2.toArray();
  24597. return data;
  24598. }
  24599. fromJSON( json ) {
  24600. super.fromJSON( json );
  24601. this.v0.fromArray( json.v0 );
  24602. this.v1.fromArray( json.v1 );
  24603. this.v2.fromArray( json.v2 );
  24604. return this;
  24605. }
  24606. }
  24607. /**
  24608. * A curve representing a 3D Quadratic Bezier curve.
  24609. *
  24610. * @augments Curve
  24611. */
  24612. class QuadraticBezierCurve3 extends Curve {
  24613. /**
  24614. * Constructs a new Quadratic Bezier curve.
  24615. *
  24616. * @param {Vector3} [v0] - The start point.
  24617. * @param {Vector3} [v1] - The control point.
  24618. * @param {Vector3} [v2] - The end point.
  24619. */
  24620. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24621. super();
  24622. /**
  24623. * This flag can be used for type testing.
  24624. *
  24625. * @type {boolean}
  24626. * @readonly
  24627. * @default true
  24628. */
  24629. this.isQuadraticBezierCurve3 = true;
  24630. this.type = 'QuadraticBezierCurve3';
  24631. /**
  24632. * The start point.
  24633. *
  24634. * @type {Vector3}
  24635. */
  24636. this.v0 = v0;
  24637. /**
  24638. * The control point.
  24639. *
  24640. * @type {Vector3}
  24641. */
  24642. this.v1 = v1;
  24643. /**
  24644. * The end point.
  24645. *
  24646. * @type {Vector3}
  24647. */
  24648. this.v2 = v2;
  24649. }
  24650. /**
  24651. * Returns a point on the curve.
  24652. *
  24653. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24654. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24655. * @return {Vector3} The position on the curve.
  24656. */
  24657. getPoint( t, optionalTarget = new Vector3() ) {
  24658. const point = optionalTarget;
  24659. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24660. point.set(
  24661. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24662. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24663. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24664. );
  24665. return point;
  24666. }
  24667. copy( source ) {
  24668. super.copy( source );
  24669. this.v0.copy( source.v0 );
  24670. this.v1.copy( source.v1 );
  24671. this.v2.copy( source.v2 );
  24672. return this;
  24673. }
  24674. toJSON() {
  24675. const data = super.toJSON();
  24676. data.v0 = this.v0.toArray();
  24677. data.v1 = this.v1.toArray();
  24678. data.v2 = this.v2.toArray();
  24679. return data;
  24680. }
  24681. fromJSON( json ) {
  24682. super.fromJSON( json );
  24683. this.v0.fromArray( json.v0 );
  24684. this.v1.fromArray( json.v1 );
  24685. this.v2.fromArray( json.v2 );
  24686. return this;
  24687. }
  24688. }
  24689. /**
  24690. * A curve representing a 2D spline curve.
  24691. *
  24692. * ```js
  24693. * // Create a sine-like wave
  24694. * const curve = new THREE.SplineCurve( [
  24695. * new THREE.Vector2( -10, 0 ),
  24696. * new THREE.Vector2( -5, 5 ),
  24697. * new THREE.Vector2( 0, 0 ),
  24698. * new THREE.Vector2( 5, -5 ),
  24699. * new THREE.Vector2( 10, 0 )
  24700. * ] );
  24701. *
  24702. * const points = curve.getPoints( 50 );
  24703. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24704. *
  24705. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24706. *
  24707. * // Create the final object to add to the scene
  24708. * const splineObject = new THREE.Line( geometry, material );
  24709. * ```
  24710. *
  24711. * @augments Curve
  24712. */
  24713. class SplineCurve extends Curve {
  24714. /**
  24715. * Constructs a new 2D spline curve.
  24716. *
  24717. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24718. */
  24719. constructor( points = [] ) {
  24720. super();
  24721. /**
  24722. * This flag can be used for type testing.
  24723. *
  24724. * @type {boolean}
  24725. * @readonly
  24726. * @default true
  24727. */
  24728. this.isSplineCurve = true;
  24729. this.type = 'SplineCurve';
  24730. /**
  24731. * An array of 2D points defining the curve.
  24732. *
  24733. * @type {Array<Vector2>}
  24734. */
  24735. this.points = points;
  24736. }
  24737. /**
  24738. * Returns a point on the curve.
  24739. *
  24740. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24741. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24742. * @return {Vector2} The position on the curve.
  24743. */
  24744. getPoint( t, optionalTarget = new Vector2() ) {
  24745. const point = optionalTarget;
  24746. const points = this.points;
  24747. const p = ( points.length - 1 ) * t;
  24748. const intPoint = Math.floor( p );
  24749. const weight = p - intPoint;
  24750. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24751. const p1 = points[ intPoint ];
  24752. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24753. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24754. point.set(
  24755. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24756. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24757. );
  24758. return point;
  24759. }
  24760. copy( source ) {
  24761. super.copy( source );
  24762. this.points = [];
  24763. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24764. const point = source.points[ i ];
  24765. this.points.push( point.clone() );
  24766. }
  24767. return this;
  24768. }
  24769. toJSON() {
  24770. const data = super.toJSON();
  24771. data.points = [];
  24772. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24773. const point = this.points[ i ];
  24774. data.points.push( point.toArray() );
  24775. }
  24776. return data;
  24777. }
  24778. fromJSON( json ) {
  24779. super.fromJSON( json );
  24780. this.points = [];
  24781. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24782. const point = json.points[ i ];
  24783. this.points.push( new Vector2().fromArray( point ) );
  24784. }
  24785. return this;
  24786. }
  24787. }
  24788. var Curves = /*#__PURE__*/Object.freeze({
  24789. __proto__: null,
  24790. ArcCurve: ArcCurve,
  24791. CatmullRomCurve3: CatmullRomCurve3,
  24792. CubicBezierCurve: CubicBezierCurve,
  24793. CubicBezierCurve3: CubicBezierCurve3,
  24794. EllipseCurve: EllipseCurve,
  24795. LineCurve: LineCurve,
  24796. LineCurve3: LineCurve3,
  24797. QuadraticBezierCurve: QuadraticBezierCurve,
  24798. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24799. SplineCurve: SplineCurve
  24800. });
  24801. /**
  24802. * A base class extending {@link Curve}. `CurvePath` is simply an
  24803. * array of connected curves, but retains the API of a curve.
  24804. *
  24805. * @augments Curve
  24806. */
  24807. class CurvePath extends Curve {
  24808. /**
  24809. * Constructs a new curve path.
  24810. */
  24811. constructor() {
  24812. super();
  24813. this.type = 'CurvePath';
  24814. /**
  24815. * An array of curves defining the
  24816. * path.
  24817. *
  24818. * @type {Array<Curve>}
  24819. */
  24820. this.curves = [];
  24821. /**
  24822. * Whether the path should automatically be closed
  24823. * by a line curve.
  24824. *
  24825. * @type {boolean}
  24826. * @default false
  24827. */
  24828. this.autoClose = false;
  24829. }
  24830. /**
  24831. * Adds a curve to this curve path.
  24832. *
  24833. * @param {Curve} curve - The curve to add.
  24834. */
  24835. add( curve ) {
  24836. this.curves.push( curve );
  24837. }
  24838. /**
  24839. * Adds a line curve to close the path.
  24840. *
  24841. * @return {CurvePath} A reference to this curve path.
  24842. */
  24843. closePath() {
  24844. // Add a line curve if start and end of lines are not connected
  24845. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24846. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24847. if ( ! startPoint.equals( endPoint ) ) {
  24848. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24849. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24850. }
  24851. return this;
  24852. }
  24853. /**
  24854. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24855. * for the given interpolation factor.
  24856. *
  24857. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24858. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24859. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24860. */
  24861. getPoint( t, optionalTarget ) {
  24862. // To get accurate point with reference to
  24863. // entire path distance at time t,
  24864. // following has to be done:
  24865. // 1. Length of each sub path have to be known
  24866. // 2. Locate and identify type of curve
  24867. // 3. Get t for the curve
  24868. // 4. Return curve.getPointAt(t')
  24869. const d = t * this.getLength();
  24870. const curveLengths = this.getCurveLengths();
  24871. let i = 0;
  24872. // To think about boundaries points.
  24873. while ( i < curveLengths.length ) {
  24874. if ( curveLengths[ i ] >= d ) {
  24875. const diff = curveLengths[ i ] - d;
  24876. const curve = this.curves[ i ];
  24877. const segmentLength = curve.getLength();
  24878. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24879. return curve.getPointAt( u, optionalTarget );
  24880. }
  24881. i ++;
  24882. }
  24883. return null;
  24884. // loop where sum != 0, sum > d , sum+1 <d
  24885. }
  24886. getLength() {
  24887. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24888. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24889. // getPoint() depends on getLength
  24890. const lens = this.getCurveLengths();
  24891. return lens[ lens.length - 1 ];
  24892. }
  24893. updateArcLengths() {
  24894. // cacheLengths must be recalculated.
  24895. this.needsUpdate = true;
  24896. this.cacheLengths = null;
  24897. this.getCurveLengths();
  24898. }
  24899. /**
  24900. * Returns list of cumulative curve lengths of the defined curves.
  24901. *
  24902. * @return {Array<number>} The curve lengths.
  24903. */
  24904. getCurveLengths() {
  24905. // Compute lengths and cache them
  24906. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24907. // We use cache values if curves and cache array are same length
  24908. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24909. return this.cacheLengths;
  24910. }
  24911. // Get length of sub-curve
  24912. // Push sums into cached array
  24913. const lengths = [];
  24914. let sums = 0;
  24915. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24916. sums += this.curves[ i ].getLength();
  24917. lengths.push( sums );
  24918. }
  24919. this.cacheLengths = lengths;
  24920. return lengths;
  24921. }
  24922. getSpacedPoints( divisions = 40 ) {
  24923. const points = [];
  24924. for ( let i = 0; i <= divisions; i ++ ) {
  24925. points.push( this.getPoint( i / divisions ) );
  24926. }
  24927. if ( this.autoClose ) {
  24928. points.push( points[ 0 ] );
  24929. }
  24930. return points;
  24931. }
  24932. getPoints( divisions = 12 ) {
  24933. const points = [];
  24934. let last;
  24935. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24936. const curve = curves[ i ];
  24937. const resolution = curve.isEllipseCurve ? divisions * 2
  24938. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24939. : curve.isSplineCurve ? divisions * curve.points.length
  24940. : divisions;
  24941. const pts = curve.getPoints( resolution );
  24942. for ( let j = 0; j < pts.length; j ++ ) {
  24943. const point = pts[ j ];
  24944. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24945. points.push( point );
  24946. last = point;
  24947. }
  24948. }
  24949. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24950. points.push( points[ 0 ] );
  24951. }
  24952. return points;
  24953. }
  24954. copy( source ) {
  24955. super.copy( source );
  24956. this.curves = [];
  24957. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24958. const curve = source.curves[ i ];
  24959. this.curves.push( curve.clone() );
  24960. }
  24961. this.autoClose = source.autoClose;
  24962. return this;
  24963. }
  24964. toJSON() {
  24965. const data = super.toJSON();
  24966. data.autoClose = this.autoClose;
  24967. data.curves = [];
  24968. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24969. const curve = this.curves[ i ];
  24970. data.curves.push( curve.toJSON() );
  24971. }
  24972. return data;
  24973. }
  24974. fromJSON( json ) {
  24975. super.fromJSON( json );
  24976. this.autoClose = json.autoClose;
  24977. this.curves = [];
  24978. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24979. const curve = json.curves[ i ];
  24980. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24981. }
  24982. return this;
  24983. }
  24984. }
  24985. /**
  24986. * A 2D path representation. The class provides methods for creating paths
  24987. * and contours of 2D shapes similar to the 2D Canvas API.
  24988. *
  24989. * ```js
  24990. * const path = new THREE.Path();
  24991. *
  24992. * path.lineTo( 0, 0.8 );
  24993. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24994. * path.lineTo( 1, 1 );
  24995. *
  24996. * const points = path.getPoints();
  24997. *
  24998. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24999. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  25000. *
  25001. * const line = new THREE.Line( geometry, material );
  25002. * scene.add( line );
  25003. * ```
  25004. *
  25005. * @augments CurvePath
  25006. */
  25007. class Path extends CurvePath {
  25008. /**
  25009. * Constructs a new path.
  25010. *
  25011. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25012. */
  25013. constructor( points ) {
  25014. super();
  25015. this.type = 'Path';
  25016. /**
  25017. * The current offset of the path. Any new curve added will start here.
  25018. *
  25019. * @type {Vector2}
  25020. */
  25021. this.currentPoint = new Vector2();
  25022. if ( points ) {
  25023. this.setFromPoints( points );
  25024. }
  25025. }
  25026. /**
  25027. * Creates a path from the given list of points. The points are added
  25028. * to the path as instances of {@link LineCurve}.
  25029. *
  25030. * @param {Array<Vector2>} points - An array of 2D points.
  25031. * @return {Path} A reference to this path.
  25032. */
  25033. setFromPoints( points ) {
  25034. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25035. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25036. this.lineTo( points[ i ].x, points[ i ].y );
  25037. }
  25038. return this;
  25039. }
  25040. /**
  25041. * Moves {@link Path#currentPoint} to the given point.
  25042. *
  25043. * @param {number} x - The x coordinate.
  25044. * @param {number} y - The y coordinate.
  25045. * @return {Path} A reference to this path.
  25046. */
  25047. moveTo( x, y ) {
  25048. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25049. return this;
  25050. }
  25051. /**
  25052. * Adds an instance of {@link LineCurve} to the path by connecting
  25053. * the current point with the given one.
  25054. *
  25055. * @param {number} x - The x coordinate of the end point.
  25056. * @param {number} y - The y coordinate of the end point.
  25057. * @return {Path} A reference to this path.
  25058. */
  25059. lineTo( x, y ) {
  25060. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25061. this.curves.push( curve );
  25062. this.currentPoint.set( x, y );
  25063. return this;
  25064. }
  25065. /**
  25066. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25067. * the current point with the given one.
  25068. *
  25069. * @param {number} aCPx - The x coordinate of the control point.
  25070. * @param {number} aCPy - The y coordinate of the control point.
  25071. * @param {number} aX - The x coordinate of the end point.
  25072. * @param {number} aY - The y coordinate of the end point.
  25073. * @return {Path} A reference to this path.
  25074. */
  25075. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25076. const curve = new QuadraticBezierCurve(
  25077. this.currentPoint.clone(),
  25078. new Vector2( aCPx, aCPy ),
  25079. new Vector2( aX, aY )
  25080. );
  25081. this.curves.push( curve );
  25082. this.currentPoint.set( aX, aY );
  25083. return this;
  25084. }
  25085. /**
  25086. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25087. * the current point with the given one.
  25088. *
  25089. * @param {number} aCP1x - The x coordinate of the first control point.
  25090. * @param {number} aCP1y - The y coordinate of the first control point.
  25091. * @param {number} aCP2x - The x coordinate of the second control point.
  25092. * @param {number} aCP2y - The y coordinate of the second control point.
  25093. * @param {number} aX - The x coordinate of the end point.
  25094. * @param {number} aY - The y coordinate of the end point.
  25095. * @return {Path} A reference to this path.
  25096. */
  25097. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25098. const curve = new CubicBezierCurve(
  25099. this.currentPoint.clone(),
  25100. new Vector2( aCP1x, aCP1y ),
  25101. new Vector2( aCP2x, aCP2y ),
  25102. new Vector2( aX, aY )
  25103. );
  25104. this.curves.push( curve );
  25105. this.currentPoint.set( aX, aY );
  25106. return this;
  25107. }
  25108. /**
  25109. * Adds an instance of {@link SplineCurve} to the path by connecting
  25110. * the current point with the given list of points.
  25111. *
  25112. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25113. * @return {Path} A reference to this path.
  25114. */
  25115. splineThru( pts ) {
  25116. const npts = [ this.currentPoint.clone() ].concat( pts );
  25117. const curve = new SplineCurve( npts );
  25118. this.curves.push( curve );
  25119. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25120. return this;
  25121. }
  25122. /**
  25123. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25124. * to the current point.
  25125. *
  25126. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25127. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25128. * @param {number} [aRadius=1] - The radius of the arc.
  25129. * @param {number} [aStartAngle=0] - The start angle in radians.
  25130. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25131. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25132. * @return {Path} A reference to this path.
  25133. */
  25134. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25135. const x0 = this.currentPoint.x;
  25136. const y0 = this.currentPoint.y;
  25137. this.absarc( aX + x0, aY + y0, aRadius,
  25138. aStartAngle, aEndAngle, aClockwise );
  25139. return this;
  25140. }
  25141. /**
  25142. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25143. *
  25144. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25145. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25146. * @param {number} [aRadius=1] - The radius of the arc.
  25147. * @param {number} [aStartAngle=0] - The start angle in radians.
  25148. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25149. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25150. * @return {Path} A reference to this path.
  25151. */
  25152. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25153. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25154. return this;
  25155. }
  25156. /**
  25157. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25158. * to the current point
  25159. *
  25160. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25161. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25162. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25163. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25164. * @param {number} [aStartAngle=0] - The start angle in radians.
  25165. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25166. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25167. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25168. * @return {Path} A reference to this path.
  25169. */
  25170. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25171. const x0 = this.currentPoint.x;
  25172. const y0 = this.currentPoint.y;
  25173. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25174. return this;
  25175. }
  25176. /**
  25177. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25178. *
  25179. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25180. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25181. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25182. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25183. * @param {number} [aStartAngle=0] - The start angle in radians.
  25184. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25185. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25186. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25187. * @return {Path} A reference to this path.
  25188. */
  25189. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25190. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25191. if ( this.curves.length > 0 ) {
  25192. // if a previous curve is present, attempt to join
  25193. const firstPoint = curve.getPoint( 0 );
  25194. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25195. this.lineTo( firstPoint.x, firstPoint.y );
  25196. }
  25197. }
  25198. this.curves.push( curve );
  25199. const lastPoint = curve.getPoint( 1 );
  25200. this.currentPoint.copy( lastPoint );
  25201. return this;
  25202. }
  25203. copy( source ) {
  25204. super.copy( source );
  25205. this.currentPoint.copy( source.currentPoint );
  25206. return this;
  25207. }
  25208. toJSON() {
  25209. const data = super.toJSON();
  25210. data.currentPoint = this.currentPoint.toArray();
  25211. return data;
  25212. }
  25213. fromJSON( json ) {
  25214. super.fromJSON( json );
  25215. this.currentPoint.fromArray( json.currentPoint );
  25216. return this;
  25217. }
  25218. }
  25219. /**
  25220. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25221. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25222. * points, or to get triangulated faces.
  25223. *
  25224. * ```js
  25225. * const heartShape = new THREE.Shape();
  25226. *
  25227. * heartShape.moveTo( 25, 25 );
  25228. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25229. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25230. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25231. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25232. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25233. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25234. *
  25235. * const extrudeSettings = {
  25236. * depth: 8,
  25237. * bevelEnabled: true,
  25238. * bevelSegments: 2,
  25239. * steps: 2,
  25240. * bevelSize: 1,
  25241. * bevelThickness: 1
  25242. * };
  25243. *
  25244. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25245. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25246. * ```
  25247. *
  25248. * @augments Path
  25249. */
  25250. class Shape extends Path {
  25251. /**
  25252. * Constructs a new shape.
  25253. *
  25254. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25255. */
  25256. constructor( points ) {
  25257. super( points );
  25258. /**
  25259. * The UUID of the shape.
  25260. *
  25261. * @type {string}
  25262. * @readonly
  25263. */
  25264. this.uuid = generateUUID();
  25265. this.type = 'Shape';
  25266. /**
  25267. * Defines the holes in the shape. Hole definitions must use the
  25268. * opposite winding order (CW/CCW) than the outer shape.
  25269. *
  25270. * @type {Array<Path>}
  25271. * @readonly
  25272. */
  25273. this.holes = [];
  25274. }
  25275. /**
  25276. * Returns an array representing each contour of the holes
  25277. * as a list of 2D points.
  25278. *
  25279. * @param {number} divisions - The fineness of the result.
  25280. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25281. */
  25282. getPointsHoles( divisions ) {
  25283. const holesPts = [];
  25284. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25285. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25286. }
  25287. return holesPts;
  25288. }
  25289. // get points of shape and holes (keypoints based on segments parameter)
  25290. /**
  25291. * Returns an object that holds contour data for the shape and its holes as
  25292. * arrays of 2D points.
  25293. *
  25294. * @param {number} divisions - The fineness of the result.
  25295. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25296. */
  25297. extractPoints( divisions ) {
  25298. return {
  25299. shape: this.getPoints( divisions ),
  25300. holes: this.getPointsHoles( divisions )
  25301. };
  25302. }
  25303. copy( source ) {
  25304. super.copy( source );
  25305. this.holes = [];
  25306. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25307. const hole = source.holes[ i ];
  25308. this.holes.push( hole.clone() );
  25309. }
  25310. return this;
  25311. }
  25312. toJSON() {
  25313. const data = super.toJSON();
  25314. data.uuid = this.uuid;
  25315. data.holes = [];
  25316. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25317. const hole = this.holes[ i ];
  25318. data.holes.push( hole.toJSON() );
  25319. }
  25320. return data;
  25321. }
  25322. fromJSON( json ) {
  25323. super.fromJSON( json );
  25324. this.uuid = json.uuid;
  25325. this.holes = [];
  25326. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25327. const hole = json.holes[ i ];
  25328. this.holes.push( new Path().fromJSON( hole ) );
  25329. }
  25330. return this;
  25331. }
  25332. }
  25333. /* eslint-disable */
  25334. // copy of mapbox/earcut version 3.0.2
  25335. // https://github.com/mapbox/earcut/tree/v3.0.2
  25336. function earcut(data, holeIndices, dim = 2) {
  25337. const hasHoles = holeIndices && holeIndices.length;
  25338. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25339. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25340. const triangles = [];
  25341. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25342. let minX, minY, invSize;
  25343. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25344. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25345. if (data.length > 80 * dim) {
  25346. minX = data[0];
  25347. minY = data[1];
  25348. let maxX = minX;
  25349. let maxY = minY;
  25350. for (let i = dim; i < outerLen; i += dim) {
  25351. const x = data[i];
  25352. const y = data[i + 1];
  25353. if (x < minX) minX = x;
  25354. if (y < minY) minY = y;
  25355. if (x > maxX) maxX = x;
  25356. if (y > maxY) maxY = y;
  25357. }
  25358. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25359. invSize = Math.max(maxX - minX, maxY - minY);
  25360. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25361. }
  25362. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25363. return triangles;
  25364. }
  25365. // create a circular doubly linked list from polygon points in the specified winding order
  25366. function linkedList(data, start, end, dim, clockwise) {
  25367. let last;
  25368. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25369. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25370. } else {
  25371. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25372. }
  25373. if (last && equals(last, last.next)) {
  25374. removeNode(last);
  25375. last = last.next;
  25376. }
  25377. return last;
  25378. }
  25379. // eliminate colinear or duplicate points
  25380. function filterPoints(start, end) {
  25381. if (!start) return start;
  25382. if (!end) end = start;
  25383. let p = start,
  25384. again;
  25385. do {
  25386. again = false;
  25387. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25388. removeNode(p);
  25389. p = end = p.prev;
  25390. if (p === p.next) break;
  25391. again = true;
  25392. } else {
  25393. p = p.next;
  25394. }
  25395. } while (again || p !== end);
  25396. return end;
  25397. }
  25398. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25399. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25400. if (!ear) return;
  25401. // interlink polygon nodes in z-order
  25402. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25403. let stop = ear;
  25404. // iterate through ears, slicing them one by one
  25405. while (ear.prev !== ear.next) {
  25406. const prev = ear.prev;
  25407. const next = ear.next;
  25408. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25409. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25410. removeNode(ear);
  25411. // skipping the next vertex leads to less sliver triangles
  25412. ear = next.next;
  25413. stop = next.next;
  25414. continue;
  25415. }
  25416. ear = next;
  25417. // if we looped through the whole remaining polygon and can't find any more ears
  25418. if (ear === stop) {
  25419. // try filtering points and slicing again
  25420. if (!pass) {
  25421. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25422. // if this didn't work, try curing all small self-intersections locally
  25423. } else if (pass === 1) {
  25424. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25425. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25426. // as a last resort, try splitting the remaining polygon into two
  25427. } else if (pass === 2) {
  25428. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25429. }
  25430. break;
  25431. }
  25432. }
  25433. }
  25434. // check whether a polygon node forms a valid ear with adjacent nodes
  25435. function isEar(ear) {
  25436. const a = ear.prev,
  25437. b = ear,
  25438. c = ear.next;
  25439. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25440. // now make sure we don't have other points inside the potential ear
  25441. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25442. // triangle bbox
  25443. const x0 = Math.min(ax, bx, cx),
  25444. y0 = Math.min(ay, by, cy),
  25445. x1 = Math.max(ax, bx, cx),
  25446. y1 = Math.max(ay, by, cy);
  25447. let p = c.next;
  25448. while (p !== a) {
  25449. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25450. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25451. area(p.prev, p, p.next) >= 0) return false;
  25452. p = p.next;
  25453. }
  25454. return true;
  25455. }
  25456. function isEarHashed(ear, minX, minY, invSize) {
  25457. const a = ear.prev,
  25458. b = ear,
  25459. c = ear.next;
  25460. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25461. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25462. // triangle bbox
  25463. const x0 = Math.min(ax, bx, cx),
  25464. y0 = Math.min(ay, by, cy),
  25465. x1 = Math.max(ax, bx, cx),
  25466. y1 = Math.max(ay, by, cy);
  25467. // z-order range for the current triangle bbox;
  25468. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25469. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25470. let p = ear.prevZ,
  25471. n = ear.nextZ;
  25472. // look for points inside the triangle in both directions
  25473. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25474. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25475. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25476. p = p.prevZ;
  25477. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25478. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25479. n = n.nextZ;
  25480. }
  25481. // look for remaining points in decreasing z-order
  25482. while (p && p.z >= minZ) {
  25483. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25484. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25485. p = p.prevZ;
  25486. }
  25487. // look for remaining points in increasing z-order
  25488. while (n && n.z <= maxZ) {
  25489. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25490. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25491. n = n.nextZ;
  25492. }
  25493. return true;
  25494. }
  25495. // go through all polygon nodes and cure small local self-intersections
  25496. function cureLocalIntersections(start, triangles) {
  25497. let p = start;
  25498. do {
  25499. const a = p.prev,
  25500. b = p.next.next;
  25501. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25502. triangles.push(a.i, p.i, b.i);
  25503. // remove two nodes involved
  25504. removeNode(p);
  25505. removeNode(p.next);
  25506. p = start = b;
  25507. }
  25508. p = p.next;
  25509. } while (p !== start);
  25510. return filterPoints(p);
  25511. }
  25512. // try splitting polygon into two and triangulate them independently
  25513. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25514. // look for a valid diagonal that divides the polygon into two
  25515. let a = start;
  25516. do {
  25517. let b = a.next.next;
  25518. while (b !== a.prev) {
  25519. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25520. // split the polygon in two by the diagonal
  25521. let c = splitPolygon(a, b);
  25522. // filter colinear points around the cuts
  25523. a = filterPoints(a, a.next);
  25524. c = filterPoints(c, c.next);
  25525. // run earcut on each half
  25526. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25527. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25528. return;
  25529. }
  25530. b = b.next;
  25531. }
  25532. a = a.next;
  25533. } while (a !== start);
  25534. }
  25535. // link every hole into the outer loop, producing a single-ring polygon without holes
  25536. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25537. const queue = [];
  25538. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25539. const start = holeIndices[i] * dim;
  25540. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25541. const list = linkedList(data, start, end, dim, false);
  25542. if (list === list.next) list.steiner = true;
  25543. queue.push(getLeftmost(list));
  25544. }
  25545. queue.sort(compareXYSlope);
  25546. // process holes from left to right
  25547. for (let i = 0; i < queue.length; i++) {
  25548. outerNode = eliminateHole(queue[i], outerNode);
  25549. }
  25550. return outerNode;
  25551. }
  25552. function compareXYSlope(a, b) {
  25553. let result = a.x - b.x;
  25554. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25555. // the bridge to the outer shell is always the point that they meet at.
  25556. if (result === 0) {
  25557. result = a.y - b.y;
  25558. if (result === 0) {
  25559. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25560. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25561. result = aSlope - bSlope;
  25562. }
  25563. }
  25564. return result;
  25565. }
  25566. // find a bridge between vertices that connects hole with an outer ring and link it
  25567. function eliminateHole(hole, outerNode) {
  25568. const bridge = findHoleBridge(hole, outerNode);
  25569. if (!bridge) {
  25570. return outerNode;
  25571. }
  25572. const bridgeReverse = splitPolygon(bridge, hole);
  25573. // filter collinear points around the cuts
  25574. filterPoints(bridgeReverse, bridgeReverse.next);
  25575. return filterPoints(bridge, bridge.next);
  25576. }
  25577. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25578. function findHoleBridge(hole, outerNode) {
  25579. let p = outerNode;
  25580. const hx = hole.x;
  25581. const hy = hole.y;
  25582. let qx = -Infinity;
  25583. let m;
  25584. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25585. // segment's endpoint with lesser x will be potential connection point
  25586. // unless they intersect at a vertex, then choose the vertex
  25587. if (equals(hole, p)) return p;
  25588. do {
  25589. if (equals(hole, p.next)) return p.next;
  25590. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25591. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25592. if (x <= hx && x > qx) {
  25593. qx = x;
  25594. m = p.x < p.next.x ? p : p.next;
  25595. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25596. }
  25597. }
  25598. p = p.next;
  25599. } while (p !== outerNode);
  25600. if (!m) return null;
  25601. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25602. // if there are no points found, we have a valid connection;
  25603. // otherwise choose the point of the minimum angle with the ray as connection point
  25604. const stop = m;
  25605. const mx = m.x;
  25606. const my = m.y;
  25607. let tanMin = Infinity;
  25608. p = m;
  25609. do {
  25610. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25611. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25612. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25613. if (locallyInside(p, hole) &&
  25614. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25615. m = p;
  25616. tanMin = tan;
  25617. }
  25618. }
  25619. p = p.next;
  25620. } while (p !== stop);
  25621. return m;
  25622. }
  25623. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25624. function sectorContainsSector(m, p) {
  25625. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25626. }
  25627. // interlink polygon nodes in z-order
  25628. function indexCurve(start, minX, minY, invSize) {
  25629. let p = start;
  25630. do {
  25631. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25632. p.prevZ = p.prev;
  25633. p.nextZ = p.next;
  25634. p = p.next;
  25635. } while (p !== start);
  25636. p.prevZ.nextZ = null;
  25637. p.prevZ = null;
  25638. sortLinked(p);
  25639. }
  25640. // Simon Tatham's linked list merge sort algorithm
  25641. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25642. function sortLinked(list) {
  25643. let numMerges;
  25644. let inSize = 1;
  25645. do {
  25646. let p = list;
  25647. let e;
  25648. list = null;
  25649. let tail = null;
  25650. numMerges = 0;
  25651. while (p) {
  25652. numMerges++;
  25653. let q = p;
  25654. let pSize = 0;
  25655. for (let i = 0; i < inSize; i++) {
  25656. pSize++;
  25657. q = q.nextZ;
  25658. if (!q) break;
  25659. }
  25660. let qSize = inSize;
  25661. while (pSize > 0 || (qSize > 0 && q)) {
  25662. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25663. e = p;
  25664. p = p.nextZ;
  25665. pSize--;
  25666. } else {
  25667. e = q;
  25668. q = q.nextZ;
  25669. qSize--;
  25670. }
  25671. if (tail) tail.nextZ = e;
  25672. else list = e;
  25673. e.prevZ = tail;
  25674. tail = e;
  25675. }
  25676. p = q;
  25677. }
  25678. tail.nextZ = null;
  25679. inSize *= 2;
  25680. } while (numMerges > 1);
  25681. return list;
  25682. }
  25683. // z-order of a point given coords and inverse of the longer side of data bbox
  25684. function zOrder(x, y, minX, minY, invSize) {
  25685. // coords are transformed into non-negative 15-bit integer range
  25686. x = (x - minX) * invSize | 0;
  25687. y = (y - minY) * invSize | 0;
  25688. x = (x | (x << 8)) & 0x00FF00FF;
  25689. x = (x | (x << 4)) & 0x0F0F0F0F;
  25690. x = (x | (x << 2)) & 0x33333333;
  25691. x = (x | (x << 1)) & 0x55555555;
  25692. y = (y | (y << 8)) & 0x00FF00FF;
  25693. y = (y | (y << 4)) & 0x0F0F0F0F;
  25694. y = (y | (y << 2)) & 0x33333333;
  25695. y = (y | (y << 1)) & 0x55555555;
  25696. return x | (y << 1);
  25697. }
  25698. // find the leftmost node of a polygon ring
  25699. function getLeftmost(start) {
  25700. let p = start,
  25701. leftmost = start;
  25702. do {
  25703. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25704. p = p.next;
  25705. } while (p !== start);
  25706. return leftmost;
  25707. }
  25708. // check if a point lies within a convex triangle
  25709. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25710. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25711. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25712. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25713. }
  25714. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25715. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25716. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25717. }
  25718. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25719. function isValidDiagonal(a, b) {
  25720. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25721. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25722. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25723. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25724. }
  25725. // signed area of a triangle
  25726. function area(p, q, r) {
  25727. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25728. }
  25729. // check if two points are equal
  25730. function equals(p1, p2) {
  25731. return p1.x === p2.x && p1.y === p2.y;
  25732. }
  25733. // check if two segments intersect
  25734. function intersects(p1, q1, p2, q2) {
  25735. const o1 = sign(area(p1, q1, p2));
  25736. const o2 = sign(area(p1, q1, q2));
  25737. const o3 = sign(area(p2, q2, p1));
  25738. const o4 = sign(area(p2, q2, q1));
  25739. if (o1 !== o2 && o3 !== o4) return true; // general case
  25740. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25741. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25742. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25743. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25744. return false;
  25745. }
  25746. // for collinear points p, q, r, check if point q lies on segment pr
  25747. function onSegment(p, q, r) {
  25748. 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);
  25749. }
  25750. function sign(num) {
  25751. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25752. }
  25753. // check if a polygon diagonal intersects any polygon segments
  25754. function intersectsPolygon(a, b) {
  25755. let p = a;
  25756. do {
  25757. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25758. intersects(p, p.next, a, b)) return true;
  25759. p = p.next;
  25760. } while (p !== a);
  25761. return false;
  25762. }
  25763. // check if a polygon diagonal is locally inside the polygon
  25764. function locallyInside(a, b) {
  25765. return area(a.prev, a, a.next) < 0 ?
  25766. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25767. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25768. }
  25769. // check if the middle point of a polygon diagonal is inside the polygon
  25770. function middleInside(a, b) {
  25771. let p = a;
  25772. let inside = false;
  25773. const px = (a.x + b.x) / 2;
  25774. const py = (a.y + b.y) / 2;
  25775. do {
  25776. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25777. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25778. inside = !inside;
  25779. p = p.next;
  25780. } while (p !== a);
  25781. return inside;
  25782. }
  25783. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25784. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25785. function splitPolygon(a, b) {
  25786. const a2 = createNode(a.i, a.x, a.y),
  25787. b2 = createNode(b.i, b.x, b.y),
  25788. an = a.next,
  25789. bp = b.prev;
  25790. a.next = b;
  25791. b.prev = a;
  25792. a2.next = an;
  25793. an.prev = a2;
  25794. b2.next = a2;
  25795. a2.prev = b2;
  25796. bp.next = b2;
  25797. b2.prev = bp;
  25798. return b2;
  25799. }
  25800. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25801. function insertNode(i, x, y, last) {
  25802. const p = createNode(i, x, y);
  25803. if (!last) {
  25804. p.prev = p;
  25805. p.next = p;
  25806. } else {
  25807. p.next = last.next;
  25808. p.prev = last;
  25809. last.next.prev = p;
  25810. last.next = p;
  25811. }
  25812. return p;
  25813. }
  25814. function removeNode(p) {
  25815. p.next.prev = p.prev;
  25816. p.prev.next = p.next;
  25817. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25818. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25819. }
  25820. function createNode(i, x, y) {
  25821. return {
  25822. i, // vertex index in coordinates array
  25823. x, y, // vertex coordinates
  25824. prev: null, // previous and next vertex nodes in a polygon ring
  25825. next: null,
  25826. z: 0, // z-order curve value
  25827. prevZ: null, // previous and next nodes in z-order
  25828. nextZ: null,
  25829. steiner: false // indicates whether this is a steiner point
  25830. };
  25831. }
  25832. function signedArea(data, start, end, dim) {
  25833. let sum = 0;
  25834. for (let i = start, j = end - dim; i < end; i += dim) {
  25835. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25836. j = i;
  25837. }
  25838. return sum;
  25839. }
  25840. /**
  25841. * An implementation of the earcut polygon triangulation algorithm.
  25842. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25843. *
  25844. * @see https://github.com/mapbox/earcut
  25845. */
  25846. class Earcut {
  25847. /**
  25848. * Triangulates the given shape definition by returning an array of triangles.
  25849. *
  25850. * @param {Array<number>} data - An array with 2D points.
  25851. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25852. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25853. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25854. * representing vertex indices.
  25855. */
  25856. static triangulate( data, holeIndices, dim = 2 ) {
  25857. return earcut( data, holeIndices, dim );
  25858. }
  25859. }
  25860. /**
  25861. * A class containing utility functions for shapes.
  25862. *
  25863. * @hideconstructor
  25864. */
  25865. class ShapeUtils {
  25866. /**
  25867. * Calculate area of a ( 2D ) contour polygon.
  25868. *
  25869. * @param {Array<Vector2>} contour - An array of 2D points.
  25870. * @return {number} The area.
  25871. */
  25872. static area( contour ) {
  25873. const n = contour.length;
  25874. let a = 0.0;
  25875. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25876. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25877. }
  25878. return a * 0.5;
  25879. }
  25880. /**
  25881. * Returns `true` if the given contour uses a clockwise winding order.
  25882. *
  25883. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25884. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25885. */
  25886. static isClockWise( pts ) {
  25887. return ShapeUtils.area( pts ) < 0;
  25888. }
  25889. /**
  25890. * Triangulates the given shape definition.
  25891. *
  25892. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25893. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25894. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25895. */
  25896. static triangulateShape( contour, holes ) {
  25897. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25898. const holeIndices = []; // array of hole indices
  25899. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25900. removeDupEndPts( contour );
  25901. addContour( vertices, contour );
  25902. //
  25903. let holeIndex = contour.length;
  25904. holes.forEach( removeDupEndPts );
  25905. for ( let i = 0; i < holes.length; i ++ ) {
  25906. holeIndices.push( holeIndex );
  25907. holeIndex += holes[ i ].length;
  25908. addContour( vertices, holes[ i ] );
  25909. }
  25910. //
  25911. const triangles = Earcut.triangulate( vertices, holeIndices );
  25912. //
  25913. for ( let i = 0; i < triangles.length; i += 3 ) {
  25914. faces.push( triangles.slice( i, i + 3 ) );
  25915. }
  25916. return faces;
  25917. }
  25918. }
  25919. function removeDupEndPts( points ) {
  25920. const l = points.length;
  25921. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25922. points.pop();
  25923. }
  25924. }
  25925. function addContour( vertices, contour ) {
  25926. for ( let i = 0; i < contour.length; i ++ ) {
  25927. vertices.push( contour[ i ].x );
  25928. vertices.push( contour[ i ].y );
  25929. }
  25930. }
  25931. /**
  25932. * Creates extruded geometry from a path shape.
  25933. *
  25934. * ```js
  25935. * const length = 12, width = 8;
  25936. *
  25937. * const shape = new THREE.Shape();
  25938. * shape.moveTo( 0,0 );
  25939. * shape.lineTo( 0, width );
  25940. * shape.lineTo( length, width );
  25941. * shape.lineTo( length, 0 );
  25942. * shape.lineTo( 0, 0 );
  25943. *
  25944. * const geometry = new THREE.ExtrudeGeometry( shape );
  25945. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25946. * const mesh = new THREE.Mesh( geometry, material ) ;
  25947. * scene.add( mesh );
  25948. * ```
  25949. *
  25950. * @augments BufferGeometry
  25951. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25952. */
  25953. class ExtrudeGeometry extends BufferGeometry {
  25954. /**
  25955. * Constructs a new extrude geometry.
  25956. *
  25957. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25958. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25959. */
  25960. 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 = {} ) {
  25961. super();
  25962. this.type = 'ExtrudeGeometry';
  25963. /**
  25964. * Holds the constructor parameters that have been
  25965. * used to generate the geometry. Any modification
  25966. * after instantiation does not change the geometry.
  25967. *
  25968. * @type {Object}
  25969. */
  25970. this.parameters = {
  25971. shapes: shapes,
  25972. options: options
  25973. };
  25974. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25975. const scope = this;
  25976. const verticesArray = [];
  25977. const uvArray = [];
  25978. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25979. const shape = shapes[ i ];
  25980. addShape( shape );
  25981. }
  25982. // build geometry
  25983. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25984. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25985. this.computeVertexNormals();
  25986. // functions
  25987. function addShape( shape ) {
  25988. const placeholder = [];
  25989. // options
  25990. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25991. const steps = options.steps !== undefined ? options.steps : 1;
  25992. const depth = options.depth !== undefined ? options.depth : 1;
  25993. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25994. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25995. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25996. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25997. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25998. const extrudePath = options.extrudePath;
  25999. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  26000. //
  26001. let extrudePts, extrudeByPath = false;
  26002. let splineTube, binormal, normal, position2;
  26003. if ( extrudePath ) {
  26004. extrudePts = extrudePath.getSpacedPoints( steps );
  26005. extrudeByPath = true;
  26006. bevelEnabled = false; // bevels not supported for path extrusion
  26007. // SETUP TNB variables
  26008. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26009. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26010. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26011. binormal = new Vector3();
  26012. normal = new Vector3();
  26013. position2 = new Vector3();
  26014. }
  26015. // Safeguards if bevels are not enabled
  26016. if ( ! bevelEnabled ) {
  26017. bevelSegments = 0;
  26018. bevelThickness = 0;
  26019. bevelSize = 0;
  26020. bevelOffset = 0;
  26021. }
  26022. // Variables initialization
  26023. const shapePoints = shape.extractPoints( curveSegments );
  26024. let vertices = shapePoints.shape;
  26025. const holes = shapePoints.holes;
  26026. const reverse = ! ShapeUtils.isClockWise( vertices );
  26027. if ( reverse ) {
  26028. vertices = vertices.reverse();
  26029. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26030. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26031. const ahole = holes[ h ];
  26032. if ( ShapeUtils.isClockWise( ahole ) ) {
  26033. holes[ h ] = ahole.reverse();
  26034. }
  26035. }
  26036. }
  26037. /**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.
  26038. * @param {Array<Vector2>} points
  26039. */
  26040. function mergeOverlappingPoints( points ) {
  26041. const THRESHOLD = 1e-10;
  26042. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26043. let prevPos = points[ 0 ];
  26044. for ( let i = 1; i <= points.length; i ++ ) {
  26045. const currentIndex = i % points.length;
  26046. const currentPos = points[ currentIndex ];
  26047. const dx = currentPos.x - prevPos.x;
  26048. const dy = currentPos.y - prevPos.y;
  26049. const distSq = dx * dx + dy * dy;
  26050. const scalingFactorSqrt = Math.max(
  26051. Math.abs( currentPos.x ),
  26052. Math.abs( currentPos.y ),
  26053. Math.abs( prevPos.x ),
  26054. Math.abs( prevPos.y )
  26055. );
  26056. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26057. if ( distSq <= thresholdSqScaled ) {
  26058. points.splice( currentIndex, 1 );
  26059. i --;
  26060. continue;
  26061. }
  26062. prevPos = currentPos;
  26063. }
  26064. }
  26065. mergeOverlappingPoints( vertices );
  26066. holes.forEach( mergeOverlappingPoints );
  26067. const numHoles = holes.length;
  26068. /* Vertices */
  26069. const contour = vertices; // vertices has all points but contour has only points of circumference
  26070. for ( let h = 0; h < numHoles; h ++ ) {
  26071. const ahole = holes[ h ];
  26072. vertices = vertices.concat( ahole );
  26073. }
  26074. function scalePt2( pt, vec, size ) {
  26075. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26076. return pt.clone().addScaledVector( vec, size );
  26077. }
  26078. const vlen = vertices.length;
  26079. // Find directions for point movement
  26080. function getBevelVec( inPt, inPrev, inNext ) {
  26081. // computes for inPt the corresponding point inPt' on a new contour
  26082. // shifted by 1 unit (length of normalized vector) to the left
  26083. // if we walk along contour clockwise, this new contour is outside the old one
  26084. //
  26085. // inPt' is the intersection of the two lines parallel to the two
  26086. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26087. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26088. // good reading for geometry algorithms (here: line-line intersection)
  26089. // http://geomalgorithms.com/a05-_intersect-1.html
  26090. const v_prev_x = inPt.x - inPrev.x,
  26091. v_prev_y = inPt.y - inPrev.y;
  26092. const v_next_x = inNext.x - inPt.x,
  26093. v_next_y = inNext.y - inPt.y;
  26094. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26095. // check for collinear edges
  26096. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26097. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26098. // not collinear
  26099. // length of vectors for normalizing
  26100. const v_prev_len = Math.sqrt( v_prev_lensq );
  26101. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26102. // shift adjacent points by unit vectors to the left
  26103. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26104. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26105. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26106. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26107. // scaling factor for v_prev to intersection point
  26108. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26109. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26110. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26111. // vector from inPt to intersection point
  26112. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26113. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26114. // Don't normalize!, otherwise sharp corners become ugly
  26115. // but prevent crazy spikes
  26116. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26117. if ( v_trans_lensq <= 2 ) {
  26118. return new Vector2( v_trans_x, v_trans_y );
  26119. } else {
  26120. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26121. }
  26122. } else {
  26123. // handle special case of collinear edges
  26124. let direction_eq = false; // assumes: opposite
  26125. if ( v_prev_x > Number.EPSILON ) {
  26126. if ( v_next_x > Number.EPSILON ) {
  26127. direction_eq = true;
  26128. }
  26129. } else {
  26130. if ( v_prev_x < - Number.EPSILON ) {
  26131. if ( v_next_x < - Number.EPSILON ) {
  26132. direction_eq = true;
  26133. }
  26134. } else {
  26135. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26136. direction_eq = true;
  26137. }
  26138. }
  26139. }
  26140. if ( direction_eq ) {
  26141. // log("Warning: lines are a straight sequence");
  26142. v_trans_x = - v_prev_y;
  26143. v_trans_y = v_prev_x;
  26144. shrink_by = Math.sqrt( v_prev_lensq );
  26145. } else {
  26146. // log("Warning: lines are a straight spike");
  26147. v_trans_x = v_prev_x;
  26148. v_trans_y = v_prev_y;
  26149. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26150. }
  26151. }
  26152. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26153. }
  26154. const contourMovements = [];
  26155. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26156. if ( j === il ) j = 0;
  26157. if ( k === il ) k = 0;
  26158. // (j)---(i)---(k)
  26159. // log('i,j,k', i, j , k)
  26160. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26161. }
  26162. const holesMovements = [];
  26163. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26164. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26165. const ahole = holes[ h ];
  26166. oneHoleMovements = [];
  26167. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26168. if ( j === il ) j = 0;
  26169. if ( k === il ) k = 0;
  26170. // (j)---(i)---(k)
  26171. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26172. }
  26173. holesMovements.push( oneHoleMovements );
  26174. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26175. }
  26176. let faces;
  26177. if ( bevelSegments === 0 ) {
  26178. faces = ShapeUtils.triangulateShape( contour, holes );
  26179. } else {
  26180. const contractedContourVertices = [];
  26181. const expandedHoleVertices = [];
  26182. // Loop bevelSegments, 1 for the front, 1 for the back
  26183. for ( let b = 0; b < bevelSegments; b ++ ) {
  26184. //for ( b = bevelSegments; b > 0; b -- ) {
  26185. const t = b / bevelSegments;
  26186. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26187. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26188. // contract shape
  26189. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26190. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26191. v( vert.x, vert.y, - z );
  26192. if ( t === 0 ) contractedContourVertices.push( vert );
  26193. }
  26194. // expand holes
  26195. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26196. const ahole = holes[ h ];
  26197. oneHoleMovements = holesMovements[ h ];
  26198. const oneHoleVertices = [];
  26199. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26200. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26201. v( vert.x, vert.y, - z );
  26202. if ( t === 0 ) oneHoleVertices.push( vert );
  26203. }
  26204. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26205. }
  26206. }
  26207. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26208. }
  26209. const flen = faces.length;
  26210. const bs = bevelSize + bevelOffset;
  26211. // Back facing vertices
  26212. for ( let i = 0; i < vlen; i ++ ) {
  26213. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26214. if ( ! extrudeByPath ) {
  26215. v( vert.x, vert.y, 0 );
  26216. } else {
  26217. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26218. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26219. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26220. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26221. v( position2.x, position2.y, position2.z );
  26222. }
  26223. }
  26224. // Add stepped vertices...
  26225. // Including front facing vertices
  26226. for ( let s = 1; s <= steps; s ++ ) {
  26227. for ( let i = 0; i < vlen; i ++ ) {
  26228. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26229. if ( ! extrudeByPath ) {
  26230. v( vert.x, vert.y, depth / steps * s );
  26231. } else {
  26232. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26233. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26234. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26235. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26236. v( position2.x, position2.y, position2.z );
  26237. }
  26238. }
  26239. }
  26240. // Add bevel segments planes
  26241. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26242. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26243. const t = b / bevelSegments;
  26244. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26245. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26246. // contract shape
  26247. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26248. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26249. v( vert.x, vert.y, depth + z );
  26250. }
  26251. // expand holes
  26252. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26253. const ahole = holes[ h ];
  26254. oneHoleMovements = holesMovements[ h ];
  26255. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26256. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26257. if ( ! extrudeByPath ) {
  26258. v( vert.x, vert.y, depth + z );
  26259. } else {
  26260. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26261. }
  26262. }
  26263. }
  26264. }
  26265. /* Faces */
  26266. // Top and bottom faces
  26267. buildLidFaces();
  26268. // Sides faces
  26269. buildSideFaces();
  26270. ///// Internal functions
  26271. function buildLidFaces() {
  26272. const start = verticesArray.length / 3;
  26273. if ( bevelEnabled ) {
  26274. let layer = 0; // steps + 1
  26275. let offset = vlen * layer;
  26276. // Bottom faces
  26277. for ( let i = 0; i < flen; i ++ ) {
  26278. const face = faces[ i ];
  26279. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26280. }
  26281. layer = steps + bevelSegments * 2;
  26282. offset = vlen * layer;
  26283. // Top faces
  26284. for ( let i = 0; i < flen; i ++ ) {
  26285. const face = faces[ i ];
  26286. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26287. }
  26288. } else {
  26289. // Bottom faces
  26290. for ( let i = 0; i < flen; i ++ ) {
  26291. const face = faces[ i ];
  26292. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26293. }
  26294. // Top faces
  26295. for ( let i = 0; i < flen; i ++ ) {
  26296. const face = faces[ i ];
  26297. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26298. }
  26299. }
  26300. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26301. }
  26302. // Create faces for the z-sides of the shape
  26303. function buildSideFaces() {
  26304. const start = verticesArray.length / 3;
  26305. let layeroffset = 0;
  26306. sidewalls( contour, layeroffset );
  26307. layeroffset += contour.length;
  26308. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26309. const ahole = holes[ h ];
  26310. sidewalls( ahole, layeroffset );
  26311. //, true
  26312. layeroffset += ahole.length;
  26313. }
  26314. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26315. }
  26316. function sidewalls( contour, layeroffset ) {
  26317. let i = contour.length;
  26318. while ( -- i >= 0 ) {
  26319. const j = i;
  26320. let k = i - 1;
  26321. if ( k < 0 ) k = contour.length - 1;
  26322. //log('b', i,j, i-1, k,vertices.length);
  26323. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26324. const slen1 = vlen * s;
  26325. const slen2 = vlen * ( s + 1 );
  26326. const a = layeroffset + j + slen1,
  26327. b = layeroffset + k + slen1,
  26328. c = layeroffset + k + slen2,
  26329. d = layeroffset + j + slen2;
  26330. f4( a, b, c, d );
  26331. }
  26332. }
  26333. }
  26334. function v( x, y, z ) {
  26335. placeholder.push( x );
  26336. placeholder.push( y );
  26337. placeholder.push( z );
  26338. }
  26339. function f3( a, b, c ) {
  26340. addVertex( a );
  26341. addVertex( b );
  26342. addVertex( c );
  26343. const nextIndex = verticesArray.length / 3;
  26344. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26345. addUV( uvs[ 0 ] );
  26346. addUV( uvs[ 1 ] );
  26347. addUV( uvs[ 2 ] );
  26348. }
  26349. function f4( a, b, c, d ) {
  26350. addVertex( a );
  26351. addVertex( b );
  26352. addVertex( d );
  26353. addVertex( b );
  26354. addVertex( c );
  26355. addVertex( d );
  26356. const nextIndex = verticesArray.length / 3;
  26357. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26358. addUV( uvs[ 0 ] );
  26359. addUV( uvs[ 1 ] );
  26360. addUV( uvs[ 3 ] );
  26361. addUV( uvs[ 1 ] );
  26362. addUV( uvs[ 2 ] );
  26363. addUV( uvs[ 3 ] );
  26364. }
  26365. function addVertex( index ) {
  26366. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26367. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26368. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26369. }
  26370. function addUV( vector2 ) {
  26371. uvArray.push( vector2.x );
  26372. uvArray.push( vector2.y );
  26373. }
  26374. }
  26375. }
  26376. copy( source ) {
  26377. super.copy( source );
  26378. this.parameters = Object.assign( {}, source.parameters );
  26379. return this;
  26380. }
  26381. toJSON() {
  26382. const data = super.toJSON();
  26383. const shapes = this.parameters.shapes;
  26384. const options = this.parameters.options;
  26385. return toJSON$1( shapes, options, data );
  26386. }
  26387. /**
  26388. * Factory method for creating an instance of this class from the given
  26389. * JSON object.
  26390. *
  26391. * @param {Object} data - A JSON object representing the serialized geometry.
  26392. * @param {Array<Shape>} shapes - An array of shapes.
  26393. * @return {ExtrudeGeometry} A new instance.
  26394. */
  26395. static fromJSON( data, shapes ) {
  26396. const geometryShapes = [];
  26397. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26398. const shape = shapes[ data.shapes[ j ] ];
  26399. geometryShapes.push( shape );
  26400. }
  26401. const extrudePath = data.options.extrudePath;
  26402. if ( extrudePath !== undefined ) {
  26403. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26404. }
  26405. return new ExtrudeGeometry( geometryShapes, data.options );
  26406. }
  26407. }
  26408. const WorldUVGenerator = {
  26409. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26410. const a_x = vertices[ indexA * 3 ];
  26411. const a_y = vertices[ indexA * 3 + 1 ];
  26412. const b_x = vertices[ indexB * 3 ];
  26413. const b_y = vertices[ indexB * 3 + 1 ];
  26414. const c_x = vertices[ indexC * 3 ];
  26415. const c_y = vertices[ indexC * 3 + 1 ];
  26416. return [
  26417. new Vector2( a_x, a_y ),
  26418. new Vector2( b_x, b_y ),
  26419. new Vector2( c_x, c_y )
  26420. ];
  26421. },
  26422. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26423. const a_x = vertices[ indexA * 3 ];
  26424. const a_y = vertices[ indexA * 3 + 1 ];
  26425. const a_z = vertices[ indexA * 3 + 2 ];
  26426. const b_x = vertices[ indexB * 3 ];
  26427. const b_y = vertices[ indexB * 3 + 1 ];
  26428. const b_z = vertices[ indexB * 3 + 2 ];
  26429. const c_x = vertices[ indexC * 3 ];
  26430. const c_y = vertices[ indexC * 3 + 1 ];
  26431. const c_z = vertices[ indexC * 3 + 2 ];
  26432. const d_x = vertices[ indexD * 3 ];
  26433. const d_y = vertices[ indexD * 3 + 1 ];
  26434. const d_z = vertices[ indexD * 3 + 2 ];
  26435. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26436. return [
  26437. new Vector2( a_x, 1 - a_z ),
  26438. new Vector2( b_x, 1 - b_z ),
  26439. new Vector2( c_x, 1 - c_z ),
  26440. new Vector2( d_x, 1 - d_z )
  26441. ];
  26442. } else {
  26443. return [
  26444. new Vector2( a_y, 1 - a_z ),
  26445. new Vector2( b_y, 1 - b_z ),
  26446. new Vector2( c_y, 1 - c_z ),
  26447. new Vector2( d_y, 1 - d_z )
  26448. ];
  26449. }
  26450. }
  26451. };
  26452. function toJSON$1( shapes, options, data ) {
  26453. data.shapes = [];
  26454. if ( Array.isArray( shapes ) ) {
  26455. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26456. const shape = shapes[ i ];
  26457. data.shapes.push( shape.uuid );
  26458. }
  26459. } else {
  26460. data.shapes.push( shapes.uuid );
  26461. }
  26462. data.options = Object.assign( {}, options );
  26463. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26464. return data;
  26465. }
  26466. /**
  26467. * A geometry class for representing an icosahedron.
  26468. *
  26469. * ```js
  26470. * const geometry = new THREE.IcosahedronGeometry();
  26471. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26472. * const icosahedron = new THREE.Mesh( geometry, material );
  26473. * scene.add( icosahedron );
  26474. * ```
  26475. *
  26476. * @augments PolyhedronGeometry
  26477. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26478. */
  26479. class IcosahedronGeometry extends PolyhedronGeometry {
  26480. /**
  26481. * Constructs a new icosahedron geometry.
  26482. *
  26483. * @param {number} [radius=1] - Radius of the icosahedron.
  26484. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26485. */
  26486. constructor( radius = 1, detail = 0 ) {
  26487. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26488. const vertices = [
  26489. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26490. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26491. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26492. ];
  26493. const indices = [
  26494. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26495. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26496. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26497. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26498. ];
  26499. super( vertices, indices, radius, detail );
  26500. this.type = 'IcosahedronGeometry';
  26501. /**
  26502. * Holds the constructor parameters that have been
  26503. * used to generate the geometry. Any modification
  26504. * after instantiation does not change the geometry.
  26505. *
  26506. * @type {Object}
  26507. */
  26508. this.parameters = {
  26509. radius: radius,
  26510. detail: detail
  26511. };
  26512. }
  26513. /**
  26514. * Factory method for creating an instance of this class from the given
  26515. * JSON object.
  26516. *
  26517. * @param {Object} data - A JSON object representing the serialized geometry.
  26518. * @return {IcosahedronGeometry} A new instance.
  26519. */
  26520. static fromJSON( data ) {
  26521. return new IcosahedronGeometry( data.radius, data.detail );
  26522. }
  26523. }
  26524. /**
  26525. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26526. *
  26527. * ```js
  26528. * const points = [];
  26529. * for ( let i = 0; i < 10; i ++ ) {
  26530. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26531. * }
  26532. * const geometry = new THREE.LatheGeometry( points );
  26533. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26534. * const lathe = new THREE.Mesh( geometry, material );
  26535. * scene.add( lathe );
  26536. * ```
  26537. *
  26538. * @augments BufferGeometry
  26539. * @demo scenes/geometry-browser.html#LatheGeometry
  26540. */
  26541. class LatheGeometry extends BufferGeometry {
  26542. /**
  26543. * Constructs a new lathe geometry.
  26544. *
  26545. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26546. * must be greater than zero.
  26547. * @param {number} [segments=12] - The number of circumference segments to generate.
  26548. * @param {number} [phiStart=0] - The starting angle in radians.
  26549. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26550. * closed lathe, less than 2PI is a portion.
  26551. */
  26552. 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 ) {
  26553. super();
  26554. this.type = 'LatheGeometry';
  26555. /**
  26556. * Holds the constructor parameters that have been
  26557. * used to generate the geometry. Any modification
  26558. * after instantiation does not change the geometry.
  26559. *
  26560. * @type {Object}
  26561. */
  26562. this.parameters = {
  26563. points: points,
  26564. segments: segments,
  26565. phiStart: phiStart,
  26566. phiLength: phiLength
  26567. };
  26568. segments = Math.floor( segments );
  26569. // clamp phiLength so it's in range of [ 0, 2PI ]
  26570. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26571. // buffers
  26572. const indices = [];
  26573. const vertices = [];
  26574. const uvs = [];
  26575. const initNormals = [];
  26576. const normals = [];
  26577. // helper variables
  26578. const inverseSegments = 1.0 / segments;
  26579. const vertex = new Vector3();
  26580. const uv = new Vector2();
  26581. const normal = new Vector3();
  26582. const curNormal = new Vector3();
  26583. const prevNormal = new Vector3();
  26584. let dx = 0;
  26585. let dy = 0;
  26586. // pre-compute normals for initial "meridian"
  26587. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26588. switch ( j ) {
  26589. case 0: // special handling for 1st vertex on path
  26590. dx = points[ j + 1 ].x - points[ j ].x;
  26591. dy = points[ j + 1 ].y - points[ j ].y;
  26592. normal.x = dy * 1.0;
  26593. normal.y = - dx;
  26594. normal.z = dy * 0.0;
  26595. prevNormal.copy( normal );
  26596. normal.normalize();
  26597. initNormals.push( normal.x, normal.y, normal.z );
  26598. break;
  26599. case ( points.length - 1 ): // special handling for last Vertex on path
  26600. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26601. break;
  26602. default: // default handling for all vertices in between
  26603. dx = points[ j + 1 ].x - points[ j ].x;
  26604. dy = points[ j + 1 ].y - points[ j ].y;
  26605. normal.x = dy * 1.0;
  26606. normal.y = - dx;
  26607. normal.z = dy * 0.0;
  26608. curNormal.copy( normal );
  26609. normal.x += prevNormal.x;
  26610. normal.y += prevNormal.y;
  26611. normal.z += prevNormal.z;
  26612. normal.normalize();
  26613. initNormals.push( normal.x, normal.y, normal.z );
  26614. prevNormal.copy( curNormal );
  26615. }
  26616. }
  26617. // generate vertices, uvs and normals
  26618. for ( let i = 0; i <= segments; i ++ ) {
  26619. const phi = phiStart + i * inverseSegments * phiLength;
  26620. const sin = Math.sin( phi );
  26621. const cos = Math.cos( phi );
  26622. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26623. // vertex
  26624. vertex.x = points[ j ].x * sin;
  26625. vertex.y = points[ j ].y;
  26626. vertex.z = points[ j ].x * cos;
  26627. vertices.push( vertex.x, vertex.y, vertex.z );
  26628. // uv
  26629. uv.x = i / segments;
  26630. uv.y = j / ( points.length - 1 );
  26631. uvs.push( uv.x, uv.y );
  26632. // normal
  26633. const x = initNormals[ 3 * j + 0 ] * sin;
  26634. const y = initNormals[ 3 * j + 1 ];
  26635. const z = initNormals[ 3 * j + 0 ] * cos;
  26636. normals.push( x, y, z );
  26637. }
  26638. }
  26639. // indices
  26640. for ( let i = 0; i < segments; i ++ ) {
  26641. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26642. const base = j + i * points.length;
  26643. const a = base;
  26644. const b = base + points.length;
  26645. const c = base + points.length + 1;
  26646. const d = base + 1;
  26647. // faces
  26648. indices.push( a, b, d );
  26649. indices.push( c, d, b );
  26650. }
  26651. }
  26652. // build geometry
  26653. this.setIndex( indices );
  26654. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26655. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26656. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26657. }
  26658. copy( source ) {
  26659. super.copy( source );
  26660. this.parameters = Object.assign( {}, source.parameters );
  26661. return this;
  26662. }
  26663. /**
  26664. * Factory method for creating an instance of this class from the given
  26665. * JSON object.
  26666. *
  26667. * @param {Object} data - A JSON object representing the serialized geometry.
  26668. * @return {LatheGeometry} A new instance.
  26669. */
  26670. static fromJSON( data ) {
  26671. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26672. }
  26673. }
  26674. /**
  26675. * A geometry class for representing an octahedron.
  26676. *
  26677. * ```js
  26678. * const geometry = new THREE.OctahedronGeometry();
  26679. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26680. * const octahedron = new THREE.Mesh( geometry, material );
  26681. * scene.add( octahedron );
  26682. * ```
  26683. *
  26684. * @augments PolyhedronGeometry
  26685. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26686. */
  26687. class OctahedronGeometry extends PolyhedronGeometry {
  26688. /**
  26689. * Constructs a new octahedron geometry.
  26690. *
  26691. * @param {number} [radius=1] - Radius of the octahedron.
  26692. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26693. */
  26694. constructor( radius = 1, detail = 0 ) {
  26695. const vertices = [
  26696. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26697. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26698. ];
  26699. const indices = [
  26700. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26701. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26702. 1, 3, 4, 1, 4, 2
  26703. ];
  26704. super( vertices, indices, radius, detail );
  26705. this.type = 'OctahedronGeometry';
  26706. /**
  26707. * Holds the constructor parameters that have been
  26708. * used to generate the geometry. Any modification
  26709. * after instantiation does not change the geometry.
  26710. *
  26711. * @type {Object}
  26712. */
  26713. this.parameters = {
  26714. radius: radius,
  26715. detail: detail
  26716. };
  26717. }
  26718. /**
  26719. * Factory method for creating an instance of this class from the given
  26720. * JSON object.
  26721. *
  26722. * @param {Object} data - A JSON object representing the serialized geometry.
  26723. * @return {OctahedronGeometry} A new instance.
  26724. */
  26725. static fromJSON( data ) {
  26726. return new OctahedronGeometry( data.radius, data.detail );
  26727. }
  26728. }
  26729. /**
  26730. * A geometry class for representing a plane.
  26731. *
  26732. * ```js
  26733. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26734. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26735. * const plane = new THREE.Mesh( geometry, material );
  26736. * scene.add( plane );
  26737. * ```
  26738. *
  26739. * @augments BufferGeometry
  26740. * @demo scenes/geometry-browser.html#PlaneGeometry
  26741. */
  26742. class PlaneGeometry extends BufferGeometry {
  26743. /**
  26744. * Constructs a new plane geometry.
  26745. *
  26746. * @param {number} [width=1] - The width along the X axis.
  26747. * @param {number} [height=1] - The height along the Y axis
  26748. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26749. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26750. */
  26751. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26752. super();
  26753. this.type = 'PlaneGeometry';
  26754. /**
  26755. * Holds the constructor parameters that have been
  26756. * used to generate the geometry. Any modification
  26757. * after instantiation does not change the geometry.
  26758. *
  26759. * @type {Object}
  26760. */
  26761. this.parameters = {
  26762. width: width,
  26763. height: height,
  26764. widthSegments: widthSegments,
  26765. heightSegments: heightSegments
  26766. };
  26767. const width_half = width / 2;
  26768. const height_half = height / 2;
  26769. const gridX = Math.floor( widthSegments );
  26770. const gridY = Math.floor( heightSegments );
  26771. const gridX1 = gridX + 1;
  26772. const gridY1 = gridY + 1;
  26773. const segment_width = width / gridX;
  26774. const segment_height = height / gridY;
  26775. //
  26776. const indices = [];
  26777. const vertices = [];
  26778. const normals = [];
  26779. const uvs = [];
  26780. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26781. const y = iy * segment_height - height_half;
  26782. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26783. const x = ix * segment_width - width_half;
  26784. vertices.push( x, - y, 0 );
  26785. normals.push( 0, 0, 1 );
  26786. uvs.push( ix / gridX );
  26787. uvs.push( 1 - ( iy / gridY ) );
  26788. }
  26789. }
  26790. for ( let iy = 0; iy < gridY; iy ++ ) {
  26791. for ( let ix = 0; ix < gridX; ix ++ ) {
  26792. const a = ix + gridX1 * iy;
  26793. const b = ix + gridX1 * ( iy + 1 );
  26794. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26795. const d = ( ix + 1 ) + gridX1 * iy;
  26796. indices.push( a, b, d );
  26797. indices.push( b, c, d );
  26798. }
  26799. }
  26800. this.setIndex( indices );
  26801. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26802. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26803. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26804. }
  26805. copy( source ) {
  26806. super.copy( source );
  26807. this.parameters = Object.assign( {}, source.parameters );
  26808. return this;
  26809. }
  26810. /**
  26811. * Factory method for creating an instance of this class from the given
  26812. * JSON object.
  26813. *
  26814. * @param {Object} data - A JSON object representing the serialized geometry.
  26815. * @return {PlaneGeometry} A new instance.
  26816. */
  26817. static fromJSON( data ) {
  26818. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26819. }
  26820. }
  26821. /**
  26822. * A class for generating a two-dimensional ring geometry.
  26823. *
  26824. * ```js
  26825. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26826. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26827. * const mesh = new THREE.Mesh( geometry, material );
  26828. * scene.add( mesh );
  26829. * ```
  26830. *
  26831. * @augments BufferGeometry
  26832. * @demo scenes/geometry-browser.html#RingGeometry
  26833. */
  26834. class RingGeometry extends BufferGeometry {
  26835. /**
  26836. * Constructs a new ring geometry.
  26837. *
  26838. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26839. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26840. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26841. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26842. * @param {number} [thetaStart=0] - Starting angle in radians.
  26843. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26844. */
  26845. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26846. super();
  26847. this.type = 'RingGeometry';
  26848. /**
  26849. * Holds the constructor parameters that have been
  26850. * used to generate the geometry. Any modification
  26851. * after instantiation does not change the geometry.
  26852. *
  26853. * @type {Object}
  26854. */
  26855. this.parameters = {
  26856. innerRadius: innerRadius,
  26857. outerRadius: outerRadius,
  26858. thetaSegments: thetaSegments,
  26859. phiSegments: phiSegments,
  26860. thetaStart: thetaStart,
  26861. thetaLength: thetaLength
  26862. };
  26863. thetaSegments = Math.max( 3, thetaSegments );
  26864. phiSegments = Math.max( 1, phiSegments );
  26865. // buffers
  26866. const indices = [];
  26867. const vertices = [];
  26868. const normals = [];
  26869. const uvs = [];
  26870. // some helper variables
  26871. let radius = innerRadius;
  26872. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26873. const vertex = new Vector3();
  26874. const uv = new Vector2();
  26875. // generate vertices, normals and uvs
  26876. for ( let j = 0; j <= phiSegments; j ++ ) {
  26877. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26878. // values are generate from the inside of the ring to the outside
  26879. const segment = thetaStart + i / thetaSegments * thetaLength;
  26880. // vertex
  26881. vertex.x = radius * Math.cos( segment );
  26882. vertex.y = radius * Math.sin( segment );
  26883. vertices.push( vertex.x, vertex.y, vertex.z );
  26884. // normal
  26885. normals.push( 0, 0, 1 );
  26886. // uv
  26887. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26888. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26889. uvs.push( uv.x, uv.y );
  26890. }
  26891. // increase the radius for next row of vertices
  26892. radius += radiusStep;
  26893. }
  26894. // indices
  26895. for ( let j = 0; j < phiSegments; j ++ ) {
  26896. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26897. for ( let i = 0; i < thetaSegments; i ++ ) {
  26898. const segment = i + thetaSegmentLevel;
  26899. const a = segment;
  26900. const b = segment + thetaSegments + 1;
  26901. const c = segment + thetaSegments + 2;
  26902. const d = segment + 1;
  26903. // faces
  26904. indices.push( a, b, d );
  26905. indices.push( b, c, d );
  26906. }
  26907. }
  26908. // build geometry
  26909. this.setIndex( indices );
  26910. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26911. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26912. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26913. }
  26914. copy( source ) {
  26915. super.copy( source );
  26916. this.parameters = Object.assign( {}, source.parameters );
  26917. return this;
  26918. }
  26919. /**
  26920. * Factory method for creating an instance of this class from the given
  26921. * JSON object.
  26922. *
  26923. * @param {Object} data - A JSON object representing the serialized geometry.
  26924. * @return {RingGeometry} A new instance.
  26925. */
  26926. static fromJSON( data ) {
  26927. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26928. }
  26929. }
  26930. /**
  26931. * Creates an one-sided polygonal geometry from one or more path shapes.
  26932. *
  26933. * ```js
  26934. * const arcShape = new THREE.Shape()
  26935. * .moveTo( 5, 1 )
  26936. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26937. *
  26938. * const geometry = new THREE.ShapeGeometry( arcShape );
  26939. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26940. * const mesh = new THREE.Mesh( geometry, material ) ;
  26941. * scene.add( mesh );
  26942. * ```
  26943. *
  26944. * @augments BufferGeometry
  26945. * @demo scenes/geometry-browser.html#ShapeGeometry
  26946. */
  26947. class ShapeGeometry extends BufferGeometry {
  26948. /**
  26949. * Constructs a new shape geometry.
  26950. *
  26951. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26952. * @param {number} [curveSegments=12] - Number of segments per shape.
  26953. */
  26954. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26955. super();
  26956. this.type = 'ShapeGeometry';
  26957. /**
  26958. * Holds the constructor parameters that have been
  26959. * used to generate the geometry. Any modification
  26960. * after instantiation does not change the geometry.
  26961. *
  26962. * @type {Object}
  26963. */
  26964. this.parameters = {
  26965. shapes: shapes,
  26966. curveSegments: curveSegments
  26967. };
  26968. // buffers
  26969. const indices = [];
  26970. const vertices = [];
  26971. const normals = [];
  26972. const uvs = [];
  26973. // helper variables
  26974. let groupStart = 0;
  26975. let groupCount = 0;
  26976. // allow single and array values for "shapes" parameter
  26977. if ( Array.isArray( shapes ) === false ) {
  26978. addShape( shapes );
  26979. } else {
  26980. for ( let i = 0; i < shapes.length; i ++ ) {
  26981. addShape( shapes[ i ] );
  26982. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26983. groupStart += groupCount;
  26984. groupCount = 0;
  26985. }
  26986. }
  26987. // build geometry
  26988. this.setIndex( indices );
  26989. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26990. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26991. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26992. // helper functions
  26993. function addShape( shape ) {
  26994. const indexOffset = vertices.length / 3;
  26995. const points = shape.extractPoints( curveSegments );
  26996. let shapeVertices = points.shape;
  26997. const shapeHoles = points.holes;
  26998. // check direction of vertices
  26999. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  27000. shapeVertices = shapeVertices.reverse();
  27001. }
  27002. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27003. const shapeHole = shapeHoles[ i ];
  27004. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27005. shapeHoles[ i ] = shapeHole.reverse();
  27006. }
  27007. }
  27008. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27009. // join vertices of inner and outer paths to a single array
  27010. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27011. const shapeHole = shapeHoles[ i ];
  27012. shapeVertices = shapeVertices.concat( shapeHole );
  27013. }
  27014. // vertices, normals, uvs
  27015. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27016. const vertex = shapeVertices[ i ];
  27017. vertices.push( vertex.x, vertex.y, 0 );
  27018. normals.push( 0, 0, 1 );
  27019. uvs.push( vertex.x, vertex.y ); // world uvs
  27020. }
  27021. // indices
  27022. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27023. const face = faces[ i ];
  27024. const a = face[ 0 ] + indexOffset;
  27025. const b = face[ 1 ] + indexOffset;
  27026. const c = face[ 2 ] + indexOffset;
  27027. indices.push( a, b, c );
  27028. groupCount += 3;
  27029. }
  27030. }
  27031. }
  27032. copy( source ) {
  27033. super.copy( source );
  27034. this.parameters = Object.assign( {}, source.parameters );
  27035. return this;
  27036. }
  27037. toJSON() {
  27038. const data = super.toJSON();
  27039. const shapes = this.parameters.shapes;
  27040. return toJSON( shapes, data );
  27041. }
  27042. /**
  27043. * Factory method for creating an instance of this class from the given
  27044. * JSON object.
  27045. *
  27046. * @param {Object} data - A JSON object representing the serialized geometry.
  27047. * @param {Array<Shape>} shapes - An array of shapes.
  27048. * @return {ShapeGeometry} A new instance.
  27049. */
  27050. static fromJSON( data, shapes ) {
  27051. const geometryShapes = [];
  27052. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27053. const shape = shapes[ data.shapes[ j ] ];
  27054. geometryShapes.push( shape );
  27055. }
  27056. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27057. }
  27058. }
  27059. function toJSON( shapes, data ) {
  27060. data.shapes = [];
  27061. if ( Array.isArray( shapes ) ) {
  27062. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27063. const shape = shapes[ i ];
  27064. data.shapes.push( shape.uuid );
  27065. }
  27066. } else {
  27067. data.shapes.push( shapes.uuid );
  27068. }
  27069. return data;
  27070. }
  27071. /**
  27072. * A class for generating a sphere geometry.
  27073. *
  27074. * ```js
  27075. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27076. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27077. * const sphere = new THREE.Mesh( geometry, material );
  27078. * scene.add( sphere );
  27079. * ```
  27080. *
  27081. * @augments BufferGeometry
  27082. * @demo scenes/geometry-browser.html#SphereGeometry
  27083. */
  27084. class SphereGeometry extends BufferGeometry {
  27085. /**
  27086. * Constructs a new sphere geometry.
  27087. *
  27088. * @param {number} [radius=1] - The sphere radius.
  27089. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27090. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27091. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27092. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27093. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27094. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27095. */
  27096. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27097. super();
  27098. this.type = 'SphereGeometry';
  27099. /**
  27100. * Holds the constructor parameters that have been
  27101. * used to generate the geometry. Any modification
  27102. * after instantiation does not change the geometry.
  27103. *
  27104. * @type {Object}
  27105. */
  27106. this.parameters = {
  27107. radius: radius,
  27108. widthSegments: widthSegments,
  27109. heightSegments: heightSegments,
  27110. phiStart: phiStart,
  27111. phiLength: phiLength,
  27112. thetaStart: thetaStart,
  27113. thetaLength: thetaLength
  27114. };
  27115. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27116. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27117. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27118. let index = 0;
  27119. const grid = [];
  27120. const vertex = new Vector3();
  27121. const normal = new Vector3();
  27122. // buffers
  27123. const indices = [];
  27124. const vertices = [];
  27125. const normals = [];
  27126. const uvs = [];
  27127. // generate vertices, normals and uvs
  27128. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27129. const verticesRow = [];
  27130. const v = iy / heightSegments;
  27131. // special case for the poles
  27132. let uOffset = 0;
  27133. if ( iy === 0 && thetaStart === 0 ) {
  27134. uOffset = 0.5 / widthSegments;
  27135. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27136. uOffset = -0.5 / widthSegments;
  27137. }
  27138. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27139. const u = ix / widthSegments;
  27140. // vertex
  27141. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27142. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27143. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27144. vertices.push( vertex.x, vertex.y, vertex.z );
  27145. // normal
  27146. normal.copy( vertex ).normalize();
  27147. normals.push( normal.x, normal.y, normal.z );
  27148. // uv
  27149. uvs.push( u + uOffset, 1 - v );
  27150. verticesRow.push( index ++ );
  27151. }
  27152. grid.push( verticesRow );
  27153. }
  27154. // indices
  27155. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27156. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27157. const a = grid[ iy ][ ix + 1 ];
  27158. const b = grid[ iy ][ ix ];
  27159. const c = grid[ iy + 1 ][ ix ];
  27160. const d = grid[ iy + 1 ][ ix + 1 ];
  27161. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27162. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27163. }
  27164. }
  27165. // build geometry
  27166. this.setIndex( indices );
  27167. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27168. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27169. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27170. }
  27171. copy( source ) {
  27172. super.copy( source );
  27173. this.parameters = Object.assign( {}, source.parameters );
  27174. return this;
  27175. }
  27176. /**
  27177. * Factory method for creating an instance of this class from the given
  27178. * JSON object.
  27179. *
  27180. * @param {Object} data - A JSON object representing the serialized geometry.
  27181. * @return {SphereGeometry} A new instance.
  27182. */
  27183. static fromJSON( data ) {
  27184. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27185. }
  27186. }
  27187. /**
  27188. * A geometry class for representing an tetrahedron.
  27189. *
  27190. * ```js
  27191. * const geometry = new THREE.TetrahedronGeometry();
  27192. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27193. * const tetrahedron = new THREE.Mesh( geometry, material );
  27194. * scene.add( tetrahedron );
  27195. * ```
  27196. *
  27197. * @augments PolyhedronGeometry
  27198. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27199. */
  27200. class TetrahedronGeometry extends PolyhedronGeometry {
  27201. /**
  27202. * Constructs a new tetrahedron geometry.
  27203. *
  27204. * @param {number} [radius=1] - Radius of the tetrahedron.
  27205. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27206. */
  27207. constructor( radius = 1, detail = 0 ) {
  27208. const vertices = [
  27209. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27210. ];
  27211. const indices = [
  27212. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27213. ];
  27214. super( vertices, indices, radius, detail );
  27215. this.type = 'TetrahedronGeometry';
  27216. /**
  27217. * Holds the constructor parameters that have been
  27218. * used to generate the geometry. Any modification
  27219. * after instantiation does not change the geometry.
  27220. *
  27221. * @type {Object}
  27222. */
  27223. this.parameters = {
  27224. radius: radius,
  27225. detail: detail
  27226. };
  27227. }
  27228. /**
  27229. * Factory method for creating an instance of this class from the given
  27230. * JSON object.
  27231. *
  27232. * @param {Object} data - A JSON object representing the serialized geometry.
  27233. * @return {TetrahedronGeometry} A new instance.
  27234. */
  27235. static fromJSON( data ) {
  27236. return new TetrahedronGeometry( data.radius, data.detail );
  27237. }
  27238. }
  27239. /**
  27240. * A geometry class for representing an torus.
  27241. *
  27242. * ```js
  27243. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27244. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27245. * const torus = new THREE.Mesh( geometry, material );
  27246. * scene.add( torus );
  27247. * ```
  27248. *
  27249. * @augments BufferGeometry
  27250. * @demo scenes/geometry-browser.html#TorusGeometry
  27251. */
  27252. class TorusGeometry extends BufferGeometry {
  27253. /**
  27254. * Constructs a new torus geometry.
  27255. *
  27256. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27257. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27258. * @param {number} [radialSegments=12] - The number of radial segments.
  27259. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27260. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27261. */
  27262. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27263. super();
  27264. this.type = 'TorusGeometry';
  27265. /**
  27266. * Holds the constructor parameters that have been
  27267. * used to generate the geometry. Any modification
  27268. * after instantiation does not change the geometry.
  27269. *
  27270. * @type {Object}
  27271. */
  27272. this.parameters = {
  27273. radius: radius,
  27274. tube: tube,
  27275. radialSegments: radialSegments,
  27276. tubularSegments: tubularSegments,
  27277. arc: arc
  27278. };
  27279. radialSegments = Math.floor( radialSegments );
  27280. tubularSegments = Math.floor( tubularSegments );
  27281. // buffers
  27282. const indices = [];
  27283. const vertices = [];
  27284. const normals = [];
  27285. const uvs = [];
  27286. // helper variables
  27287. const center = new Vector3();
  27288. const vertex = new Vector3();
  27289. const normal = new Vector3();
  27290. // generate vertices, normals and uvs
  27291. for ( let j = 0; j <= radialSegments; j ++ ) {
  27292. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27293. const u = i / tubularSegments * arc;
  27294. const v = j / radialSegments * Math.PI * 2;
  27295. // vertex
  27296. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27297. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27298. vertex.z = tube * Math.sin( v );
  27299. vertices.push( vertex.x, vertex.y, vertex.z );
  27300. // normal
  27301. center.x = radius * Math.cos( u );
  27302. center.y = radius * Math.sin( u );
  27303. normal.subVectors( vertex, center ).normalize();
  27304. normals.push( normal.x, normal.y, normal.z );
  27305. // uv
  27306. uvs.push( i / tubularSegments );
  27307. uvs.push( j / radialSegments );
  27308. }
  27309. }
  27310. // generate indices
  27311. for ( let j = 1; j <= radialSegments; j ++ ) {
  27312. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27313. // indices
  27314. const a = ( tubularSegments + 1 ) * j + i - 1;
  27315. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27316. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27317. const d = ( tubularSegments + 1 ) * j + i;
  27318. // faces
  27319. indices.push( a, b, d );
  27320. indices.push( b, c, d );
  27321. }
  27322. }
  27323. // build geometry
  27324. this.setIndex( indices );
  27325. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27326. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27327. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27328. }
  27329. copy( source ) {
  27330. super.copy( source );
  27331. this.parameters = Object.assign( {}, source.parameters );
  27332. return this;
  27333. }
  27334. /**
  27335. * Factory method for creating an instance of this class from the given
  27336. * JSON object.
  27337. *
  27338. * @param {Object} data - A JSON object representing the serialized geometry.
  27339. * @return {TorusGeometry} A new instance.
  27340. */
  27341. static fromJSON( data ) {
  27342. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27343. }
  27344. }
  27345. /**
  27346. * Creates a torus knot, the particular shape of which is defined by a pair
  27347. * of coprime integers, p and q. If p and q are not coprime, the result will
  27348. * be a torus link.
  27349. *
  27350. * ```js
  27351. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27352. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27353. * const torusKnot = new THREE.Mesh( geometry, material );
  27354. * scene.add( torusKnot );
  27355. * ```
  27356. *
  27357. * @augments BufferGeometry
  27358. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27359. */
  27360. class TorusKnotGeometry extends BufferGeometry {
  27361. /**
  27362. * Constructs a new torus knot geometry.
  27363. *
  27364. * @param {number} [radius=1] - Radius of the torus knot.
  27365. * @param {number} [tube=0.4] - Radius of the tube.
  27366. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27367. * @param {number} [radialSegments=8] - The number of radial segments.
  27368. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27369. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27370. */
  27371. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27372. super();
  27373. this.type = 'TorusKnotGeometry';
  27374. /**
  27375. * Holds the constructor parameters that have been
  27376. * used to generate the geometry. Any modification
  27377. * after instantiation does not change the geometry.
  27378. *
  27379. * @type {Object}
  27380. */
  27381. this.parameters = {
  27382. radius: radius,
  27383. tube: tube,
  27384. tubularSegments: tubularSegments,
  27385. radialSegments: radialSegments,
  27386. p: p,
  27387. q: q
  27388. };
  27389. tubularSegments = Math.floor( tubularSegments );
  27390. radialSegments = Math.floor( radialSegments );
  27391. // buffers
  27392. const indices = [];
  27393. const vertices = [];
  27394. const normals = [];
  27395. const uvs = [];
  27396. // helper variables
  27397. const vertex = new Vector3();
  27398. const normal = new Vector3();
  27399. const P1 = new Vector3();
  27400. const P2 = new Vector3();
  27401. const B = new Vector3();
  27402. const T = new Vector3();
  27403. const N = new Vector3();
  27404. // generate vertices, normals and uvs
  27405. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27406. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27407. const u = i / tubularSegments * p * Math.PI * 2;
  27408. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27409. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27410. calculatePositionOnCurve( u, p, q, radius, P1 );
  27411. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27412. // calculate orthonormal basis
  27413. T.subVectors( P2, P1 );
  27414. N.addVectors( P2, P1 );
  27415. B.crossVectors( T, N );
  27416. N.crossVectors( B, T );
  27417. // normalize B, N. T can be ignored, we don't use it
  27418. B.normalize();
  27419. N.normalize();
  27420. for ( let j = 0; j <= radialSegments; ++ j ) {
  27421. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27422. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27423. const v = j / radialSegments * Math.PI * 2;
  27424. const cx = - tube * Math.cos( v );
  27425. const cy = tube * Math.sin( v );
  27426. // now calculate the final vertex position.
  27427. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27428. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27429. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27430. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27431. vertices.push( vertex.x, vertex.y, vertex.z );
  27432. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27433. normal.subVectors( vertex, P1 ).normalize();
  27434. normals.push( normal.x, normal.y, normal.z );
  27435. // uv
  27436. uvs.push( i / tubularSegments );
  27437. uvs.push( j / radialSegments );
  27438. }
  27439. }
  27440. // generate indices
  27441. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27442. for ( let i = 1; i <= radialSegments; i ++ ) {
  27443. // indices
  27444. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27445. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27446. const c = ( radialSegments + 1 ) * j + i;
  27447. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27448. // faces
  27449. indices.push( a, b, d );
  27450. indices.push( b, c, d );
  27451. }
  27452. }
  27453. // build geometry
  27454. this.setIndex( indices );
  27455. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27456. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27457. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27458. // this function calculates the current position on the torus curve
  27459. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27460. const cu = Math.cos( u );
  27461. const su = Math.sin( u );
  27462. const quOverP = q / p * u;
  27463. const cs = Math.cos( quOverP );
  27464. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27465. position.y = radius * ( 2 + cs ) * su * 0.5;
  27466. position.z = radius * Math.sin( quOverP ) * 0.5;
  27467. }
  27468. }
  27469. copy( source ) {
  27470. super.copy( source );
  27471. this.parameters = Object.assign( {}, source.parameters );
  27472. return this;
  27473. }
  27474. /**
  27475. * Factory method for creating an instance of this class from the given
  27476. * JSON object.
  27477. *
  27478. * @param {Object} data - A JSON object representing the serialized geometry.
  27479. * @return {TorusKnotGeometry} A new instance.
  27480. */
  27481. static fromJSON( data ) {
  27482. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27483. }
  27484. }
  27485. /**
  27486. * Creates a tube that extrudes along a 3D curve.
  27487. *
  27488. * ```js
  27489. * class CustomSinCurve extends THREE.Curve {
  27490. *
  27491. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27492. *
  27493. * const tx = t * 3 - 1.5;
  27494. * const ty = Math.sin( 2 * Math.PI * t );
  27495. * const tz = 0;
  27496. *
  27497. * return optionalTarget.set( tx, ty, tz );
  27498. * }
  27499. *
  27500. * }
  27501. *
  27502. * const path = new CustomSinCurve( 10 );
  27503. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27504. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27505. * const mesh = new THREE.Mesh( geometry, material );
  27506. * scene.add( mesh );
  27507. * ```
  27508. *
  27509. * @augments BufferGeometry
  27510. * @demo scenes/geometry-browser.html#TubeGeometry
  27511. */
  27512. class TubeGeometry extends BufferGeometry {
  27513. /**
  27514. * Constructs a new tube geometry.
  27515. *
  27516. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27517. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27518. * @param {number} [radius=1] -The radius of the tube.
  27519. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27520. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27521. */
  27522. 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 ) {
  27523. super();
  27524. this.type = 'TubeGeometry';
  27525. /**
  27526. * Holds the constructor parameters that have been
  27527. * used to generate the geometry. Any modification
  27528. * after instantiation does not change the geometry.
  27529. *
  27530. * @type {Object}
  27531. */
  27532. this.parameters = {
  27533. path: path,
  27534. tubularSegments: tubularSegments,
  27535. radius: radius,
  27536. radialSegments: radialSegments,
  27537. closed: closed
  27538. };
  27539. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27540. // expose internals
  27541. this.tangents = frames.tangents;
  27542. this.normals = frames.normals;
  27543. this.binormals = frames.binormals;
  27544. // helper variables
  27545. const vertex = new Vector3();
  27546. const normal = new Vector3();
  27547. const uv = new Vector2();
  27548. let P = new Vector3();
  27549. // buffer
  27550. const vertices = [];
  27551. const normals = [];
  27552. const uvs = [];
  27553. const indices = [];
  27554. // create buffer data
  27555. generateBufferData();
  27556. // build geometry
  27557. this.setIndex( indices );
  27558. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27559. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27560. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27561. // functions
  27562. function generateBufferData() {
  27563. for ( let i = 0; i < tubularSegments; i ++ ) {
  27564. generateSegment( i );
  27565. }
  27566. // if the geometry is not closed, generate the last row of vertices and normals
  27567. // at the regular position on the given path
  27568. //
  27569. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27570. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27571. // uvs are generated in a separate function.
  27572. // this makes it easy compute correct values for closed geometries
  27573. generateUVs();
  27574. // finally create faces
  27575. generateIndices();
  27576. }
  27577. function generateSegment( i ) {
  27578. // we use getPointAt to sample evenly distributed points from the given path
  27579. P = path.getPointAt( i / tubularSegments, P );
  27580. // retrieve corresponding normal and binormal
  27581. const N = frames.normals[ i ];
  27582. const B = frames.binormals[ i ];
  27583. // generate normals and vertices for the current segment
  27584. for ( let j = 0; j <= radialSegments; j ++ ) {
  27585. const v = j / radialSegments * Math.PI * 2;
  27586. const sin = Math.sin( v );
  27587. const cos = - Math.cos( v );
  27588. // normal
  27589. normal.x = ( cos * N.x + sin * B.x );
  27590. normal.y = ( cos * N.y + sin * B.y );
  27591. normal.z = ( cos * N.z + sin * B.z );
  27592. normal.normalize();
  27593. normals.push( normal.x, normal.y, normal.z );
  27594. // vertex
  27595. vertex.x = P.x + radius * normal.x;
  27596. vertex.y = P.y + radius * normal.y;
  27597. vertex.z = P.z + radius * normal.z;
  27598. vertices.push( vertex.x, vertex.y, vertex.z );
  27599. }
  27600. }
  27601. function generateIndices() {
  27602. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27603. for ( let i = 1; i <= radialSegments; i ++ ) {
  27604. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27605. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27606. const c = ( radialSegments + 1 ) * j + i;
  27607. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27608. // faces
  27609. indices.push( a, b, d );
  27610. indices.push( b, c, d );
  27611. }
  27612. }
  27613. }
  27614. function generateUVs() {
  27615. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27616. for ( let j = 0; j <= radialSegments; j ++ ) {
  27617. uv.x = i / tubularSegments;
  27618. uv.y = j / radialSegments;
  27619. uvs.push( uv.x, uv.y );
  27620. }
  27621. }
  27622. }
  27623. }
  27624. copy( source ) {
  27625. super.copy( source );
  27626. this.parameters = Object.assign( {}, source.parameters );
  27627. return this;
  27628. }
  27629. toJSON() {
  27630. const data = super.toJSON();
  27631. data.path = this.parameters.path.toJSON();
  27632. return data;
  27633. }
  27634. /**
  27635. * Factory method for creating an instance of this class from the given
  27636. * JSON object.
  27637. *
  27638. * @param {Object} data - A JSON object representing the serialized geometry.
  27639. * @return {TubeGeometry} A new instance.
  27640. */
  27641. static fromJSON( data ) {
  27642. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27643. // User defined curves or instances of CurvePath will not be deserialized.
  27644. return new TubeGeometry(
  27645. new Curves[ data.path.type ]().fromJSON( data.path ),
  27646. data.tubularSegments,
  27647. data.radius,
  27648. data.radialSegments,
  27649. data.closed
  27650. );
  27651. }
  27652. }
  27653. /**
  27654. * Can be used as a helper object to visualize a geometry as a wireframe.
  27655. *
  27656. * ```js
  27657. * const geometry = new THREE.SphereGeometry();
  27658. *
  27659. * const wireframe = new THREE.WireframeGeometry( geometry );
  27660. *
  27661. * const line = new THREE.LineSegments( wireframe );
  27662. * line.material.depthWrite = false;
  27663. * line.material.opacity = 0.25;
  27664. * line.material.transparent = true;
  27665. *
  27666. * scene.add( line );
  27667. * ```
  27668. *
  27669. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27670. *
  27671. * @augments BufferGeometry
  27672. */
  27673. class WireframeGeometry extends BufferGeometry {
  27674. /**
  27675. * Constructs a new wireframe geometry.
  27676. *
  27677. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27678. */
  27679. constructor( geometry = null ) {
  27680. super();
  27681. this.type = 'WireframeGeometry';
  27682. /**
  27683. * Holds the constructor parameters that have been
  27684. * used to generate the geometry. Any modification
  27685. * after instantiation does not change the geometry.
  27686. *
  27687. * @type {Object}
  27688. */
  27689. this.parameters = {
  27690. geometry: geometry
  27691. };
  27692. if ( geometry !== null ) {
  27693. // buffer
  27694. const vertices = [];
  27695. const edges = new Set();
  27696. // helper variables
  27697. const start = new Vector3();
  27698. const end = new Vector3();
  27699. if ( geometry.index !== null ) {
  27700. // indexed BufferGeometry
  27701. const position = geometry.attributes.position;
  27702. const indices = geometry.index;
  27703. let groups = geometry.groups;
  27704. if ( groups.length === 0 ) {
  27705. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27706. }
  27707. // create a data structure that contains all edges without duplicates
  27708. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27709. const group = groups[ o ];
  27710. const groupStart = group.start;
  27711. const groupCount = group.count;
  27712. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27713. for ( let j = 0; j < 3; j ++ ) {
  27714. const index1 = indices.getX( i + j );
  27715. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27716. start.fromBufferAttribute( position, index1 );
  27717. end.fromBufferAttribute( position, index2 );
  27718. if ( isUniqueEdge( start, end, edges ) === true ) {
  27719. vertices.push( start.x, start.y, start.z );
  27720. vertices.push( end.x, end.y, end.z );
  27721. }
  27722. }
  27723. }
  27724. }
  27725. } else {
  27726. // non-indexed BufferGeometry
  27727. const position = geometry.attributes.position;
  27728. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27729. for ( let j = 0; j < 3; j ++ ) {
  27730. // three edges per triangle, an edge is represented as (index1, index2)
  27731. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27732. const index1 = 3 * i + j;
  27733. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27734. start.fromBufferAttribute( position, index1 );
  27735. end.fromBufferAttribute( position, index2 );
  27736. if ( isUniqueEdge( start, end, edges ) === true ) {
  27737. vertices.push( start.x, start.y, start.z );
  27738. vertices.push( end.x, end.y, end.z );
  27739. }
  27740. }
  27741. }
  27742. }
  27743. // build geometry
  27744. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27745. }
  27746. }
  27747. copy( source ) {
  27748. super.copy( source );
  27749. this.parameters = Object.assign( {}, source.parameters );
  27750. return this;
  27751. }
  27752. }
  27753. function isUniqueEdge( start, end, edges ) {
  27754. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27755. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27756. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27757. return false;
  27758. } else {
  27759. edges.add( hash1 );
  27760. edges.add( hash2 );
  27761. return true;
  27762. }
  27763. }
  27764. var Geometries = /*#__PURE__*/Object.freeze({
  27765. __proto__: null,
  27766. BoxGeometry: BoxGeometry,
  27767. CapsuleGeometry: CapsuleGeometry,
  27768. CircleGeometry: CircleGeometry,
  27769. ConeGeometry: ConeGeometry,
  27770. CylinderGeometry: CylinderGeometry,
  27771. DodecahedronGeometry: DodecahedronGeometry,
  27772. EdgesGeometry: EdgesGeometry,
  27773. ExtrudeGeometry: ExtrudeGeometry,
  27774. IcosahedronGeometry: IcosahedronGeometry,
  27775. LatheGeometry: LatheGeometry,
  27776. OctahedronGeometry: OctahedronGeometry,
  27777. PlaneGeometry: PlaneGeometry,
  27778. PolyhedronGeometry: PolyhedronGeometry,
  27779. RingGeometry: RingGeometry,
  27780. ShapeGeometry: ShapeGeometry,
  27781. SphereGeometry: SphereGeometry,
  27782. TetrahedronGeometry: TetrahedronGeometry,
  27783. TorusGeometry: TorusGeometry,
  27784. TorusKnotGeometry: TorusKnotGeometry,
  27785. TubeGeometry: TubeGeometry,
  27786. WireframeGeometry: WireframeGeometry
  27787. });
  27788. /**
  27789. * This material can receive shadows, but otherwise is completely transparent.
  27790. *
  27791. * ```js
  27792. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27793. * geometry.rotateX( - Math.PI / 2 );
  27794. *
  27795. * const material = new THREE.ShadowMaterial();
  27796. * material.opacity = 0.2;
  27797. *
  27798. * const plane = new THREE.Mesh( geometry, material );
  27799. * plane.position.y = -200;
  27800. * plane.receiveShadow = true;
  27801. * scene.add( plane );
  27802. * ```
  27803. *
  27804. * @augments Material
  27805. */
  27806. class ShadowMaterial extends Material {
  27807. /**
  27808. * Constructs a new shadow material.
  27809. *
  27810. * @param {Object} [parameters] - An object with one or more properties
  27811. * defining the material's appearance. Any property of the material
  27812. * (including any property from inherited materials) can be passed
  27813. * in here. Color values can be passed any type of value accepted
  27814. * by {@link Color#set}.
  27815. */
  27816. constructor( parameters ) {
  27817. super();
  27818. /**
  27819. * This flag can be used for type testing.
  27820. *
  27821. * @type {boolean}
  27822. * @readonly
  27823. * @default true
  27824. */
  27825. this.isShadowMaterial = true;
  27826. this.type = 'ShadowMaterial';
  27827. /**
  27828. * Color of the material.
  27829. *
  27830. * @type {Color}
  27831. * @default (0,0,0)
  27832. */
  27833. this.color = new Color( 0x000000 );
  27834. /**
  27835. * Overwritten since shadow materials are transparent
  27836. * by default.
  27837. *
  27838. * @type {boolean}
  27839. * @default true
  27840. */
  27841. this.transparent = true;
  27842. /**
  27843. * Whether the material is affected by fog or not.
  27844. *
  27845. * @type {boolean}
  27846. * @default true
  27847. */
  27848. this.fog = true;
  27849. this.setValues( parameters );
  27850. }
  27851. copy( source ) {
  27852. super.copy( source );
  27853. this.color.copy( source.color );
  27854. this.fog = source.fog;
  27855. return this;
  27856. }
  27857. }
  27858. /**
  27859. * This class works just like {@link ShaderMaterial}, except that definitions
  27860. * of built-in uniforms and attributes are not automatically prepended to the
  27861. * GLSL shader code.
  27862. *
  27863. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27864. *
  27865. * @augments ShaderMaterial
  27866. */
  27867. class RawShaderMaterial extends ShaderMaterial {
  27868. /**
  27869. * Constructs a new raw shader material.
  27870. *
  27871. * @param {Object} [parameters] - An object with one or more properties
  27872. * defining the material's appearance. Any property of the material
  27873. * (including any property from inherited materials) can be passed
  27874. * in here. Color values can be passed any type of value accepted
  27875. * by {@link Color#set}.
  27876. */
  27877. constructor( parameters ) {
  27878. super( parameters );
  27879. /**
  27880. * This flag can be used for type testing.
  27881. *
  27882. * @type {boolean}
  27883. * @readonly
  27884. * @default true
  27885. */
  27886. this.isRawShaderMaterial = true;
  27887. this.type = 'RawShaderMaterial';
  27888. }
  27889. }
  27890. /**
  27891. * A standard physically based material, using Metallic-Roughness workflow.
  27892. *
  27893. * Physically based rendering (PBR) has recently become the standard in many
  27894. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27895. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27896. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27897. *
  27898. * This approach differs from older approaches in that instead of using
  27899. * approximations for the way in which light interacts with a surface, a
  27900. * physically correct model is used. The idea is that, instead of tweaking
  27901. * materials to look good under specific lighting, a material can be created
  27902. * that will react 'correctly' under all lighting scenarios.
  27903. *
  27904. * In practice this gives a more accurate and realistic looking result than
  27905. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27906. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27907. * shading.
  27908. *
  27909. * Note that for best results you should always specify an environment map when using this material.
  27910. *
  27911. * For a non-technical introduction to the concept of PBR and how to set up a
  27912. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27913. *
  27914. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27915. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27916. *
  27917. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27918. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27919. * (pdf), by Brent Burley.
  27920. *
  27921. * @augments Material
  27922. * @demo scenes/material-browser.html#MeshStandardMaterial
  27923. */
  27924. class MeshStandardMaterial extends Material {
  27925. /**
  27926. * Constructs a new mesh standard material.
  27927. *
  27928. * @param {Object} [parameters] - An object with one or more properties
  27929. * defining the material's appearance. Any property of the material
  27930. * (including any property from inherited materials) can be passed
  27931. * in here. Color values can be passed any type of value accepted
  27932. * by {@link Color#set}.
  27933. */
  27934. constructor( parameters ) {
  27935. super();
  27936. /**
  27937. * This flag can be used for type testing.
  27938. *
  27939. * @type {boolean}
  27940. * @readonly
  27941. * @default true
  27942. */
  27943. this.isMeshStandardMaterial = true;
  27944. this.type = 'MeshStandardMaterial';
  27945. this.defines = { 'STANDARD': '' };
  27946. /**
  27947. * Color of the material.
  27948. *
  27949. * @type {Color}
  27950. * @default (1,1,1)
  27951. */
  27952. this.color = new Color( 0xffffff ); // diffuse
  27953. /**
  27954. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27955. * means fully diffuse. If `roughnessMap` is also provided,
  27956. * both values are multiplied.
  27957. *
  27958. * @type {number}
  27959. * @default 1
  27960. */
  27961. this.roughness = 1.0;
  27962. /**
  27963. * How much the material is like a metal. Non-metallic materials such as wood
  27964. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27965. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27966. * If `metalnessMap` is also provided, both values are multiplied.
  27967. *
  27968. * @type {number}
  27969. * @default 0
  27970. */
  27971. this.metalness = 0.0;
  27972. /**
  27973. * The color map. May optionally include an alpha channel, typically combined
  27974. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27975. * color is modulated by the diffuse `color`.
  27976. *
  27977. * @type {?Texture}
  27978. * @default null
  27979. */
  27980. this.map = null;
  27981. /**
  27982. * The light map. Requires a second set of UVs.
  27983. *
  27984. * @type {?Texture}
  27985. * @default null
  27986. */
  27987. this.lightMap = null;
  27988. /**
  27989. * Intensity of the baked light.
  27990. *
  27991. * @type {number}
  27992. * @default 1
  27993. */
  27994. this.lightMapIntensity = 1.0;
  27995. /**
  27996. * The red channel of this texture is used as the ambient occlusion map.
  27997. * Requires a second set of UVs.
  27998. *
  27999. * @type {?Texture}
  28000. * @default null
  28001. */
  28002. this.aoMap = null;
  28003. /**
  28004. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28005. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28006. * red channel is also `1`, ambient light is fully occluded on a surface.
  28007. *
  28008. * @type {number}
  28009. * @default 1
  28010. */
  28011. this.aoMapIntensity = 1.0;
  28012. /**
  28013. * Emissive (light) color of the material, essentially a solid color
  28014. * unaffected by other lighting.
  28015. *
  28016. * @type {Color}
  28017. * @default (0,0,0)
  28018. */
  28019. this.emissive = new Color( 0x000000 );
  28020. /**
  28021. * Intensity of the emissive light. Modulates the emissive color.
  28022. *
  28023. * @type {number}
  28024. * @default 1
  28025. */
  28026. this.emissiveIntensity = 1.0;
  28027. /**
  28028. * Set emissive (glow) map. The emissive map color is modulated by the
  28029. * emissive color and the emissive intensity. If you have an emissive map,
  28030. * be sure to set the emissive color to something other than black.
  28031. *
  28032. * @type {?Texture}
  28033. * @default null
  28034. */
  28035. this.emissiveMap = null;
  28036. /**
  28037. * The texture to create a bump map. The black and white values map to the
  28038. * perceived depth in relation to the lights. Bump doesn't actually affect
  28039. * the geometry of the object, only the lighting. If a normal map is defined
  28040. * this will be ignored.
  28041. *
  28042. * @type {?Texture}
  28043. * @default null
  28044. */
  28045. this.bumpMap = null;
  28046. /**
  28047. * How much the bump map affects the material. Typical range is `[0,1]`.
  28048. *
  28049. * @type {number}
  28050. * @default 1
  28051. */
  28052. this.bumpScale = 1;
  28053. /**
  28054. * The texture to create a normal map. The RGB values affect the surface
  28055. * normal for each pixel fragment and change the way the color is lit. Normal
  28056. * maps do not change the actual shape of the surface, only the lighting. In
  28057. * case the material has a normal map authored using the left handed
  28058. * convention, the `y` component of `normalScale` should be negated to compensate
  28059. * for the different handedness.
  28060. *
  28061. * @type {?Texture}
  28062. * @default null
  28063. */
  28064. this.normalMap = null;
  28065. /**
  28066. * The type of normal map.
  28067. *
  28068. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28069. * @default TangentSpaceNormalMap
  28070. */
  28071. this.normalMapType = TangentSpaceNormalMap;
  28072. /**
  28073. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28074. *
  28075. * @type {Vector2}
  28076. * @default (1,1)
  28077. */
  28078. this.normalScale = new Vector2( 1, 1 );
  28079. /**
  28080. * The displacement map affects the position of the mesh's vertices. Unlike
  28081. * other maps which only affect the light and shade of the material the
  28082. * displaced vertices can cast shadows, block other objects, and otherwise
  28083. * act as real geometry. The displacement texture is an image where the value
  28084. * of each pixel (white being the highest) is mapped against, and
  28085. * repositions, the vertices of the mesh.
  28086. *
  28087. * @type {?Texture}
  28088. * @default null
  28089. */
  28090. this.displacementMap = null;
  28091. /**
  28092. * How much the displacement map affects the mesh (where black is no
  28093. * displacement, and white is maximum displacement). Without a displacement
  28094. * map set, this value is not applied.
  28095. *
  28096. * @type {number}
  28097. * @default 0
  28098. */
  28099. this.displacementScale = 1;
  28100. /**
  28101. * The offset of the displacement map's values on the mesh's vertices.
  28102. * The bias is added to the scaled sample of the displacement map.
  28103. * Without a displacement map set, this value is not applied.
  28104. *
  28105. * @type {number}
  28106. * @default 0
  28107. */
  28108. this.displacementBias = 0;
  28109. /**
  28110. * The green channel of this texture is used to alter the roughness of the
  28111. * material.
  28112. *
  28113. * @type {?Texture}
  28114. * @default null
  28115. */
  28116. this.roughnessMap = null;
  28117. /**
  28118. * The blue channel of this texture is used to alter the metalness of the
  28119. * material.
  28120. *
  28121. * @type {?Texture}
  28122. * @default null
  28123. */
  28124. this.metalnessMap = null;
  28125. /**
  28126. * The alpha map is a grayscale texture that controls the opacity across the
  28127. * surface (black: fully transparent; white: fully opaque).
  28128. *
  28129. * Only the color of the texture is used, ignoring the alpha channel if one
  28130. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28131. * when sampling this texture due to the extra bit of precision provided for
  28132. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28133. * luminance/alpha textures will also still work as expected.
  28134. *
  28135. * @type {?Texture}
  28136. * @default null
  28137. */
  28138. this.alphaMap = null;
  28139. /**
  28140. * The environment map. To ensure a physically correct rendering, environment maps
  28141. * are internally pre-processed with {@link PMREMGenerator}.
  28142. *
  28143. * @type {?Texture}
  28144. * @default null
  28145. */
  28146. this.envMap = null;
  28147. /**
  28148. * The rotation of the environment map in radians.
  28149. *
  28150. * @type {Euler}
  28151. * @default (0,0,0)
  28152. */
  28153. this.envMapRotation = new Euler();
  28154. /**
  28155. * Scales the effect of the environment map by multiplying its color.
  28156. *
  28157. * @type {number}
  28158. * @default 1
  28159. */
  28160. this.envMapIntensity = 1.0;
  28161. /**
  28162. * Renders the geometry as a wireframe.
  28163. *
  28164. * @type {boolean}
  28165. * @default false
  28166. */
  28167. this.wireframe = false;
  28168. /**
  28169. * Controls the thickness of the wireframe.
  28170. *
  28171. * Can only be used with {@link SVGRenderer}.
  28172. *
  28173. * @type {number}
  28174. * @default 1
  28175. */
  28176. this.wireframeLinewidth = 1;
  28177. /**
  28178. * Defines appearance of wireframe ends.
  28179. *
  28180. * Can only be used with {@link SVGRenderer}.
  28181. *
  28182. * @type {('round'|'bevel'|'miter')}
  28183. * @default 'round'
  28184. */
  28185. this.wireframeLinecap = 'round';
  28186. /**
  28187. * Defines appearance of wireframe joints.
  28188. *
  28189. * Can only be used with {@link SVGRenderer}.
  28190. *
  28191. * @type {('round'|'bevel'|'miter')}
  28192. * @default 'round'
  28193. */
  28194. this.wireframeLinejoin = 'round';
  28195. /**
  28196. * Whether the material is rendered with flat shading or not.
  28197. *
  28198. * @type {boolean}
  28199. * @default false
  28200. */
  28201. this.flatShading = false;
  28202. /**
  28203. * Whether the material is affected by fog or not.
  28204. *
  28205. * @type {boolean}
  28206. * @default true
  28207. */
  28208. this.fog = true;
  28209. this.setValues( parameters );
  28210. }
  28211. copy( source ) {
  28212. super.copy( source );
  28213. this.defines = { 'STANDARD': '' };
  28214. this.color.copy( source.color );
  28215. this.roughness = source.roughness;
  28216. this.metalness = source.metalness;
  28217. this.map = source.map;
  28218. this.lightMap = source.lightMap;
  28219. this.lightMapIntensity = source.lightMapIntensity;
  28220. this.aoMap = source.aoMap;
  28221. this.aoMapIntensity = source.aoMapIntensity;
  28222. this.emissive.copy( source.emissive );
  28223. this.emissiveMap = source.emissiveMap;
  28224. this.emissiveIntensity = source.emissiveIntensity;
  28225. this.bumpMap = source.bumpMap;
  28226. this.bumpScale = source.bumpScale;
  28227. this.normalMap = source.normalMap;
  28228. this.normalMapType = source.normalMapType;
  28229. this.normalScale.copy( source.normalScale );
  28230. this.displacementMap = source.displacementMap;
  28231. this.displacementScale = source.displacementScale;
  28232. this.displacementBias = source.displacementBias;
  28233. this.roughnessMap = source.roughnessMap;
  28234. this.metalnessMap = source.metalnessMap;
  28235. this.alphaMap = source.alphaMap;
  28236. this.envMap = source.envMap;
  28237. this.envMapRotation.copy( source.envMapRotation );
  28238. this.envMapIntensity = source.envMapIntensity;
  28239. this.wireframe = source.wireframe;
  28240. this.wireframeLinewidth = source.wireframeLinewidth;
  28241. this.wireframeLinecap = source.wireframeLinecap;
  28242. this.wireframeLinejoin = source.wireframeLinejoin;
  28243. this.flatShading = source.flatShading;
  28244. this.fog = source.fog;
  28245. return this;
  28246. }
  28247. }
  28248. /**
  28249. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28250. * physically-based rendering properties:
  28251. *
  28252. * - Anisotropy: Ability to represent the anisotropic property of materials
  28253. * as observable with brushed metals.
  28254. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28255. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28256. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28257. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28258. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28259. * wings of many insects.
  28260. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28261. * transparent materials are less reflective. Physically-based transmission provides a more
  28262. * realistic option for thin, transparent surfaces like glass.
  28263. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28264. * - Sheen: Can be used for representing cloth and fabric materials.
  28265. *
  28266. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28267. * higher performance cost, per pixel, than other three.js materials. Most
  28268. * effects are disabled by default, and add cost as they are enabled. For
  28269. * best results, always specify an environment map when using this material.
  28270. *
  28271. * @augments MeshStandardMaterial
  28272. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28273. */
  28274. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28275. /**
  28276. * Constructs a new mesh physical material.
  28277. *
  28278. * @param {Object} [parameters] - An object with one or more properties
  28279. * defining the material's appearance. Any property of the material
  28280. * (including any property from inherited materials) can be passed
  28281. * in here. Color values can be passed any type of value accepted
  28282. * by {@link Color#set}.
  28283. */
  28284. constructor( parameters ) {
  28285. super();
  28286. /**
  28287. * This flag can be used for type testing.
  28288. *
  28289. * @type {boolean}
  28290. * @readonly
  28291. * @default true
  28292. */
  28293. this.isMeshPhysicalMaterial = true;
  28294. this.defines = {
  28295. 'STANDARD': '',
  28296. 'PHYSICAL': ''
  28297. };
  28298. this.type = 'MeshPhysicalMaterial';
  28299. /**
  28300. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28301. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28302. * property provides additional rotation to the vectors in the texture.
  28303. *
  28304. * @type {number}
  28305. * @default 1
  28306. */
  28307. this.anisotropyRotation = 0;
  28308. /**
  28309. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28310. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28311. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28312. *
  28313. * @type {?Texture}
  28314. * @default null
  28315. */
  28316. this.anisotropyMap = null;
  28317. /**
  28318. * The red channel of this texture is multiplied against `clearcoat`,
  28319. * for per-pixel control over a coating's intensity.
  28320. *
  28321. * @type {?Texture}
  28322. * @default null
  28323. */
  28324. this.clearcoatMap = null;
  28325. /**
  28326. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28327. *
  28328. * @type {number}
  28329. * @default 0
  28330. */
  28331. this.clearcoatRoughness = 0.0;
  28332. /**
  28333. * The green channel of this texture is multiplied against
  28334. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28335. *
  28336. * @type {?Texture}
  28337. * @default null
  28338. */
  28339. this.clearcoatRoughnessMap = null;
  28340. /**
  28341. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28342. * `(0,0)` to `(1,1)`.
  28343. *
  28344. * @type {Vector2}
  28345. * @default (1,1)
  28346. */
  28347. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28348. /**
  28349. * Can be used to enable independent normals for the clear coat layer.
  28350. *
  28351. * @type {?Texture}
  28352. * @default null
  28353. */
  28354. this.clearcoatNormalMap = null;
  28355. /**
  28356. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28357. *
  28358. * @type {number}
  28359. * @default 1.5
  28360. */
  28361. this.ior = 1.5;
  28362. /**
  28363. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28364. * corresponds to an index-of-refraction of `1.5`.
  28365. *
  28366. * This models the reflectivity of non-metallic materials. It has no effect
  28367. * when `metalness` is `1.0`
  28368. *
  28369. * @name MeshPhysicalMaterial#reflectivity
  28370. * @type {number}
  28371. * @default 0.5
  28372. */
  28373. Object.defineProperty( this, 'reflectivity', {
  28374. get: function () {
  28375. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28376. },
  28377. set: function ( reflectivity ) {
  28378. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28379. }
  28380. } );
  28381. /**
  28382. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28383. * control over iridescence.
  28384. *
  28385. * @type {?Texture}
  28386. * @default null
  28387. */
  28388. this.iridescenceMap = null;
  28389. /**
  28390. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28391. * Between `1.0` to `2.333`.
  28392. *
  28393. * @type {number}
  28394. * @default 1.3
  28395. */
  28396. this.iridescenceIOR = 1.3;
  28397. /**
  28398. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28399. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28400. *
  28401. * @type {Array<number,number>}
  28402. * @default [100,400]
  28403. */
  28404. this.iridescenceThicknessRange = [ 100, 400 ];
  28405. /**
  28406. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28407. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28408. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28409. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28410. * - Values in-between will linearly interpolate between the elements of the array.
  28411. *
  28412. * @type {?Texture}
  28413. * @default null
  28414. */
  28415. this.iridescenceThicknessMap = null;
  28416. /**
  28417. * The sheen tint.
  28418. *
  28419. * @type {Color}
  28420. * @default (0,0,0)
  28421. */
  28422. this.sheenColor = new Color( 0x000000 );
  28423. /**
  28424. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28425. * over sheen tint.
  28426. *
  28427. * @type {?Texture}
  28428. * @default null
  28429. */
  28430. this.sheenColorMap = null;
  28431. /**
  28432. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28433. *
  28434. * @type {number}
  28435. * @default 1
  28436. */
  28437. this.sheenRoughness = 1.0;
  28438. /**
  28439. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28440. * over sheen roughness.
  28441. *
  28442. * @type {?Texture}
  28443. * @default null
  28444. */
  28445. this.sheenRoughnessMap = null;
  28446. /**
  28447. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28448. * optical transparency.
  28449. *
  28450. * @type {?Texture}
  28451. * @default null
  28452. */
  28453. this.transmissionMap = null;
  28454. /**
  28455. * The thickness of the volume beneath the surface. The value is given in the
  28456. * coordinate space of the mesh. If the value is `0` the material is
  28457. * thin-walled. Otherwise the material is a volume boundary.
  28458. *
  28459. * @type {number}
  28460. * @default 0
  28461. */
  28462. this.thickness = 0;
  28463. /**
  28464. * A texture that defines the thickness, stored in the green channel. This will
  28465. * be multiplied by `thickness`.
  28466. *
  28467. * @type {?Texture}
  28468. * @default null
  28469. */
  28470. this.thicknessMap = null;
  28471. /**
  28472. * Density of the medium given as the average distance that light travels in
  28473. * the medium before interacting with a particle. The value is given in world
  28474. * space units, and must be greater than zero.
  28475. *
  28476. * @type {number}
  28477. * @default Infinity
  28478. */
  28479. this.attenuationDistance = Infinity;
  28480. /**
  28481. * The color that white light turns into due to absorption when reaching the
  28482. * attenuation distance.
  28483. *
  28484. * @type {Color}
  28485. * @default (1,1,1)
  28486. */
  28487. this.attenuationColor = new Color( 1, 1, 1 );
  28488. /**
  28489. * A float that scales the amount of specular reflection for non-metals only.
  28490. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28491. *
  28492. * @type {number}
  28493. * @default 1
  28494. */
  28495. this.specularIntensity = 1.0;
  28496. /**
  28497. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28498. * for per-pixel control over specular intensity.
  28499. *
  28500. * @type {?Texture}
  28501. * @default null
  28502. */
  28503. this.specularIntensityMap = null;
  28504. /**
  28505. * Tints the specular reflection at normal incidence for non-metals only.
  28506. *
  28507. * @type {Color}
  28508. * @default (1,1,1)
  28509. */
  28510. this.specularColor = new Color( 1, 1, 1 );
  28511. /**
  28512. * The RGB channels of this texture are multiplied against `specularColor`,
  28513. * for per-pixel control over specular color.
  28514. *
  28515. * @type {?Texture}
  28516. * @default null
  28517. */
  28518. this.specularColorMap = null;
  28519. this._anisotropy = 0;
  28520. this._clearcoat = 0;
  28521. this._dispersion = 0;
  28522. this._iridescence = 0;
  28523. this._sheen = 0.0;
  28524. this._transmission = 0;
  28525. this.setValues( parameters );
  28526. }
  28527. /**
  28528. * The anisotropy strength, from `0.0` to `1.0`.
  28529. *
  28530. * @type {number}
  28531. * @default 0
  28532. */
  28533. get anisotropy() {
  28534. return this._anisotropy;
  28535. }
  28536. set anisotropy( value ) {
  28537. if ( this._anisotropy > 0 !== value > 0 ) {
  28538. this.version ++;
  28539. }
  28540. this._anisotropy = value;
  28541. }
  28542. /**
  28543. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28544. * clear coat related properties to enable multilayer materials that have a
  28545. * thin translucent layer over the base layer.
  28546. *
  28547. * @type {number}
  28548. * @default 0
  28549. */
  28550. get clearcoat() {
  28551. return this._clearcoat;
  28552. }
  28553. set clearcoat( value ) {
  28554. if ( this._clearcoat > 0 !== value > 0 ) {
  28555. this.version ++;
  28556. }
  28557. this._clearcoat = value;
  28558. }
  28559. /**
  28560. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28561. * the surface and the viewer, from `0.0` to `1.0`.
  28562. *
  28563. * @type {number}
  28564. * @default 0
  28565. */
  28566. get iridescence() {
  28567. return this._iridescence;
  28568. }
  28569. set iridescence( value ) {
  28570. if ( this._iridescence > 0 !== value > 0 ) {
  28571. this.version ++;
  28572. }
  28573. this._iridescence = value;
  28574. }
  28575. /**
  28576. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28577. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28578. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28579. *
  28580. * @type {number}
  28581. * @default 0
  28582. */
  28583. get dispersion() {
  28584. return this._dispersion;
  28585. }
  28586. set dispersion( value ) {
  28587. if ( this._dispersion > 0 !== value > 0 ) {
  28588. this.version ++;
  28589. }
  28590. this._dispersion = value;
  28591. }
  28592. /**
  28593. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28594. *
  28595. * @type {number}
  28596. * @default 0
  28597. */
  28598. get sheen() {
  28599. return this._sheen;
  28600. }
  28601. set sheen( value ) {
  28602. if ( this._sheen > 0 !== value > 0 ) {
  28603. this.version ++;
  28604. }
  28605. this._sheen = value;
  28606. }
  28607. /**
  28608. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28609. *
  28610. * Thin, transparent or semitransparent, plastic or glass materials remain
  28611. * largely reflective even if they are fully transmissive. The transmission
  28612. * property can be used to model these materials.
  28613. *
  28614. * When transmission is non-zero, `opacity` should be set to `1`.
  28615. *
  28616. * @type {number}
  28617. * @default 0
  28618. */
  28619. get transmission() {
  28620. return this._transmission;
  28621. }
  28622. set transmission( value ) {
  28623. if ( this._transmission > 0 !== value > 0 ) {
  28624. this.version ++;
  28625. }
  28626. this._transmission = value;
  28627. }
  28628. copy( source ) {
  28629. super.copy( source );
  28630. this.defines = {
  28631. 'STANDARD': '',
  28632. 'PHYSICAL': ''
  28633. };
  28634. this.anisotropy = source.anisotropy;
  28635. this.anisotropyRotation = source.anisotropyRotation;
  28636. this.anisotropyMap = source.anisotropyMap;
  28637. this.clearcoat = source.clearcoat;
  28638. this.clearcoatMap = source.clearcoatMap;
  28639. this.clearcoatRoughness = source.clearcoatRoughness;
  28640. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28641. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28642. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28643. this.dispersion = source.dispersion;
  28644. this.ior = source.ior;
  28645. this.iridescence = source.iridescence;
  28646. this.iridescenceMap = source.iridescenceMap;
  28647. this.iridescenceIOR = source.iridescenceIOR;
  28648. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28649. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28650. this.sheen = source.sheen;
  28651. this.sheenColor.copy( source.sheenColor );
  28652. this.sheenColorMap = source.sheenColorMap;
  28653. this.sheenRoughness = source.sheenRoughness;
  28654. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28655. this.transmission = source.transmission;
  28656. this.transmissionMap = source.transmissionMap;
  28657. this.thickness = source.thickness;
  28658. this.thicknessMap = source.thicknessMap;
  28659. this.attenuationDistance = source.attenuationDistance;
  28660. this.attenuationColor.copy( source.attenuationColor );
  28661. this.specularIntensity = source.specularIntensity;
  28662. this.specularIntensityMap = source.specularIntensityMap;
  28663. this.specularColor.copy( source.specularColor );
  28664. this.specularColorMap = source.specularColorMap;
  28665. return this;
  28666. }
  28667. }
  28668. /**
  28669. * A material for shiny surfaces with specular highlights.
  28670. *
  28671. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28672. * model for calculating reflectance. Unlike the Lambertian model used in the
  28673. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28674. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28675. *
  28676. * Performance will generally be greater when using this material over the
  28677. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28678. * some graphical accuracy.
  28679. *
  28680. * @augments Material
  28681. * @demo scenes/material-browser.html#MeshPhongMaterial
  28682. */
  28683. class MeshPhongMaterial extends Material {
  28684. /**
  28685. * Constructs a new mesh phong material.
  28686. *
  28687. * @param {Object} [parameters] - An object with one or more properties
  28688. * defining the material's appearance. Any property of the material
  28689. * (including any property from inherited materials) can be passed
  28690. * in here. Color values can be passed any type of value accepted
  28691. * by {@link Color#set}.
  28692. */
  28693. constructor( parameters ) {
  28694. super();
  28695. /**
  28696. * This flag can be used for type testing.
  28697. *
  28698. * @type {boolean}
  28699. * @readonly
  28700. * @default true
  28701. */
  28702. this.isMeshPhongMaterial = true;
  28703. this.type = 'MeshPhongMaterial';
  28704. /**
  28705. * Color of the material.
  28706. *
  28707. * @type {Color}
  28708. * @default (1,1,1)
  28709. */
  28710. this.color = new Color( 0xffffff ); // diffuse
  28711. /**
  28712. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28713. *
  28714. * This defines how shiny the material is and the color of its shine.
  28715. *
  28716. * @type {Color}
  28717. */
  28718. this.specular = new Color( 0x111111 );
  28719. /**
  28720. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28721. *
  28722. * @type {number}
  28723. * @default 30
  28724. */
  28725. this.shininess = 30;
  28726. /**
  28727. * The color map. May optionally include an alpha channel, typically combined
  28728. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28729. * color is modulated by the diffuse `color`.
  28730. *
  28731. * @type {?Texture}
  28732. * @default null
  28733. */
  28734. this.map = null;
  28735. /**
  28736. * The light map. Requires a second set of UVs.
  28737. *
  28738. * @type {?Texture}
  28739. * @default null
  28740. */
  28741. this.lightMap = null;
  28742. /**
  28743. * Intensity of the baked light.
  28744. *
  28745. * @type {number}
  28746. * @default 1
  28747. */
  28748. this.lightMapIntensity = 1.0;
  28749. /**
  28750. * The red channel of this texture is used as the ambient occlusion map.
  28751. * Requires a second set of UVs.
  28752. *
  28753. * @type {?Texture}
  28754. * @default null
  28755. */
  28756. this.aoMap = null;
  28757. /**
  28758. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28759. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28760. * red channel is also `1`, ambient light is fully occluded on a surface.
  28761. *
  28762. * @type {number}
  28763. * @default 1
  28764. */
  28765. this.aoMapIntensity = 1.0;
  28766. /**
  28767. * Emissive (light) color of the material, essentially a solid color
  28768. * unaffected by other lighting.
  28769. *
  28770. * @type {Color}
  28771. * @default (0,0,0)
  28772. */
  28773. this.emissive = new Color( 0x000000 );
  28774. /**
  28775. * Intensity of the emissive light. Modulates the emissive color.
  28776. *
  28777. * @type {number}
  28778. * @default 1
  28779. */
  28780. this.emissiveIntensity = 1.0;
  28781. /**
  28782. * Set emissive (glow) map. The emissive map color is modulated by the
  28783. * emissive color and the emissive intensity. If you have an emissive map,
  28784. * be sure to set the emissive color to something other than black.
  28785. *
  28786. * @type {?Texture}
  28787. * @default null
  28788. */
  28789. this.emissiveMap = null;
  28790. /**
  28791. * The texture to create a bump map. The black and white values map to the
  28792. * perceived depth in relation to the lights. Bump doesn't actually affect
  28793. * the geometry of the object, only the lighting. If a normal map is defined
  28794. * this will be ignored.
  28795. *
  28796. * @type {?Texture}
  28797. * @default null
  28798. */
  28799. this.bumpMap = null;
  28800. /**
  28801. * How much the bump map affects the material. Typical range is `[0,1]`.
  28802. *
  28803. * @type {number}
  28804. * @default 1
  28805. */
  28806. this.bumpScale = 1;
  28807. /**
  28808. * The texture to create a normal map. The RGB values affect the surface
  28809. * normal for each pixel fragment and change the way the color is lit. Normal
  28810. * maps do not change the actual shape of the surface, only the lighting. In
  28811. * case the material has a normal map authored using the left handed
  28812. * convention, the `y` component of `normalScale` should be negated to compensate
  28813. * for the different handedness.
  28814. *
  28815. * @type {?Texture}
  28816. * @default null
  28817. */
  28818. this.normalMap = null;
  28819. /**
  28820. * The type of normal map.
  28821. *
  28822. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28823. * @default TangentSpaceNormalMap
  28824. */
  28825. this.normalMapType = TangentSpaceNormalMap;
  28826. /**
  28827. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28828. *
  28829. * @type {Vector2}
  28830. * @default (1,1)
  28831. */
  28832. this.normalScale = new Vector2( 1, 1 );
  28833. /**
  28834. * The displacement map affects the position of the mesh's vertices. Unlike
  28835. * other maps which only affect the light and shade of the material the
  28836. * displaced vertices can cast shadows, block other objects, and otherwise
  28837. * act as real geometry. The displacement texture is an image where the value
  28838. * of each pixel (white being the highest) is mapped against, and
  28839. * repositions, the vertices of the mesh.
  28840. *
  28841. * @type {?Texture}
  28842. * @default null
  28843. */
  28844. this.displacementMap = null;
  28845. /**
  28846. * How much the displacement map affects the mesh (where black is no
  28847. * displacement, and white is maximum displacement). Without a displacement
  28848. * map set, this value is not applied.
  28849. *
  28850. * @type {number}
  28851. * @default 0
  28852. */
  28853. this.displacementScale = 1;
  28854. /**
  28855. * The offset of the displacement map's values on the mesh's vertices.
  28856. * The bias is added to the scaled sample of the displacement map.
  28857. * Without a displacement map set, this value is not applied.
  28858. *
  28859. * @type {number}
  28860. * @default 0
  28861. */
  28862. this.displacementBias = 0;
  28863. /**
  28864. * The specular map value affects both how much the specular surface
  28865. * highlight contributes and how much of the environment map affects the
  28866. * surface.
  28867. *
  28868. * @type {?Texture}
  28869. * @default null
  28870. */
  28871. this.specularMap = null;
  28872. /**
  28873. * The alpha map is a grayscale texture that controls the opacity across the
  28874. * surface (black: fully transparent; white: fully opaque).
  28875. *
  28876. * Only the color of the texture is used, ignoring the alpha channel if one
  28877. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28878. * when sampling this texture due to the extra bit of precision provided for
  28879. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28880. * luminance/alpha textures will also still work as expected.
  28881. *
  28882. * @type {?Texture}
  28883. * @default null
  28884. */
  28885. this.alphaMap = null;
  28886. /**
  28887. * The environment map.
  28888. *
  28889. * @type {?Texture}
  28890. * @default null
  28891. */
  28892. this.envMap = null;
  28893. /**
  28894. * The rotation of the environment map in radians.
  28895. *
  28896. * @type {Euler}
  28897. * @default (0,0,0)
  28898. */
  28899. this.envMapRotation = new Euler();
  28900. /**
  28901. * How to combine the result of the surface's color with the environment map, if any.
  28902. *
  28903. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28904. * blend between the two colors.
  28905. *
  28906. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28907. * @default MultiplyOperation
  28908. */
  28909. this.combine = MultiplyOperation;
  28910. /**
  28911. * How much the environment map affects the surface.
  28912. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28913. *
  28914. * @type {number}
  28915. * @default 1
  28916. */
  28917. this.reflectivity = 1;
  28918. /**
  28919. * The index of refraction (IOR) of air (approximately 1) divided by the
  28920. * index of refraction of the material. It is used with environment mapping
  28921. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28922. * The refraction ratio should not exceed `1`.
  28923. *
  28924. * @type {number}
  28925. * @default 0.98
  28926. */
  28927. this.refractionRatio = 0.98;
  28928. /**
  28929. * Renders the geometry as a wireframe.
  28930. *
  28931. * @type {boolean}
  28932. * @default false
  28933. */
  28934. this.wireframe = false;
  28935. /**
  28936. * Controls the thickness of the wireframe.
  28937. *
  28938. * Can only be used with {@link SVGRenderer}.
  28939. *
  28940. * @type {number}
  28941. * @default 1
  28942. */
  28943. this.wireframeLinewidth = 1;
  28944. /**
  28945. * Defines appearance of wireframe ends.
  28946. *
  28947. * Can only be used with {@link SVGRenderer}.
  28948. *
  28949. * @type {('round'|'bevel'|'miter')}
  28950. * @default 'round'
  28951. */
  28952. this.wireframeLinecap = 'round';
  28953. /**
  28954. * Defines appearance of wireframe joints.
  28955. *
  28956. * Can only be used with {@link SVGRenderer}.
  28957. *
  28958. * @type {('round'|'bevel'|'miter')}
  28959. * @default 'round'
  28960. */
  28961. this.wireframeLinejoin = 'round';
  28962. /**
  28963. * Whether the material is rendered with flat shading or not.
  28964. *
  28965. * @type {boolean}
  28966. * @default false
  28967. */
  28968. this.flatShading = false;
  28969. /**
  28970. * Whether the material is affected by fog or not.
  28971. *
  28972. * @type {boolean}
  28973. * @default true
  28974. */
  28975. this.fog = true;
  28976. this.setValues( parameters );
  28977. }
  28978. copy( source ) {
  28979. super.copy( source );
  28980. this.color.copy( source.color );
  28981. this.specular.copy( source.specular );
  28982. this.shininess = source.shininess;
  28983. this.map = source.map;
  28984. this.lightMap = source.lightMap;
  28985. this.lightMapIntensity = source.lightMapIntensity;
  28986. this.aoMap = source.aoMap;
  28987. this.aoMapIntensity = source.aoMapIntensity;
  28988. this.emissive.copy( source.emissive );
  28989. this.emissiveMap = source.emissiveMap;
  28990. this.emissiveIntensity = source.emissiveIntensity;
  28991. this.bumpMap = source.bumpMap;
  28992. this.bumpScale = source.bumpScale;
  28993. this.normalMap = source.normalMap;
  28994. this.normalMapType = source.normalMapType;
  28995. this.normalScale.copy( source.normalScale );
  28996. this.displacementMap = source.displacementMap;
  28997. this.displacementScale = source.displacementScale;
  28998. this.displacementBias = source.displacementBias;
  28999. this.specularMap = source.specularMap;
  29000. this.alphaMap = source.alphaMap;
  29001. this.envMap = source.envMap;
  29002. this.envMapRotation.copy( source.envMapRotation );
  29003. this.combine = source.combine;
  29004. this.reflectivity = source.reflectivity;
  29005. this.refractionRatio = source.refractionRatio;
  29006. this.wireframe = source.wireframe;
  29007. this.wireframeLinewidth = source.wireframeLinewidth;
  29008. this.wireframeLinecap = source.wireframeLinecap;
  29009. this.wireframeLinejoin = source.wireframeLinejoin;
  29010. this.flatShading = source.flatShading;
  29011. this.fog = source.fog;
  29012. return this;
  29013. }
  29014. }
  29015. /**
  29016. * A material implementing toon shading.
  29017. *
  29018. * @augments Material
  29019. * @demo scenes/material-browser.html#MeshToonMaterial
  29020. */
  29021. class MeshToonMaterial extends Material {
  29022. /**
  29023. * Constructs a new mesh toon material.
  29024. *
  29025. * @param {Object} [parameters] - An object with one or more properties
  29026. * defining the material's appearance. Any property of the material
  29027. * (including any property from inherited materials) can be passed
  29028. * in here. Color values can be passed any type of value accepted
  29029. * by {@link Color#set}.
  29030. */
  29031. constructor( parameters ) {
  29032. super();
  29033. /**
  29034. * This flag can be used for type testing.
  29035. *
  29036. * @type {boolean}
  29037. * @readonly
  29038. * @default true
  29039. */
  29040. this.isMeshToonMaterial = true;
  29041. this.defines = { 'TOON': '' };
  29042. this.type = 'MeshToonMaterial';
  29043. /**
  29044. * Color of the material.
  29045. *
  29046. * @type {Color}
  29047. * @default (1,1,1)
  29048. */
  29049. this.color = new Color( 0xffffff );
  29050. /**
  29051. * The color map. May optionally include an alpha channel, typically combined
  29052. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29053. * color is modulated by the diffuse `color`.
  29054. *
  29055. * @type {?Texture}
  29056. * @default null
  29057. */
  29058. this.map = null;
  29059. /**
  29060. * Gradient map for toon shading. It's required to set
  29061. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29062. * when using this type of texture.
  29063. *
  29064. * @type {?Texture}
  29065. * @default null
  29066. */
  29067. this.gradientMap = null;
  29068. /**
  29069. * The light map. Requires a second set of UVs.
  29070. *
  29071. * @type {?Texture}
  29072. * @default null
  29073. */
  29074. this.lightMap = null;
  29075. /**
  29076. * Intensity of the baked light.
  29077. *
  29078. * @type {number}
  29079. * @default 1
  29080. */
  29081. this.lightMapIntensity = 1.0;
  29082. /**
  29083. * The red channel of this texture is used as the ambient occlusion map.
  29084. * Requires a second set of UVs.
  29085. *
  29086. * @type {?Texture}
  29087. * @default null
  29088. */
  29089. this.aoMap = null;
  29090. /**
  29091. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29092. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29093. * red channel is also `1`, ambient light is fully occluded on a surface.
  29094. *
  29095. * @type {number}
  29096. * @default 1
  29097. */
  29098. this.aoMapIntensity = 1.0;
  29099. /**
  29100. * Emissive (light) color of the material, essentially a solid color
  29101. * unaffected by other lighting.
  29102. *
  29103. * @type {Color}
  29104. * @default (0,0,0)
  29105. */
  29106. this.emissive = new Color( 0x000000 );
  29107. /**
  29108. * Intensity of the emissive light. Modulates the emissive color.
  29109. *
  29110. * @type {number}
  29111. * @default 1
  29112. */
  29113. this.emissiveIntensity = 1.0;
  29114. /**
  29115. * Set emissive (glow) map. The emissive map color is modulated by the
  29116. * emissive color and the emissive intensity. If you have an emissive map,
  29117. * be sure to set the emissive color to something other than black.
  29118. *
  29119. * @type {?Texture}
  29120. * @default null
  29121. */
  29122. this.emissiveMap = null;
  29123. /**
  29124. * The texture to create a bump map. The black and white values map to the
  29125. * perceived depth in relation to the lights. Bump doesn't actually affect
  29126. * the geometry of the object, only the lighting. If a normal map is defined
  29127. * this will be ignored.
  29128. *
  29129. * @type {?Texture}
  29130. * @default null
  29131. */
  29132. this.bumpMap = null;
  29133. /**
  29134. * How much the bump map affects the material. Typical range is `[0,1]`.
  29135. *
  29136. * @type {number}
  29137. * @default 1
  29138. */
  29139. this.bumpScale = 1;
  29140. /**
  29141. * The texture to create a normal map. The RGB values affect the surface
  29142. * normal for each pixel fragment and change the way the color is lit. Normal
  29143. * maps do not change the actual shape of the surface, only the lighting. In
  29144. * case the material has a normal map authored using the left handed
  29145. * convention, the `y` component of `normalScale` should be negated to compensate
  29146. * for the different handedness.
  29147. *
  29148. * @type {?Texture}
  29149. * @default null
  29150. */
  29151. this.normalMap = null;
  29152. /**
  29153. * The type of normal map.
  29154. *
  29155. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29156. * @default TangentSpaceNormalMap
  29157. */
  29158. this.normalMapType = TangentSpaceNormalMap;
  29159. /**
  29160. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29161. *
  29162. * @type {Vector2}
  29163. * @default (1,1)
  29164. */
  29165. this.normalScale = new Vector2( 1, 1 );
  29166. /**
  29167. * The displacement map affects the position of the mesh's vertices. Unlike
  29168. * other maps which only affect the light and shade of the material the
  29169. * displaced vertices can cast shadows, block other objects, and otherwise
  29170. * act as real geometry. The displacement texture is an image where the value
  29171. * of each pixel (white being the highest) is mapped against, and
  29172. * repositions, the vertices of the mesh.
  29173. *
  29174. * @type {?Texture}
  29175. * @default null
  29176. */
  29177. this.displacementMap = null;
  29178. /**
  29179. * How much the displacement map affects the mesh (where black is no
  29180. * displacement, and white is maximum displacement). Without a displacement
  29181. * map set, this value is not applied.
  29182. *
  29183. * @type {number}
  29184. * @default 0
  29185. */
  29186. this.displacementScale = 1;
  29187. /**
  29188. * The offset of the displacement map's values on the mesh's vertices.
  29189. * The bias is added to the scaled sample of the displacement map.
  29190. * Without a displacement map set, this value is not applied.
  29191. *
  29192. * @type {number}
  29193. * @default 0
  29194. */
  29195. this.displacementBias = 0;
  29196. /**
  29197. * The alpha map is a grayscale texture that controls the opacity across the
  29198. * surface (black: fully transparent; white: fully opaque).
  29199. *
  29200. * Only the color of the texture is used, ignoring the alpha channel if one
  29201. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29202. * when sampling this texture due to the extra bit of precision provided for
  29203. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29204. * luminance/alpha textures will also still work as expected.
  29205. *
  29206. * @type {?Texture}
  29207. * @default null
  29208. */
  29209. this.alphaMap = null;
  29210. /**
  29211. * Renders the geometry as a wireframe.
  29212. *
  29213. * @type {boolean}
  29214. * @default false
  29215. */
  29216. this.wireframe = false;
  29217. /**
  29218. * Controls the thickness of the wireframe.
  29219. *
  29220. * Can only be used with {@link SVGRenderer}.
  29221. *
  29222. * @type {number}
  29223. * @default 1
  29224. */
  29225. this.wireframeLinewidth = 1;
  29226. /**
  29227. * Defines appearance of wireframe ends.
  29228. *
  29229. * Can only be used with {@link SVGRenderer}.
  29230. *
  29231. * @type {('round'|'bevel'|'miter')}
  29232. * @default 'round'
  29233. */
  29234. this.wireframeLinecap = 'round';
  29235. /**
  29236. * Defines appearance of wireframe joints.
  29237. *
  29238. * Can only be used with {@link SVGRenderer}.
  29239. *
  29240. * @type {('round'|'bevel'|'miter')}
  29241. * @default 'round'
  29242. */
  29243. this.wireframeLinejoin = 'round';
  29244. /**
  29245. * Whether the material is affected by fog or not.
  29246. *
  29247. * @type {boolean}
  29248. * @default true
  29249. */
  29250. this.fog = true;
  29251. this.setValues( parameters );
  29252. }
  29253. copy( source ) {
  29254. super.copy( source );
  29255. this.color.copy( source.color );
  29256. this.map = source.map;
  29257. this.gradientMap = source.gradientMap;
  29258. this.lightMap = source.lightMap;
  29259. this.lightMapIntensity = source.lightMapIntensity;
  29260. this.aoMap = source.aoMap;
  29261. this.aoMapIntensity = source.aoMapIntensity;
  29262. this.emissive.copy( source.emissive );
  29263. this.emissiveMap = source.emissiveMap;
  29264. this.emissiveIntensity = source.emissiveIntensity;
  29265. this.bumpMap = source.bumpMap;
  29266. this.bumpScale = source.bumpScale;
  29267. this.normalMap = source.normalMap;
  29268. this.normalMapType = source.normalMapType;
  29269. this.normalScale.copy( source.normalScale );
  29270. this.displacementMap = source.displacementMap;
  29271. this.displacementScale = source.displacementScale;
  29272. this.displacementBias = source.displacementBias;
  29273. this.alphaMap = source.alphaMap;
  29274. this.wireframe = source.wireframe;
  29275. this.wireframeLinewidth = source.wireframeLinewidth;
  29276. this.wireframeLinecap = source.wireframeLinecap;
  29277. this.wireframeLinejoin = source.wireframeLinejoin;
  29278. this.fog = source.fog;
  29279. return this;
  29280. }
  29281. }
  29282. /**
  29283. * A material that maps the normal vectors to RGB colors.
  29284. *
  29285. * @augments Material
  29286. * @demo scenes/material-browser.html#MeshNormalMaterial
  29287. */
  29288. class MeshNormalMaterial extends Material {
  29289. /**
  29290. * Constructs a new mesh normal material.
  29291. *
  29292. * @param {Object} [parameters] - An object with one or more properties
  29293. * defining the material's appearance. Any property of the material
  29294. * (including any property from inherited materials) can be passed
  29295. * in here. Color values can be passed any type of value accepted
  29296. * by {@link Color#set}.
  29297. */
  29298. constructor( parameters ) {
  29299. super();
  29300. /**
  29301. * This flag can be used for type testing.
  29302. *
  29303. * @type {boolean}
  29304. * @readonly
  29305. * @default true
  29306. */
  29307. this.isMeshNormalMaterial = true;
  29308. this.type = 'MeshNormalMaterial';
  29309. /**
  29310. * The texture to create a bump map. The black and white values map to the
  29311. * perceived depth in relation to the lights. Bump doesn't actually affect
  29312. * the geometry of the object, only the lighting. If a normal map is defined
  29313. * this will be ignored.
  29314. *
  29315. * @type {?Texture}
  29316. * @default null
  29317. */
  29318. this.bumpMap = null;
  29319. /**
  29320. * How much the bump map affects the material. Typical range is `[0,1]`.
  29321. *
  29322. * @type {number}
  29323. * @default 1
  29324. */
  29325. this.bumpScale = 1;
  29326. /**
  29327. * The texture to create a normal map. The RGB values affect the surface
  29328. * normal for each pixel fragment and change the way the color is lit. Normal
  29329. * maps do not change the actual shape of the surface, only the lighting. In
  29330. * case the material has a normal map authored using the left handed
  29331. * convention, the `y` component of `normalScale` should be negated to compensate
  29332. * for the different handedness.
  29333. *
  29334. * @type {?Texture}
  29335. * @default null
  29336. */
  29337. this.normalMap = null;
  29338. /**
  29339. * The type of normal map.
  29340. *
  29341. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29342. * @default TangentSpaceNormalMap
  29343. */
  29344. this.normalMapType = TangentSpaceNormalMap;
  29345. /**
  29346. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29347. *
  29348. * @type {Vector2}
  29349. * @default (1,1)
  29350. */
  29351. this.normalScale = new Vector2( 1, 1 );
  29352. /**
  29353. * The displacement map affects the position of the mesh's vertices. Unlike
  29354. * other maps which only affect the light and shade of the material the
  29355. * displaced vertices can cast shadows, block other objects, and otherwise
  29356. * act as real geometry. The displacement texture is an image where the value
  29357. * of each pixel (white being the highest) is mapped against, and
  29358. * repositions, the vertices of the mesh.
  29359. *
  29360. * @type {?Texture}
  29361. * @default null
  29362. */
  29363. this.displacementMap = null;
  29364. /**
  29365. * How much the displacement map affects the mesh (where black is no
  29366. * displacement, and white is maximum displacement). Without a displacement
  29367. * map set, this value is not applied.
  29368. *
  29369. * @type {number}
  29370. * @default 0
  29371. */
  29372. this.displacementScale = 1;
  29373. /**
  29374. * The offset of the displacement map's values on the mesh's vertices.
  29375. * The bias is added to the scaled sample of the displacement map.
  29376. * Without a displacement map set, this value is not applied.
  29377. *
  29378. * @type {number}
  29379. * @default 0
  29380. */
  29381. this.displacementBias = 0;
  29382. /**
  29383. * Renders the geometry as a wireframe.
  29384. *
  29385. * @type {boolean}
  29386. * @default false
  29387. */
  29388. this.wireframe = false;
  29389. /**
  29390. * Controls the thickness of the wireframe.
  29391. *
  29392. * WebGL and WebGPU ignore this property and always render
  29393. * 1 pixel wide lines.
  29394. *
  29395. * @type {number}
  29396. * @default 1
  29397. */
  29398. this.wireframeLinewidth = 1;
  29399. /**
  29400. * Whether the material is rendered with flat shading or not.
  29401. *
  29402. * @type {boolean}
  29403. * @default false
  29404. */
  29405. this.flatShading = false;
  29406. this.setValues( parameters );
  29407. }
  29408. copy( source ) {
  29409. super.copy( source );
  29410. this.bumpMap = source.bumpMap;
  29411. this.bumpScale = source.bumpScale;
  29412. this.normalMap = source.normalMap;
  29413. this.normalMapType = source.normalMapType;
  29414. this.normalScale.copy( source.normalScale );
  29415. this.displacementMap = source.displacementMap;
  29416. this.displacementScale = source.displacementScale;
  29417. this.displacementBias = source.displacementBias;
  29418. this.wireframe = source.wireframe;
  29419. this.wireframeLinewidth = source.wireframeLinewidth;
  29420. this.flatShading = source.flatShading;
  29421. return this;
  29422. }
  29423. }
  29424. /**
  29425. * A material for non-shiny surfaces, without specular highlights.
  29426. *
  29427. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29428. * model for calculating reflectance. This can simulate some surfaces (such
  29429. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29430. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29431. * shading.
  29432. *
  29433. * Due to the simplicity of the reflectance and illumination models,
  29434. * performance will be greater when using this material over the
  29435. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29436. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29437. *
  29438. * @augments Material
  29439. * @demo scenes/material-browser.html#MeshLambertMaterial
  29440. */
  29441. class MeshLambertMaterial extends Material {
  29442. /**
  29443. * Constructs a new mesh lambert material.
  29444. *
  29445. * @param {Object} [parameters] - An object with one or more properties
  29446. * defining the material's appearance. Any property of the material
  29447. * (including any property from inherited materials) can be passed
  29448. * in here. Color values can be passed any type of value accepted
  29449. * by {@link Color#set}.
  29450. */
  29451. constructor( parameters ) {
  29452. super();
  29453. /**
  29454. * This flag can be used for type testing.
  29455. *
  29456. * @type {boolean}
  29457. * @readonly
  29458. * @default true
  29459. */
  29460. this.isMeshLambertMaterial = true;
  29461. this.type = 'MeshLambertMaterial';
  29462. /**
  29463. * Color of the material.
  29464. *
  29465. * @type {Color}
  29466. * @default (1,1,1)
  29467. */
  29468. this.color = new Color( 0xffffff ); // diffuse
  29469. /**
  29470. * The color map. May optionally include an alpha channel, typically combined
  29471. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29472. * color is modulated by the diffuse `color`.
  29473. *
  29474. * @type {?Texture}
  29475. * @default null
  29476. */
  29477. this.map = null;
  29478. /**
  29479. * The light map. Requires a second set of UVs.
  29480. *
  29481. * @type {?Texture}
  29482. * @default null
  29483. */
  29484. this.lightMap = null;
  29485. /**
  29486. * Intensity of the baked light.
  29487. *
  29488. * @type {number}
  29489. * @default 1
  29490. */
  29491. this.lightMapIntensity = 1.0;
  29492. /**
  29493. * The red channel of this texture is used as the ambient occlusion map.
  29494. * Requires a second set of UVs.
  29495. *
  29496. * @type {?Texture}
  29497. * @default null
  29498. */
  29499. this.aoMap = null;
  29500. /**
  29501. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29502. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29503. * red channel is also `1`, ambient light is fully occluded on a surface.
  29504. *
  29505. * @type {number}
  29506. * @default 1
  29507. */
  29508. this.aoMapIntensity = 1.0;
  29509. /**
  29510. * Emissive (light) color of the material, essentially a solid color
  29511. * unaffected by other lighting.
  29512. *
  29513. * @type {Color}
  29514. * @default (0,0,0)
  29515. */
  29516. this.emissive = new Color( 0x000000 );
  29517. /**
  29518. * Intensity of the emissive light. Modulates the emissive color.
  29519. *
  29520. * @type {number}
  29521. * @default 1
  29522. */
  29523. this.emissiveIntensity = 1.0;
  29524. /**
  29525. * Set emissive (glow) map. The emissive map color is modulated by the
  29526. * emissive color and the emissive intensity. If you have an emissive map,
  29527. * be sure to set the emissive color to something other than black.
  29528. *
  29529. * @type {?Texture}
  29530. * @default null
  29531. */
  29532. this.emissiveMap = null;
  29533. /**
  29534. * The texture to create a bump map. The black and white values map to the
  29535. * perceived depth in relation to the lights. Bump doesn't actually affect
  29536. * the geometry of the object, only the lighting. If a normal map is defined
  29537. * this will be ignored.
  29538. *
  29539. * @type {?Texture}
  29540. * @default null
  29541. */
  29542. this.bumpMap = null;
  29543. /**
  29544. * How much the bump map affects the material. Typical range is `[0,1]`.
  29545. *
  29546. * @type {number}
  29547. * @default 1
  29548. */
  29549. this.bumpScale = 1;
  29550. /**
  29551. * The texture to create a normal map. The RGB values affect the surface
  29552. * normal for each pixel fragment and change the way the color is lit. Normal
  29553. * maps do not change the actual shape of the surface, only the lighting. In
  29554. * case the material has a normal map authored using the left handed
  29555. * convention, the `y` component of `normalScale` should be negated to compensate
  29556. * for the different handedness.
  29557. *
  29558. * @type {?Texture}
  29559. * @default null
  29560. */
  29561. this.normalMap = null;
  29562. /**
  29563. * The type of normal map.
  29564. *
  29565. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29566. * @default TangentSpaceNormalMap
  29567. */
  29568. this.normalMapType = TangentSpaceNormalMap;
  29569. /**
  29570. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29571. *
  29572. * @type {Vector2}
  29573. * @default (1,1)
  29574. */
  29575. this.normalScale = new Vector2( 1, 1 );
  29576. /**
  29577. * The displacement map affects the position of the mesh's vertices. Unlike
  29578. * other maps which only affect the light and shade of the material the
  29579. * displaced vertices can cast shadows, block other objects, and otherwise
  29580. * act as real geometry. The displacement texture is an image where the value
  29581. * of each pixel (white being the highest) is mapped against, and
  29582. * repositions, the vertices of the mesh.
  29583. *
  29584. * @type {?Texture}
  29585. * @default null
  29586. */
  29587. this.displacementMap = null;
  29588. /**
  29589. * How much the displacement map affects the mesh (where black is no
  29590. * displacement, and white is maximum displacement). Without a displacement
  29591. * map set, this value is not applied.
  29592. *
  29593. * @type {number}
  29594. * @default 0
  29595. */
  29596. this.displacementScale = 1;
  29597. /**
  29598. * The offset of the displacement map's values on the mesh's vertices.
  29599. * The bias is added to the scaled sample of the displacement map.
  29600. * Without a displacement map set, this value is not applied.
  29601. *
  29602. * @type {number}
  29603. * @default 0
  29604. */
  29605. this.displacementBias = 0;
  29606. /**
  29607. * Specular map used by the material.
  29608. *
  29609. * @type {?Texture}
  29610. * @default null
  29611. */
  29612. this.specularMap = null;
  29613. /**
  29614. * The alpha map is a grayscale texture that controls the opacity across the
  29615. * surface (black: fully transparent; white: fully opaque).
  29616. *
  29617. * Only the color of the texture is used, ignoring the alpha channel if one
  29618. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29619. * when sampling this texture due to the extra bit of precision provided for
  29620. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29621. * luminance/alpha textures will also still work as expected.
  29622. *
  29623. * @type {?Texture}
  29624. * @default null
  29625. */
  29626. this.alphaMap = null;
  29627. /**
  29628. * The environment map.
  29629. *
  29630. * @type {?Texture}
  29631. * @default null
  29632. */
  29633. this.envMap = null;
  29634. /**
  29635. * The rotation of the environment map in radians.
  29636. *
  29637. * @type {Euler}
  29638. * @default (0,0,0)
  29639. */
  29640. this.envMapRotation = new Euler();
  29641. /**
  29642. * How to combine the result of the surface's color with the environment map, if any.
  29643. *
  29644. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29645. * blend between the two colors.
  29646. *
  29647. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29648. * @default MultiplyOperation
  29649. */
  29650. this.combine = MultiplyOperation;
  29651. /**
  29652. * How much the environment map affects the surface.
  29653. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29654. *
  29655. * @type {number}
  29656. * @default 1
  29657. */
  29658. this.reflectivity = 1;
  29659. /**
  29660. * The index of refraction (IOR) of air (approximately 1) divided by the
  29661. * index of refraction of the material. It is used with environment mapping
  29662. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29663. * The refraction ratio should not exceed `1`.
  29664. *
  29665. * @type {number}
  29666. * @default 0.98
  29667. */
  29668. this.refractionRatio = 0.98;
  29669. /**
  29670. * Renders the geometry as a wireframe.
  29671. *
  29672. * @type {boolean}
  29673. * @default false
  29674. */
  29675. this.wireframe = false;
  29676. /**
  29677. * Controls the thickness of the wireframe.
  29678. *
  29679. * Can only be used with {@link SVGRenderer}.
  29680. *
  29681. * @type {number}
  29682. * @default 1
  29683. */
  29684. this.wireframeLinewidth = 1;
  29685. /**
  29686. * Defines appearance of wireframe ends.
  29687. *
  29688. * Can only be used with {@link SVGRenderer}.
  29689. *
  29690. * @type {('round'|'bevel'|'miter')}
  29691. * @default 'round'
  29692. */
  29693. this.wireframeLinecap = 'round';
  29694. /**
  29695. * Defines appearance of wireframe joints.
  29696. *
  29697. * Can only be used with {@link SVGRenderer}.
  29698. *
  29699. * @type {('round'|'bevel'|'miter')}
  29700. * @default 'round'
  29701. */
  29702. this.wireframeLinejoin = 'round';
  29703. /**
  29704. * Whether the material is rendered with flat shading or not.
  29705. *
  29706. * @type {boolean}
  29707. * @default false
  29708. */
  29709. this.flatShading = false;
  29710. /**
  29711. * Whether the material is affected by fog or not.
  29712. *
  29713. * @type {boolean}
  29714. * @default true
  29715. */
  29716. this.fog = true;
  29717. this.setValues( parameters );
  29718. }
  29719. copy( source ) {
  29720. super.copy( source );
  29721. this.color.copy( source.color );
  29722. this.map = source.map;
  29723. this.lightMap = source.lightMap;
  29724. this.lightMapIntensity = source.lightMapIntensity;
  29725. this.aoMap = source.aoMap;
  29726. this.aoMapIntensity = source.aoMapIntensity;
  29727. this.emissive.copy( source.emissive );
  29728. this.emissiveMap = source.emissiveMap;
  29729. this.emissiveIntensity = source.emissiveIntensity;
  29730. this.bumpMap = source.bumpMap;
  29731. this.bumpScale = source.bumpScale;
  29732. this.normalMap = source.normalMap;
  29733. this.normalMapType = source.normalMapType;
  29734. this.normalScale.copy( source.normalScale );
  29735. this.displacementMap = source.displacementMap;
  29736. this.displacementScale = source.displacementScale;
  29737. this.displacementBias = source.displacementBias;
  29738. this.specularMap = source.specularMap;
  29739. this.alphaMap = source.alphaMap;
  29740. this.envMap = source.envMap;
  29741. this.envMapRotation.copy( source.envMapRotation );
  29742. this.combine = source.combine;
  29743. this.reflectivity = source.reflectivity;
  29744. this.refractionRatio = source.refractionRatio;
  29745. this.wireframe = source.wireframe;
  29746. this.wireframeLinewidth = source.wireframeLinewidth;
  29747. this.wireframeLinecap = source.wireframeLinecap;
  29748. this.wireframeLinejoin = source.wireframeLinejoin;
  29749. this.flatShading = source.flatShading;
  29750. this.fog = source.fog;
  29751. return this;
  29752. }
  29753. }
  29754. /**
  29755. * A material for drawing geometry by depth. Depth is based off of the camera
  29756. * near and far plane. White is nearest, black is farthest.
  29757. *
  29758. * @augments Material
  29759. * @demo scenes/material-browser.html#MeshDepthMaterial
  29760. */
  29761. class MeshDepthMaterial extends Material {
  29762. /**
  29763. * Constructs a new mesh depth material.
  29764. *
  29765. * @param {Object} [parameters] - An object with one or more properties
  29766. * defining the material's appearance. Any property of the material
  29767. * (including any property from inherited materials) can be passed
  29768. * in here. Color values can be passed any type of value accepted
  29769. * by {@link Color#set}.
  29770. */
  29771. constructor( parameters ) {
  29772. super();
  29773. /**
  29774. * This flag can be used for type testing.
  29775. *
  29776. * @type {boolean}
  29777. * @readonly
  29778. * @default true
  29779. */
  29780. this.isMeshDepthMaterial = true;
  29781. this.type = 'MeshDepthMaterial';
  29782. /**
  29783. * Type for depth packing.
  29784. *
  29785. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29786. * @default BasicDepthPacking
  29787. */
  29788. this.depthPacking = BasicDepthPacking;
  29789. /**
  29790. * The color map. May optionally include an alpha channel, typically combined
  29791. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29792. *
  29793. * @type {?Texture}
  29794. * @default null
  29795. */
  29796. this.map = null;
  29797. /**
  29798. * The alpha map is a grayscale texture that controls the opacity across the
  29799. * surface (black: fully transparent; white: fully opaque).
  29800. *
  29801. * Only the color of the texture is used, ignoring the alpha channel if one
  29802. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29803. * when sampling this texture due to the extra bit of precision provided for
  29804. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29805. * luminance/alpha textures will also still work as expected.
  29806. *
  29807. * @type {?Texture}
  29808. * @default null
  29809. */
  29810. this.alphaMap = null;
  29811. /**
  29812. * The displacement map affects the position of the mesh's vertices. Unlike
  29813. * other maps which only affect the light and shade of the material the
  29814. * displaced vertices can cast shadows, block other objects, and otherwise
  29815. * act as real geometry. The displacement texture is an image where the value
  29816. * of each pixel (white being the highest) is mapped against, and
  29817. * repositions, the vertices of the mesh.
  29818. *
  29819. * @type {?Texture}
  29820. * @default null
  29821. */
  29822. this.displacementMap = null;
  29823. /**
  29824. * How much the displacement map affects the mesh (where black is no
  29825. * displacement, and white is maximum displacement). Without a displacement
  29826. * map set, this value is not applied.
  29827. *
  29828. * @type {number}
  29829. * @default 0
  29830. */
  29831. this.displacementScale = 1;
  29832. /**
  29833. * The offset of the displacement map's values on the mesh's vertices.
  29834. * The bias is added to the scaled sample of the displacement map.
  29835. * Without a displacement map set, this value is not applied.
  29836. *
  29837. * @type {number}
  29838. * @default 0
  29839. */
  29840. this.displacementBias = 0;
  29841. /**
  29842. * Renders the geometry as a wireframe.
  29843. *
  29844. * @type {boolean}
  29845. * @default false
  29846. */
  29847. this.wireframe = false;
  29848. /**
  29849. * Controls the thickness of the wireframe.
  29850. *
  29851. * WebGL and WebGPU ignore this property and always render
  29852. * 1 pixel wide lines.
  29853. *
  29854. * @type {number}
  29855. * @default 1
  29856. */
  29857. this.wireframeLinewidth = 1;
  29858. this.setValues( parameters );
  29859. }
  29860. copy( source ) {
  29861. super.copy( source );
  29862. this.depthPacking = source.depthPacking;
  29863. this.map = source.map;
  29864. this.alphaMap = source.alphaMap;
  29865. this.displacementMap = source.displacementMap;
  29866. this.displacementScale = source.displacementScale;
  29867. this.displacementBias = source.displacementBias;
  29868. this.wireframe = source.wireframe;
  29869. this.wireframeLinewidth = source.wireframeLinewidth;
  29870. return this;
  29871. }
  29872. }
  29873. /**
  29874. * A material used internally for implementing shadow mapping with
  29875. * point lights.
  29876. *
  29877. * Can also be used to customize the shadow casting of an object by assigning
  29878. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29879. * The following examples demonstrates this approach in order to ensure
  29880. * transparent parts of objects do not cast shadows.
  29881. *
  29882. * @augments Material
  29883. */
  29884. class MeshDistanceMaterial extends Material {
  29885. /**
  29886. * Constructs a new mesh distance material.
  29887. *
  29888. * @param {Object} [parameters] - An object with one or more properties
  29889. * defining the material's appearance. Any property of the material
  29890. * (including any property from inherited materials) can be passed
  29891. * in here. Color values can be passed any type of value accepted
  29892. * by {@link Color#set}.
  29893. */
  29894. constructor( parameters ) {
  29895. super();
  29896. /**
  29897. * This flag can be used for type testing.
  29898. *
  29899. * @type {boolean}
  29900. * @readonly
  29901. * @default true
  29902. */
  29903. this.isMeshDistanceMaterial = true;
  29904. this.type = 'MeshDistanceMaterial';
  29905. /**
  29906. * The color map. May optionally include an alpha channel, typically combined
  29907. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29908. *
  29909. * @type {?Texture}
  29910. * @default null
  29911. */
  29912. this.map = null;
  29913. /**
  29914. * The alpha map is a grayscale texture that controls the opacity across the
  29915. * surface (black: fully transparent; white: fully opaque).
  29916. *
  29917. * Only the color of the texture is used, ignoring the alpha channel if one
  29918. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29919. * when sampling this texture due to the extra bit of precision provided for
  29920. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29921. * luminance/alpha textures will also still work as expected.
  29922. *
  29923. * @type {?Texture}
  29924. * @default null
  29925. */
  29926. this.alphaMap = null;
  29927. /**
  29928. * The displacement map affects the position of the mesh's vertices. Unlike
  29929. * other maps which only affect the light and shade of the material the
  29930. * displaced vertices can cast shadows, block other objects, and otherwise
  29931. * act as real geometry. The displacement texture is an image where the value
  29932. * of each pixel (white being the highest) is mapped against, and
  29933. * repositions, the vertices of the mesh.
  29934. *
  29935. * @type {?Texture}
  29936. * @default null
  29937. */
  29938. this.displacementMap = null;
  29939. /**
  29940. * How much the displacement map affects the mesh (where black is no
  29941. * displacement, and white is maximum displacement). Without a displacement
  29942. * map set, this value is not applied.
  29943. *
  29944. * @type {number}
  29945. * @default 0
  29946. */
  29947. this.displacementScale = 1;
  29948. /**
  29949. * The offset of the displacement map's values on the mesh's vertices.
  29950. * The bias is added to the scaled sample of the displacement map.
  29951. * Without a displacement map set, this value is not applied.
  29952. *
  29953. * @type {number}
  29954. * @default 0
  29955. */
  29956. this.displacementBias = 0;
  29957. this.setValues( parameters );
  29958. }
  29959. copy( source ) {
  29960. super.copy( source );
  29961. this.map = source.map;
  29962. this.alphaMap = source.alphaMap;
  29963. this.displacementMap = source.displacementMap;
  29964. this.displacementScale = source.displacementScale;
  29965. this.displacementBias = source.displacementBias;
  29966. return this;
  29967. }
  29968. }
  29969. /**
  29970. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29971. * material color and shading.
  29972. *
  29973. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29974. * baked lighting. It will cast a shadow onto an object that receives shadows
  29975. * (and shadow clipping works), but it will not self-shadow or receive
  29976. * shadows.
  29977. *
  29978. * @augments Material
  29979. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29980. */
  29981. class MeshMatcapMaterial extends Material {
  29982. /**
  29983. * Constructs a new mesh matcap material.
  29984. *
  29985. * @param {Object} [parameters] - An object with one or more properties
  29986. * defining the material's appearance. Any property of the material
  29987. * (including any property from inherited materials) can be passed
  29988. * in here. Color values can be passed any type of value accepted
  29989. * by {@link Color#set}.
  29990. */
  29991. constructor( parameters ) {
  29992. super();
  29993. /**
  29994. * This flag can be used for type testing.
  29995. *
  29996. * @type {boolean}
  29997. * @readonly
  29998. * @default true
  29999. */
  30000. this.isMeshMatcapMaterial = true;
  30001. this.defines = { 'MATCAP': '' };
  30002. this.type = 'MeshMatcapMaterial';
  30003. /**
  30004. * Color of the material.
  30005. *
  30006. * @type {Color}
  30007. * @default (1,1,1)
  30008. */
  30009. this.color = new Color( 0xffffff ); // diffuse
  30010. /**
  30011. * The matcap map.
  30012. *
  30013. * @type {?Texture}
  30014. * @default null
  30015. */
  30016. this.matcap = null;
  30017. /**
  30018. * The color map. May optionally include an alpha channel, typically combined
  30019. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30020. * color is modulated by the diffuse `color`.
  30021. *
  30022. * @type {?Texture}
  30023. * @default null
  30024. */
  30025. this.map = null;
  30026. /**
  30027. * The texture to create a bump map. The black and white values map to the
  30028. * perceived depth in relation to the lights. Bump doesn't actually affect
  30029. * the geometry of the object, only the lighting. If a normal map is defined
  30030. * this will be ignored.
  30031. *
  30032. * @type {?Texture}
  30033. * @default null
  30034. */
  30035. this.bumpMap = null;
  30036. /**
  30037. * How much the bump map affects the material. Typical range is `[0,1]`.
  30038. *
  30039. * @type {number}
  30040. * @default 1
  30041. */
  30042. this.bumpScale = 1;
  30043. /**
  30044. * The texture to create a normal map. The RGB values affect the surface
  30045. * normal for each pixel fragment and change the way the color is lit. Normal
  30046. * maps do not change the actual shape of the surface, only the lighting. In
  30047. * case the material has a normal map authored using the left handed
  30048. * convention, the `y` component of `normalScale` should be negated to compensate
  30049. * for the different handedness.
  30050. *
  30051. * @type {?Texture}
  30052. * @default null
  30053. */
  30054. this.normalMap = null;
  30055. /**
  30056. * The type of normal map.
  30057. *
  30058. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30059. * @default TangentSpaceNormalMap
  30060. */
  30061. this.normalMapType = TangentSpaceNormalMap;
  30062. /**
  30063. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30064. *
  30065. * @type {Vector2}
  30066. * @default (1,1)
  30067. */
  30068. this.normalScale = new Vector2( 1, 1 );
  30069. /**
  30070. * The displacement map affects the position of the mesh's vertices. Unlike
  30071. * other maps which only affect the light and shade of the material the
  30072. * displaced vertices can cast shadows, block other objects, and otherwise
  30073. * act as real geometry. The displacement texture is an image where the value
  30074. * of each pixel (white being the highest) is mapped against, and
  30075. * repositions, the vertices of the mesh.
  30076. *
  30077. * @type {?Texture}
  30078. * @default null
  30079. */
  30080. this.displacementMap = null;
  30081. /**
  30082. * How much the displacement map affects the mesh (where black is no
  30083. * displacement, and white is maximum displacement). Without a displacement
  30084. * map set, this value is not applied.
  30085. *
  30086. * @type {number}
  30087. * @default 0
  30088. */
  30089. this.displacementScale = 1;
  30090. /**
  30091. * The offset of the displacement map's values on the mesh's vertices.
  30092. * The bias is added to the scaled sample of the displacement map.
  30093. * Without a displacement map set, this value is not applied.
  30094. *
  30095. * @type {number}
  30096. * @default 0
  30097. */
  30098. this.displacementBias = 0;
  30099. /**
  30100. * The alpha map is a grayscale texture that controls the opacity across the
  30101. * surface (black: fully transparent; white: fully opaque).
  30102. *
  30103. * Only the color of the texture is used, ignoring the alpha channel if one
  30104. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30105. * when sampling this texture due to the extra bit of precision provided for
  30106. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30107. * luminance/alpha textures will also still work as expected.
  30108. *
  30109. * @type {?Texture}
  30110. * @default null
  30111. */
  30112. this.alphaMap = null;
  30113. /**
  30114. * Renders the geometry as a wireframe.
  30115. *
  30116. * @type {boolean}
  30117. * @default false
  30118. */
  30119. this.wireframe = false;
  30120. /**
  30121. * Controls the thickness of the wireframe.
  30122. *
  30123. * Can only be used with {@link SVGRenderer}.
  30124. *
  30125. * @type {number}
  30126. * @default 1
  30127. */
  30128. this.wireframeLinewidth = 1;
  30129. /**
  30130. * Whether the material is rendered with flat shading or not.
  30131. *
  30132. * @type {boolean}
  30133. * @default false
  30134. */
  30135. this.flatShading = false;
  30136. /**
  30137. * Whether the material is affected by fog or not.
  30138. *
  30139. * @type {boolean}
  30140. * @default true
  30141. */
  30142. this.fog = true;
  30143. this.setValues( parameters );
  30144. }
  30145. copy( source ) {
  30146. super.copy( source );
  30147. this.defines = { 'MATCAP': '' };
  30148. this.color.copy( source.color );
  30149. this.matcap = source.matcap;
  30150. this.map = source.map;
  30151. this.bumpMap = source.bumpMap;
  30152. this.bumpScale = source.bumpScale;
  30153. this.normalMap = source.normalMap;
  30154. this.normalMapType = source.normalMapType;
  30155. this.normalScale.copy( source.normalScale );
  30156. this.displacementMap = source.displacementMap;
  30157. this.displacementScale = source.displacementScale;
  30158. this.displacementBias = source.displacementBias;
  30159. this.alphaMap = source.alphaMap;
  30160. this.wireframe = source.wireframe;
  30161. this.wireframeLinewidth = source.wireframeLinewidth;
  30162. this.flatShading = source.flatShading;
  30163. this.fog = source.fog;
  30164. return this;
  30165. }
  30166. }
  30167. /**
  30168. * A material for rendering line primitives.
  30169. *
  30170. * Materials define the appearance of renderable 3D objects.
  30171. *
  30172. * ```js
  30173. * const material = new THREE.LineDashedMaterial( {
  30174. * color: 0xffffff,
  30175. * scale: 1,
  30176. * dashSize: 3,
  30177. * gapSize: 1,
  30178. * } );
  30179. * ```
  30180. *
  30181. * @augments LineBasicMaterial
  30182. */
  30183. class LineDashedMaterial extends LineBasicMaterial {
  30184. /**
  30185. * Constructs a new line dashed material.
  30186. *
  30187. * @param {Object} [parameters] - An object with one or more properties
  30188. * defining the material's appearance. Any property of the material
  30189. * (including any property from inherited materials) can be passed
  30190. * in here. Color values can be passed any type of value accepted
  30191. * by {@link Color#set}.
  30192. */
  30193. constructor( parameters ) {
  30194. super();
  30195. /**
  30196. * This flag can be used for type testing.
  30197. *
  30198. * @type {boolean}
  30199. * @readonly
  30200. * @default true
  30201. */
  30202. this.isLineDashedMaterial = true;
  30203. this.type = 'LineDashedMaterial';
  30204. /**
  30205. * The scale of the dashed part of a line.
  30206. *
  30207. * @type {number}
  30208. * @default 1
  30209. */
  30210. this.scale = 1;
  30211. /**
  30212. * The size of the dash. This is both the gap with the stroke.
  30213. *
  30214. * @type {number}
  30215. * @default 3
  30216. */
  30217. this.dashSize = 3;
  30218. /**
  30219. * The size of the gap.
  30220. *
  30221. * @type {number}
  30222. * @default 1
  30223. */
  30224. this.gapSize = 1;
  30225. this.setValues( parameters );
  30226. }
  30227. copy( source ) {
  30228. super.copy( source );
  30229. this.scale = source.scale;
  30230. this.dashSize = source.dashSize;
  30231. this.gapSize = source.gapSize;
  30232. return this;
  30233. }
  30234. }
  30235. /**
  30236. * Converts an array to a specific type.
  30237. *
  30238. * @param {TypedArray|Array} array - The array to convert.
  30239. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30240. * @return {TypedArray} The converted array.
  30241. */
  30242. function convertArray( array, type ) {
  30243. if ( ! array || array.constructor === type ) return array;
  30244. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30245. return new type( array ); // create typed array
  30246. }
  30247. return Array.prototype.slice.call( array ); // create Array
  30248. }
  30249. /**
  30250. * Returns an array by which times and values can be sorted.
  30251. *
  30252. * @param {Array<number>} times - The keyframe time values.
  30253. * @return {Array<number>} The array.
  30254. */
  30255. function getKeyframeOrder( times ) {
  30256. function compareTime( i, j ) {
  30257. return times[ i ] - times[ j ];
  30258. }
  30259. const n = times.length;
  30260. const result = new Array( n );
  30261. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30262. result.sort( compareTime );
  30263. return result;
  30264. }
  30265. /**
  30266. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30267. *
  30268. * @param {Array<number>} values - The values to sort.
  30269. * @param {number} stride - The stride.
  30270. * @param {Array<number>} order - The sort order.
  30271. * @return {Array<number>} The sorted values.
  30272. */
  30273. function sortedArray( values, stride, order ) {
  30274. const nValues = values.length;
  30275. const result = new values.constructor( nValues );
  30276. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30277. const srcOffset = order[ i ] * stride;
  30278. for ( let j = 0; j !== stride; ++ j ) {
  30279. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30280. }
  30281. }
  30282. return result;
  30283. }
  30284. /**
  30285. * Used for parsing AOS keyframe formats.
  30286. *
  30287. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30288. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30289. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30290. * @param {string} valuePropertyName - The name of the property to use.
  30291. */
  30292. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30293. let i = 1, key = jsonKeys[ 0 ];
  30294. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30295. key = jsonKeys[ i ++ ];
  30296. }
  30297. if ( key === undefined ) return; // no data
  30298. let value = key[ valuePropertyName ];
  30299. if ( value === undefined ) return; // no data
  30300. if ( Array.isArray( value ) ) {
  30301. do {
  30302. value = key[ valuePropertyName ];
  30303. if ( value !== undefined ) {
  30304. times.push( key.time );
  30305. values.push( ...value ); // push all elements
  30306. }
  30307. key = jsonKeys[ i ++ ];
  30308. } while ( key !== undefined );
  30309. } else if ( value.toArray !== undefined ) {
  30310. // ...assume THREE.Math-ish
  30311. do {
  30312. value = key[ valuePropertyName ];
  30313. if ( value !== undefined ) {
  30314. times.push( key.time );
  30315. value.toArray( values, values.length );
  30316. }
  30317. key = jsonKeys[ i ++ ];
  30318. } while ( key !== undefined );
  30319. } else {
  30320. // otherwise push as-is
  30321. do {
  30322. value = key[ valuePropertyName ];
  30323. if ( value !== undefined ) {
  30324. times.push( key.time );
  30325. values.push( value );
  30326. }
  30327. key = jsonKeys[ i ++ ];
  30328. } while ( key !== undefined );
  30329. }
  30330. }
  30331. /**
  30332. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30333. *
  30334. * @param {AnimationClip} sourceClip - The values to sort.
  30335. * @param {string} name - The name of the clip.
  30336. * @param {number} startFrame - The start frame.
  30337. * @param {number} endFrame - The end frame.
  30338. * @param {number} [fps=30] - The FPS.
  30339. * @return {AnimationClip} The new sub clip.
  30340. */
  30341. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30342. const clip = sourceClip.clone();
  30343. clip.name = name;
  30344. const tracks = [];
  30345. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30346. const track = clip.tracks[ i ];
  30347. const valueSize = track.getValueSize();
  30348. const times = [];
  30349. const values = [];
  30350. for ( let j = 0; j < track.times.length; ++ j ) {
  30351. const frame = track.times[ j ] * fps;
  30352. if ( frame < startFrame || frame >= endFrame ) continue;
  30353. times.push( track.times[ j ] );
  30354. for ( let k = 0; k < valueSize; ++ k ) {
  30355. values.push( track.values[ j * valueSize + k ] );
  30356. }
  30357. }
  30358. if ( times.length === 0 ) continue;
  30359. track.times = convertArray( times, track.times.constructor );
  30360. track.values = convertArray( values, track.values.constructor );
  30361. tracks.push( track );
  30362. }
  30363. clip.tracks = tracks;
  30364. // find minimum .times value across all tracks in the trimmed clip
  30365. let minStartTime = Infinity;
  30366. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30367. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30368. minStartTime = clip.tracks[ i ].times[ 0 ];
  30369. }
  30370. }
  30371. // shift all tracks such that clip begins at t=0
  30372. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30373. clip.tracks[ i ].shift( -1 * minStartTime );
  30374. }
  30375. clip.resetDuration();
  30376. return clip;
  30377. }
  30378. /**
  30379. * Converts the keyframes of the given animation clip to an additive format.
  30380. *
  30381. * @param {AnimationClip} targetClip - The clip to make additive.
  30382. * @param {number} [referenceFrame=0] - The reference frame.
  30383. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30384. * @param {number} [fps=30] - The FPS.
  30385. * @return {AnimationClip} The updated clip which is now additive.
  30386. */
  30387. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30388. if ( fps <= 0 ) fps = 30;
  30389. const numTracks = referenceClip.tracks.length;
  30390. const referenceTime = referenceFrame / fps;
  30391. // Make each track's values relative to the values at the reference frame
  30392. for ( let i = 0; i < numTracks; ++ i ) {
  30393. const referenceTrack = referenceClip.tracks[ i ];
  30394. const referenceTrackType = referenceTrack.ValueTypeName;
  30395. // Skip this track if it's non-numeric
  30396. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30397. // Find the track in the target clip whose name and type matches the reference track
  30398. const targetTrack = targetClip.tracks.find( function ( track ) {
  30399. return track.name === referenceTrack.name
  30400. && track.ValueTypeName === referenceTrackType;
  30401. } );
  30402. if ( targetTrack === undefined ) continue;
  30403. let referenceOffset = 0;
  30404. const referenceValueSize = referenceTrack.getValueSize();
  30405. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30406. referenceOffset = referenceValueSize / 3;
  30407. }
  30408. let targetOffset = 0;
  30409. const targetValueSize = targetTrack.getValueSize();
  30410. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30411. targetOffset = targetValueSize / 3;
  30412. }
  30413. const lastIndex = referenceTrack.times.length - 1;
  30414. let referenceValue;
  30415. // Find the value to subtract out of the track
  30416. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30417. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30418. const startIndex = referenceOffset;
  30419. const endIndex = referenceValueSize - referenceOffset;
  30420. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30421. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30422. // Reference frame is after the last keyframe, so just use the last keyframe
  30423. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30424. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30425. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30426. } else {
  30427. // Interpolate to the reference value
  30428. const interpolant = referenceTrack.createInterpolant();
  30429. const startIndex = referenceOffset;
  30430. const endIndex = referenceValueSize - referenceOffset;
  30431. interpolant.evaluate( referenceTime );
  30432. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30433. }
  30434. // Conjugate the quaternion
  30435. if ( referenceTrackType === 'quaternion' ) {
  30436. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30437. referenceQuat.toArray( referenceValue );
  30438. }
  30439. // Subtract the reference value from all of the track values
  30440. const numTimes = targetTrack.times.length;
  30441. for ( let j = 0; j < numTimes; ++ j ) {
  30442. const valueStart = j * targetValueSize + targetOffset;
  30443. if ( referenceTrackType === 'quaternion' ) {
  30444. // Multiply the conjugate for quaternion track types
  30445. Quaternion.multiplyQuaternionsFlat(
  30446. targetTrack.values,
  30447. valueStart,
  30448. referenceValue,
  30449. 0,
  30450. targetTrack.values,
  30451. valueStart
  30452. );
  30453. } else {
  30454. const valueEnd = targetValueSize - targetOffset * 2;
  30455. // Subtract each value for all other numeric track types
  30456. for ( let k = 0; k < valueEnd; ++ k ) {
  30457. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30458. }
  30459. }
  30460. }
  30461. }
  30462. targetClip.blendMode = AdditiveAnimationBlendMode;
  30463. return targetClip;
  30464. }
  30465. /**
  30466. * A class with various methods to assist with animations.
  30467. *
  30468. * @hideconstructor
  30469. */
  30470. class AnimationUtils {
  30471. /**
  30472. * Converts an array to a specific type
  30473. *
  30474. * @static
  30475. * @param {TypedArray|Array} array - The array to convert.
  30476. * @param {TypedArray.constructor} type - The constructor of a type array.
  30477. * @return {TypedArray} The converted array
  30478. */
  30479. static convertArray( array, type ) {
  30480. return convertArray( array, type );
  30481. }
  30482. /**
  30483. * Returns `true` if the given object is a typed array.
  30484. *
  30485. * @static
  30486. * @param {any} object - The object to check.
  30487. * @return {boolean} Whether the given object is a typed array.
  30488. */
  30489. static isTypedArray( object ) {
  30490. return isTypedArray( object );
  30491. }
  30492. /**
  30493. * Returns an array by which times and values can be sorted.
  30494. *
  30495. * @static
  30496. * @param {Array<number>} times - The keyframe time values.
  30497. * @return {Array<number>} The array.
  30498. */
  30499. static getKeyframeOrder( times ) {
  30500. return getKeyframeOrder( times );
  30501. }
  30502. /**
  30503. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30504. *
  30505. * @static
  30506. * @param {Array<number>} values - The values to sort.
  30507. * @param {number} stride - The stride.
  30508. * @param {Array<number>} order - The sort order.
  30509. * @return {Array<number>} The sorted values.
  30510. */
  30511. static sortedArray( values, stride, order ) {
  30512. return sortedArray( values, stride, order );
  30513. }
  30514. /**
  30515. * Used for parsing AOS keyframe formats.
  30516. *
  30517. * @static
  30518. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30519. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30520. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30521. * @param {string} valuePropertyName - The name of the property to use.
  30522. */
  30523. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30524. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30525. }
  30526. /**
  30527. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30528. *
  30529. * @static
  30530. * @param {AnimationClip} sourceClip - The values to sort.
  30531. * @param {string} name - The name of the clip.
  30532. * @param {number} startFrame - The start frame.
  30533. * @param {number} endFrame - The end frame.
  30534. * @param {number} [fps=30] - The FPS.
  30535. * @return {AnimationClip} The new sub clip.
  30536. */
  30537. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30538. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30539. }
  30540. /**
  30541. * Converts the keyframes of the given animation clip to an additive format.
  30542. *
  30543. * @static
  30544. * @param {AnimationClip} targetClip - The clip to make additive.
  30545. * @param {number} [referenceFrame=0] - The reference frame.
  30546. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30547. * @param {number} [fps=30] - The FPS.
  30548. * @return {AnimationClip} The updated clip which is now additive.
  30549. */
  30550. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30551. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30552. }
  30553. }
  30554. /**
  30555. * Abstract base class of interpolants over parametric samples.
  30556. *
  30557. * The parameter domain is one dimensional, typically the time or a path
  30558. * along a curve defined by the data.
  30559. *
  30560. * The sample values can have any dimensionality and derived classes may
  30561. * apply special interpretations to the data.
  30562. *
  30563. * This class provides the interval seek in a Template Method, deferring
  30564. * the actual interpolation to derived classes.
  30565. *
  30566. * Time complexity is O(1) for linear access crossing at most two points
  30567. * and O(log N) for random access, where N is the number of positions.
  30568. *
  30569. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30570. *
  30571. * @abstract
  30572. */
  30573. class Interpolant {
  30574. /**
  30575. * Constructs a new interpolant.
  30576. *
  30577. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30578. * @param {TypedArray} sampleValues - The sample values.
  30579. * @param {number} sampleSize - The sample size
  30580. * @param {TypedArray} [resultBuffer] - The result buffer.
  30581. */
  30582. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30583. /**
  30584. * The parameter positions.
  30585. *
  30586. * @type {TypedArray}
  30587. */
  30588. this.parameterPositions = parameterPositions;
  30589. /**
  30590. * A cache index.
  30591. *
  30592. * @private
  30593. * @type {number}
  30594. * @default 0
  30595. */
  30596. this._cachedIndex = 0;
  30597. /**
  30598. * The result buffer.
  30599. *
  30600. * @type {TypedArray}
  30601. */
  30602. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30603. /**
  30604. * The sample values.
  30605. *
  30606. * @type {TypedArray}
  30607. */
  30608. this.sampleValues = sampleValues;
  30609. /**
  30610. * The value size.
  30611. *
  30612. * @type {TypedArray}
  30613. */
  30614. this.valueSize = sampleSize;
  30615. /**
  30616. * The interpolation settings.
  30617. *
  30618. * @type {?Object}
  30619. * @default null
  30620. */
  30621. this.settings = null;
  30622. /**
  30623. * The default settings object.
  30624. *
  30625. * @type {Object}
  30626. */
  30627. this.DefaultSettings_ = {};
  30628. }
  30629. /**
  30630. * Evaluate the interpolant at position `t`.
  30631. *
  30632. * @param {number} t - The interpolation factor.
  30633. * @return {TypedArray} The result buffer.
  30634. */
  30635. evaluate( t ) {
  30636. const pp = this.parameterPositions;
  30637. let i1 = this._cachedIndex,
  30638. t1 = pp[ i1 ],
  30639. t0 = pp[ i1 - 1 ];
  30640. validate_interval: {
  30641. seek: {
  30642. let right;
  30643. linear_scan: {
  30644. //- See http://jsperf.com/comparison-to-undefined/3
  30645. //- slower code:
  30646. //-
  30647. //- if ( t >= t1 || t1 === undefined ) {
  30648. forward_scan: if ( ! ( t < t1 ) ) {
  30649. for ( let giveUpAt = i1 + 2; ; ) {
  30650. if ( t1 === undefined ) {
  30651. if ( t < t0 ) break forward_scan;
  30652. // after end
  30653. i1 = pp.length;
  30654. this._cachedIndex = i1;
  30655. return this.copySampleValue_( i1 - 1 );
  30656. }
  30657. if ( i1 === giveUpAt ) break; // this loop
  30658. t0 = t1;
  30659. t1 = pp[ ++ i1 ];
  30660. if ( t < t1 ) {
  30661. // we have arrived at the sought interval
  30662. break seek;
  30663. }
  30664. }
  30665. // prepare binary search on the right side of the index
  30666. right = pp.length;
  30667. break linear_scan;
  30668. }
  30669. //- slower code:
  30670. //- if ( t < t0 || t0 === undefined ) {
  30671. if ( ! ( t >= t0 ) ) {
  30672. // looping?
  30673. const t1global = pp[ 1 ];
  30674. if ( t < t1global ) {
  30675. i1 = 2; // + 1, using the scan for the details
  30676. t0 = t1global;
  30677. }
  30678. // linear reverse scan
  30679. for ( let giveUpAt = i1 - 2; ; ) {
  30680. if ( t0 === undefined ) {
  30681. // before start
  30682. this._cachedIndex = 0;
  30683. return this.copySampleValue_( 0 );
  30684. }
  30685. if ( i1 === giveUpAt ) break; // this loop
  30686. t1 = t0;
  30687. t0 = pp[ -- i1 - 1 ];
  30688. if ( t >= t0 ) {
  30689. // we have arrived at the sought interval
  30690. break seek;
  30691. }
  30692. }
  30693. // prepare binary search on the left side of the index
  30694. right = i1;
  30695. i1 = 0;
  30696. break linear_scan;
  30697. }
  30698. // the interval is valid
  30699. break validate_interval;
  30700. } // linear scan
  30701. // binary search
  30702. while ( i1 < right ) {
  30703. const mid = ( i1 + right ) >>> 1;
  30704. if ( t < pp[ mid ] ) {
  30705. right = mid;
  30706. } else {
  30707. i1 = mid + 1;
  30708. }
  30709. }
  30710. t1 = pp[ i1 ];
  30711. t0 = pp[ i1 - 1 ];
  30712. // check boundary cases, again
  30713. if ( t0 === undefined ) {
  30714. this._cachedIndex = 0;
  30715. return this.copySampleValue_( 0 );
  30716. }
  30717. if ( t1 === undefined ) {
  30718. i1 = pp.length;
  30719. this._cachedIndex = i1;
  30720. return this.copySampleValue_( i1 - 1 );
  30721. }
  30722. } // seek
  30723. this._cachedIndex = i1;
  30724. this.intervalChanged_( i1, t0, t1 );
  30725. } // validate_interval
  30726. return this.interpolate_( i1, t0, t, t1 );
  30727. }
  30728. /**
  30729. * Returns the interpolation settings.
  30730. *
  30731. * @return {Object} The interpolation settings.
  30732. */
  30733. getSettings_() {
  30734. return this.settings || this.DefaultSettings_;
  30735. }
  30736. /**
  30737. * Copies a sample value to the result buffer.
  30738. *
  30739. * @param {number} index - An index into the sample value buffer.
  30740. * @return {TypedArray} The result buffer.
  30741. */
  30742. copySampleValue_( index ) {
  30743. // copies a sample value to the result buffer
  30744. const result = this.resultBuffer,
  30745. values = this.sampleValues,
  30746. stride = this.valueSize,
  30747. offset = index * stride;
  30748. for ( let i = 0; i !== stride; ++ i ) {
  30749. result[ i ] = values[ offset + i ];
  30750. }
  30751. return result;
  30752. }
  30753. /**
  30754. * Copies a sample value to the result buffer.
  30755. *
  30756. * @abstract
  30757. * @param {number} i1 - An index into the sample value buffer.
  30758. * @param {number} t0 - The previous interpolation factor.
  30759. * @param {number} t - The current interpolation factor.
  30760. * @param {number} t1 - The next interpolation factor.
  30761. * @return {TypedArray} The result buffer.
  30762. */
  30763. interpolate_( /* i1, t0, t, t1 */ ) {
  30764. throw new Error( 'call to abstract method' );
  30765. // implementations shall return this.resultBuffer
  30766. }
  30767. /**
  30768. * Optional method that is executed when the interval has changed.
  30769. *
  30770. * @param {number} i1 - An index into the sample value buffer.
  30771. * @param {number} t0 - The previous interpolation factor.
  30772. * @param {number} t - The current interpolation factor.
  30773. */
  30774. intervalChanged_( /* i1, t0, t1 */ ) {
  30775. // empty
  30776. }
  30777. }
  30778. /**
  30779. * Fast and simple cubic spline interpolant.
  30780. *
  30781. * It was derived from a Hermitian construction setting the first derivative
  30782. * at each sample position to the linear slope between neighboring positions
  30783. * over their parameter interval.
  30784. *
  30785. * @augments Interpolant
  30786. */
  30787. class CubicInterpolant extends Interpolant {
  30788. /**
  30789. * Constructs a new cubic interpolant.
  30790. *
  30791. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30792. * @param {TypedArray} sampleValues - The sample values.
  30793. * @param {number} sampleSize - The sample size
  30794. * @param {TypedArray} [resultBuffer] - The result buffer.
  30795. */
  30796. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30797. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30798. this._weightPrev = -0;
  30799. this._offsetPrev = -0;
  30800. this._weightNext = -0;
  30801. this._offsetNext = -0;
  30802. this.DefaultSettings_ = {
  30803. endingStart: ZeroCurvatureEnding,
  30804. endingEnd: ZeroCurvatureEnding
  30805. };
  30806. }
  30807. intervalChanged_( i1, t0, t1 ) {
  30808. const pp = this.parameterPositions;
  30809. let iPrev = i1 - 2,
  30810. iNext = i1 + 1,
  30811. tPrev = pp[ iPrev ],
  30812. tNext = pp[ iNext ];
  30813. if ( tPrev === undefined ) {
  30814. switch ( this.getSettings_().endingStart ) {
  30815. case ZeroSlopeEnding:
  30816. // f'(t0) = 0
  30817. iPrev = i1;
  30818. tPrev = 2 * t0 - t1;
  30819. break;
  30820. case WrapAroundEnding:
  30821. // use the other end of the curve
  30822. iPrev = pp.length - 2;
  30823. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30824. break;
  30825. default: // ZeroCurvatureEnding
  30826. // f''(t0) = 0 a.k.a. Natural Spline
  30827. iPrev = i1;
  30828. tPrev = t1;
  30829. }
  30830. }
  30831. if ( tNext === undefined ) {
  30832. switch ( this.getSettings_().endingEnd ) {
  30833. case ZeroSlopeEnding:
  30834. // f'(tN) = 0
  30835. iNext = i1;
  30836. tNext = 2 * t1 - t0;
  30837. break;
  30838. case WrapAroundEnding:
  30839. // use the other end of the curve
  30840. iNext = 1;
  30841. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30842. break;
  30843. default: // ZeroCurvatureEnding
  30844. // f''(tN) = 0, a.k.a. Natural Spline
  30845. iNext = i1 - 1;
  30846. tNext = t0;
  30847. }
  30848. }
  30849. const halfDt = ( t1 - t0 ) * 0.5,
  30850. stride = this.valueSize;
  30851. this._weightPrev = halfDt / ( t0 - tPrev );
  30852. this._weightNext = halfDt / ( tNext - t1 );
  30853. this._offsetPrev = iPrev * stride;
  30854. this._offsetNext = iNext * stride;
  30855. }
  30856. interpolate_( i1, t0, t, t1 ) {
  30857. const result = this.resultBuffer,
  30858. values = this.sampleValues,
  30859. stride = this.valueSize,
  30860. o1 = i1 * stride, o0 = o1 - stride,
  30861. oP = this._offsetPrev, oN = this._offsetNext,
  30862. wP = this._weightPrev, wN = this._weightNext,
  30863. p = ( t - t0 ) / ( t1 - t0 ),
  30864. pp = p * p,
  30865. ppp = pp * p;
  30866. // evaluate polynomials
  30867. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30868. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30869. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30870. const sN = wN * ppp - wN * pp;
  30871. // combine data linearly
  30872. for ( let i = 0; i !== stride; ++ i ) {
  30873. result[ i ] =
  30874. sP * values[ oP + i ] +
  30875. s0 * values[ o0 + i ] +
  30876. s1 * values[ o1 + i ] +
  30877. sN * values[ oN + i ];
  30878. }
  30879. return result;
  30880. }
  30881. }
  30882. /**
  30883. * A basic linear interpolant.
  30884. *
  30885. * @augments Interpolant
  30886. */
  30887. class LinearInterpolant extends Interpolant {
  30888. /**
  30889. * Constructs a new linear interpolant.
  30890. *
  30891. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30892. * @param {TypedArray} sampleValues - The sample values.
  30893. * @param {number} sampleSize - The sample size
  30894. * @param {TypedArray} [resultBuffer] - The result buffer.
  30895. */
  30896. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30897. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30898. }
  30899. interpolate_( i1, t0, t, t1 ) {
  30900. const result = this.resultBuffer,
  30901. values = this.sampleValues,
  30902. stride = this.valueSize,
  30903. offset1 = i1 * stride,
  30904. offset0 = offset1 - stride,
  30905. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30906. weight0 = 1 - weight1;
  30907. for ( let i = 0; i !== stride; ++ i ) {
  30908. result[ i ] =
  30909. values[ offset0 + i ] * weight0 +
  30910. values[ offset1 + i ] * weight1;
  30911. }
  30912. return result;
  30913. }
  30914. }
  30915. /**
  30916. * Interpolant that evaluates to the sample value at the position preceding
  30917. * the parameter.
  30918. *
  30919. * @augments Interpolant
  30920. */
  30921. class DiscreteInterpolant extends Interpolant {
  30922. /**
  30923. * Constructs a new discrete interpolant.
  30924. *
  30925. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30926. * @param {TypedArray} sampleValues - The sample values.
  30927. * @param {number} sampleSize - The sample size
  30928. * @param {TypedArray} [resultBuffer] - The result buffer.
  30929. */
  30930. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30931. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30932. }
  30933. interpolate_( i1 /*, t0, t, t1 */ ) {
  30934. return this.copySampleValue_( i1 - 1 );
  30935. }
  30936. }
  30937. /**
  30938. * Represents s a timed sequence of keyframes, which are composed of lists of
  30939. * times and related values, and which are used to animate a specific property
  30940. * of an object.
  30941. */
  30942. class KeyframeTrack {
  30943. /**
  30944. * Constructs a new keyframe track.
  30945. *
  30946. * @param {string} name - The keyframe track's name.
  30947. * @param {Array<number>} times - A list of keyframe times.
  30948. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30949. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30950. */
  30951. constructor( name, times, values, interpolation ) {
  30952. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30953. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30954. /**
  30955. * The track's name can refer to morph targets or bones or
  30956. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30957. * for the forms of strings that can be parsed for property binding.
  30958. *
  30959. * @type {string}
  30960. */
  30961. this.name = name;
  30962. /**
  30963. * The keyframe times.
  30964. *
  30965. * @type {Float32Array}
  30966. */
  30967. this.times = convertArray( times, this.TimeBufferType );
  30968. /**
  30969. * The keyframe values.
  30970. *
  30971. * @type {Float32Array}
  30972. */
  30973. this.values = convertArray( values, this.ValueBufferType );
  30974. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30975. }
  30976. /**
  30977. * Converts the keyframe track to JSON.
  30978. *
  30979. * @static
  30980. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30981. * @return {Object} The serialized keyframe track as JSON.
  30982. */
  30983. static toJSON( track ) {
  30984. const trackType = track.constructor;
  30985. let json;
  30986. // derived classes can define a static toJSON method
  30987. if ( trackType.toJSON !== this.toJSON ) {
  30988. json = trackType.toJSON( track );
  30989. } else {
  30990. // by default, we assume the data can be serialized as-is
  30991. json = {
  30992. 'name': track.name,
  30993. 'times': convertArray( track.times, Array ),
  30994. 'values': convertArray( track.values, Array )
  30995. };
  30996. const interpolation = track.getInterpolation();
  30997. if ( interpolation !== track.DefaultInterpolation ) {
  30998. json.interpolation = interpolation;
  30999. }
  31000. }
  31001. json.type = track.ValueTypeName; // mandatory
  31002. return json;
  31003. }
  31004. /**
  31005. * Factory method for creating a new discrete interpolant.
  31006. *
  31007. * @static
  31008. * @param {TypedArray} [result] - The result buffer.
  31009. * @return {DiscreteInterpolant} The new interpolant.
  31010. */
  31011. InterpolantFactoryMethodDiscrete( result ) {
  31012. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31013. }
  31014. /**
  31015. * Factory method for creating a new linear interpolant.
  31016. *
  31017. * @static
  31018. * @param {TypedArray} [result] - The result buffer.
  31019. * @return {LinearInterpolant} The new interpolant.
  31020. */
  31021. InterpolantFactoryMethodLinear( result ) {
  31022. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31023. }
  31024. /**
  31025. * Factory method for creating a new smooth interpolant.
  31026. *
  31027. * @static
  31028. * @param {TypedArray} [result] - The result buffer.
  31029. * @return {CubicInterpolant} The new interpolant.
  31030. */
  31031. InterpolantFactoryMethodSmooth( result ) {
  31032. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31033. }
  31034. /**
  31035. * Defines the interpolation factor method for this keyframe track.
  31036. *
  31037. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31038. * @return {KeyframeTrack} A reference to this keyframe track.
  31039. */
  31040. setInterpolation( interpolation ) {
  31041. let factoryMethod;
  31042. switch ( interpolation ) {
  31043. case InterpolateDiscrete:
  31044. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31045. break;
  31046. case InterpolateLinear:
  31047. factoryMethod = this.InterpolantFactoryMethodLinear;
  31048. break;
  31049. case InterpolateSmooth:
  31050. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31051. break;
  31052. }
  31053. if ( factoryMethod === undefined ) {
  31054. const message = 'unsupported interpolation for ' +
  31055. this.ValueTypeName + ' keyframe track named ' + this.name;
  31056. if ( this.createInterpolant === undefined ) {
  31057. // fall back to default, unless the default itself is messed up
  31058. if ( interpolation !== this.DefaultInterpolation ) {
  31059. this.setInterpolation( this.DefaultInterpolation );
  31060. } else {
  31061. throw new Error( message ); // fatal, in this case
  31062. }
  31063. }
  31064. warn( 'KeyframeTrack:', message );
  31065. return this;
  31066. }
  31067. this.createInterpolant = factoryMethod;
  31068. return this;
  31069. }
  31070. /**
  31071. * Returns the current interpolation type.
  31072. *
  31073. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31074. */
  31075. getInterpolation() {
  31076. switch ( this.createInterpolant ) {
  31077. case this.InterpolantFactoryMethodDiscrete:
  31078. return InterpolateDiscrete;
  31079. case this.InterpolantFactoryMethodLinear:
  31080. return InterpolateLinear;
  31081. case this.InterpolantFactoryMethodSmooth:
  31082. return InterpolateSmooth;
  31083. }
  31084. }
  31085. /**
  31086. * Returns the value size.
  31087. *
  31088. * @return {number} The value size.
  31089. */
  31090. getValueSize() {
  31091. return this.values.length / this.times.length;
  31092. }
  31093. /**
  31094. * Moves all keyframes either forward or backward in time.
  31095. *
  31096. * @param {number} timeOffset - The offset to move the time values.
  31097. * @return {KeyframeTrack} A reference to this keyframe track.
  31098. */
  31099. shift( timeOffset ) {
  31100. if ( timeOffset !== 0.0 ) {
  31101. const times = this.times;
  31102. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31103. times[ i ] += timeOffset;
  31104. }
  31105. }
  31106. return this;
  31107. }
  31108. /**
  31109. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31110. *
  31111. * @param {number} timeScale - The time scale.
  31112. * @return {KeyframeTrack} A reference to this keyframe track.
  31113. */
  31114. scale( timeScale ) {
  31115. if ( timeScale !== 1.0 ) {
  31116. const times = this.times;
  31117. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31118. times[ i ] *= timeScale;
  31119. }
  31120. }
  31121. return this;
  31122. }
  31123. /**
  31124. * Removes keyframes before and after animation without changing any values within the defined time range.
  31125. *
  31126. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31127. * keys this will change their values
  31128. *
  31129. * @param {number} startTime - The start time.
  31130. * @param {number} endTime - The end time.
  31131. * @return {KeyframeTrack} A reference to this keyframe track.
  31132. */
  31133. trim( startTime, endTime ) {
  31134. const times = this.times,
  31135. nKeys = times.length;
  31136. let from = 0,
  31137. to = nKeys - 1;
  31138. while ( from !== nKeys && times[ from ] < startTime ) {
  31139. ++ from;
  31140. }
  31141. while ( to !== -1 && times[ to ] > endTime ) {
  31142. -- to;
  31143. }
  31144. ++ to; // inclusive -> exclusive bound
  31145. if ( from !== 0 || to !== nKeys ) {
  31146. // empty tracks are forbidden, so keep at least one keyframe
  31147. if ( from >= to ) {
  31148. to = Math.max( to, 1 );
  31149. from = to - 1;
  31150. }
  31151. const stride = this.getValueSize();
  31152. this.times = times.slice( from, to );
  31153. this.values = this.values.slice( from * stride, to * stride );
  31154. }
  31155. return this;
  31156. }
  31157. /**
  31158. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31159. * are valid.
  31160. *
  31161. * @return {boolean} Whether the keyframes are valid or not.
  31162. */
  31163. validate() {
  31164. let valid = true;
  31165. const valueSize = this.getValueSize();
  31166. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31167. error( 'KeyframeTrack: Invalid value size in track.', this );
  31168. valid = false;
  31169. }
  31170. const times = this.times,
  31171. values = this.values,
  31172. nKeys = times.length;
  31173. if ( nKeys === 0 ) {
  31174. error( 'KeyframeTrack: Track is empty.', this );
  31175. valid = false;
  31176. }
  31177. let prevTime = null;
  31178. for ( let i = 0; i !== nKeys; i ++ ) {
  31179. const currTime = times[ i ];
  31180. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31181. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31182. valid = false;
  31183. break;
  31184. }
  31185. if ( prevTime !== null && prevTime > currTime ) {
  31186. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31187. valid = false;
  31188. break;
  31189. }
  31190. prevTime = currTime;
  31191. }
  31192. if ( values !== undefined ) {
  31193. if ( isTypedArray( values ) ) {
  31194. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31195. const value = values[ i ];
  31196. if ( isNaN( value ) ) {
  31197. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31198. valid = false;
  31199. break;
  31200. }
  31201. }
  31202. }
  31203. }
  31204. return valid;
  31205. }
  31206. /**
  31207. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31208. * common in morph target sequences).
  31209. *
  31210. * @return {AnimationClip} A reference to this animation clip.
  31211. */
  31212. optimize() {
  31213. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31214. // times or values may be shared with other tracks, so overwriting is unsafe
  31215. const times = this.times.slice(),
  31216. values = this.values.slice(),
  31217. stride = this.getValueSize(),
  31218. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31219. lastIndex = times.length - 1;
  31220. let writeIndex = 1;
  31221. for ( let i = 1; i < lastIndex; ++ i ) {
  31222. let keep = false;
  31223. const time = times[ i ];
  31224. const timeNext = times[ i + 1 ];
  31225. // remove adjacent keyframes scheduled at the same time
  31226. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31227. if ( ! smoothInterpolation ) {
  31228. // remove unnecessary keyframes same as their neighbors
  31229. const offset = i * stride,
  31230. offsetP = offset - stride,
  31231. offsetN = offset + stride;
  31232. for ( let j = 0; j !== stride; ++ j ) {
  31233. const value = values[ offset + j ];
  31234. if ( value !== values[ offsetP + j ] ||
  31235. value !== values[ offsetN + j ] ) {
  31236. keep = true;
  31237. break;
  31238. }
  31239. }
  31240. } else {
  31241. keep = true;
  31242. }
  31243. }
  31244. // in-place compaction
  31245. if ( keep ) {
  31246. if ( i !== writeIndex ) {
  31247. times[ writeIndex ] = times[ i ];
  31248. const readOffset = i * stride,
  31249. writeOffset = writeIndex * stride;
  31250. for ( let j = 0; j !== stride; ++ j ) {
  31251. values[ writeOffset + j ] = values[ readOffset + j ];
  31252. }
  31253. }
  31254. ++ writeIndex;
  31255. }
  31256. }
  31257. // flush last keyframe (compaction looks ahead)
  31258. if ( lastIndex > 0 ) {
  31259. times[ writeIndex ] = times[ lastIndex ];
  31260. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31261. values[ writeOffset + j ] = values[ readOffset + j ];
  31262. }
  31263. ++ writeIndex;
  31264. }
  31265. if ( writeIndex !== times.length ) {
  31266. this.times = times.slice( 0, writeIndex );
  31267. this.values = values.slice( 0, writeIndex * stride );
  31268. } else {
  31269. this.times = times;
  31270. this.values = values;
  31271. }
  31272. return this;
  31273. }
  31274. /**
  31275. * Returns a new keyframe track with copied values from this instance.
  31276. *
  31277. * @return {KeyframeTrack} A clone of this instance.
  31278. */
  31279. clone() {
  31280. const times = this.times.slice();
  31281. const values = this.values.slice();
  31282. const TypedKeyframeTrack = this.constructor;
  31283. const track = new TypedKeyframeTrack( this.name, times, values );
  31284. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31285. track.createInterpolant = this.createInterpolant;
  31286. return track;
  31287. }
  31288. }
  31289. /**
  31290. * The value type name.
  31291. *
  31292. * @type {string}
  31293. * @default ''
  31294. */
  31295. KeyframeTrack.prototype.ValueTypeName = '';
  31296. /**
  31297. * The time buffer type of this keyframe track.
  31298. *
  31299. * @type {TypedArray|Array}
  31300. * @default Float32Array.constructor
  31301. */
  31302. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31303. /**
  31304. * The value buffer type of this keyframe track.
  31305. *
  31306. * @type {TypedArray|Array}
  31307. * @default Float32Array.constructor
  31308. */
  31309. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31310. /**
  31311. * The default interpolation type of this keyframe track.
  31312. *
  31313. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31314. * @default InterpolateLinear
  31315. */
  31316. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31317. /**
  31318. * A track for boolean keyframe values.
  31319. *
  31320. * @augments KeyframeTrack
  31321. */
  31322. class BooleanKeyframeTrack extends KeyframeTrack {
  31323. /**
  31324. * Constructs a new boolean keyframe track.
  31325. *
  31326. * This keyframe track type has no `interpolation` parameter because the
  31327. * interpolation is always discrete.
  31328. *
  31329. * @param {string} name - The keyframe track's name.
  31330. * @param {Array<number>} times - A list of keyframe times.
  31331. * @param {Array<boolean>} values - A list of keyframe values.
  31332. */
  31333. constructor( name, times, values ) {
  31334. super( name, times, values );
  31335. }
  31336. }
  31337. /**
  31338. * The value type name.
  31339. *
  31340. * @type {string}
  31341. * @default 'bool'
  31342. */
  31343. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31344. /**
  31345. * The value buffer type of this keyframe track.
  31346. *
  31347. * @type {TypedArray|Array}
  31348. * @default Array.constructor
  31349. */
  31350. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31351. /**
  31352. * The default interpolation type of this keyframe track.
  31353. *
  31354. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31355. * @default InterpolateDiscrete
  31356. */
  31357. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31358. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31359. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31360. /**
  31361. * A track for color keyframe values.
  31362. *
  31363. * @augments KeyframeTrack
  31364. */
  31365. class ColorKeyframeTrack extends KeyframeTrack {
  31366. /**
  31367. * Constructs a new color keyframe track.
  31368. *
  31369. * @param {string} name - The keyframe track's name.
  31370. * @param {Array<number>} times - A list of keyframe times.
  31371. * @param {Array<number>} values - A list of keyframe values.
  31372. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31373. */
  31374. constructor( name, times, values, interpolation ) {
  31375. super( name, times, values, interpolation );
  31376. }
  31377. }
  31378. /**
  31379. * The value type name.
  31380. *
  31381. * @type {string}
  31382. * @default 'color'
  31383. */
  31384. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31385. /**
  31386. * A track for numeric keyframe values.
  31387. *
  31388. * @augments KeyframeTrack
  31389. */
  31390. class NumberKeyframeTrack extends KeyframeTrack {
  31391. /**
  31392. * Constructs a new number keyframe track.
  31393. *
  31394. * @param {string} name - The keyframe track's name.
  31395. * @param {Array<number>} times - A list of keyframe times.
  31396. * @param {Array<number>} values - A list of keyframe values.
  31397. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31398. */
  31399. constructor( name, times, values, interpolation ) {
  31400. super( name, times, values, interpolation );
  31401. }
  31402. }
  31403. /**
  31404. * The value type name.
  31405. *
  31406. * @type {string}
  31407. * @default 'number'
  31408. */
  31409. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31410. /**
  31411. * Spherical linear unit quaternion interpolant.
  31412. *
  31413. * @augments Interpolant
  31414. */
  31415. class QuaternionLinearInterpolant extends Interpolant {
  31416. /**
  31417. * Constructs a new SLERP interpolant.
  31418. *
  31419. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31420. * @param {TypedArray} sampleValues - The sample values.
  31421. * @param {number} sampleSize - The sample size
  31422. * @param {TypedArray} [resultBuffer] - The result buffer.
  31423. */
  31424. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31425. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31426. }
  31427. interpolate_( i1, t0, t, t1 ) {
  31428. const result = this.resultBuffer,
  31429. values = this.sampleValues,
  31430. stride = this.valueSize,
  31431. alpha = ( t - t0 ) / ( t1 - t0 );
  31432. let offset = i1 * stride;
  31433. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31434. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31435. }
  31436. return result;
  31437. }
  31438. }
  31439. /**
  31440. * A track for Quaternion keyframe values.
  31441. *
  31442. * @augments KeyframeTrack
  31443. */
  31444. class QuaternionKeyframeTrack extends KeyframeTrack {
  31445. /**
  31446. * Constructs a new Quaternion keyframe track.
  31447. *
  31448. * @param {string} name - The keyframe track's name.
  31449. * @param {Array<number>} times - A list of keyframe times.
  31450. * @param {Array<number>} values - A list of keyframe values.
  31451. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31452. */
  31453. constructor( name, times, values, interpolation ) {
  31454. super( name, times, values, interpolation );
  31455. }
  31456. /**
  31457. * Overwritten so the method returns Quaternion based interpolant.
  31458. *
  31459. * @static
  31460. * @param {TypedArray} [result] - The result buffer.
  31461. * @return {QuaternionLinearInterpolant} The new interpolant.
  31462. */
  31463. InterpolantFactoryMethodLinear( result ) {
  31464. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31465. }
  31466. }
  31467. /**
  31468. * The value type name.
  31469. *
  31470. * @type {string}
  31471. * @default 'quaternion'
  31472. */
  31473. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31474. // ValueBufferType is inherited
  31475. // DefaultInterpolation is inherited;
  31476. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31477. /**
  31478. * A track for string keyframe values.
  31479. *
  31480. * @augments KeyframeTrack
  31481. */
  31482. class StringKeyframeTrack extends KeyframeTrack {
  31483. /**
  31484. * Constructs a new string keyframe track.
  31485. *
  31486. * This keyframe track type has no `interpolation` parameter because the
  31487. * interpolation is always discrete.
  31488. *
  31489. * @param {string} name - The keyframe track's name.
  31490. * @param {Array<number>} times - A list of keyframe times.
  31491. * @param {Array<string>} values - A list of keyframe values.
  31492. */
  31493. constructor( name, times, values ) {
  31494. super( name, times, values );
  31495. }
  31496. }
  31497. /**
  31498. * The value type name.
  31499. *
  31500. * @type {string}
  31501. * @default 'string'
  31502. */
  31503. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31504. /**
  31505. * The value buffer type of this keyframe track.
  31506. *
  31507. * @type {TypedArray|Array}
  31508. * @default Array.constructor
  31509. */
  31510. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31511. /**
  31512. * The default interpolation type of this keyframe track.
  31513. *
  31514. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31515. * @default InterpolateDiscrete
  31516. */
  31517. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31518. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31519. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31520. /**
  31521. * A track for vector keyframe values.
  31522. *
  31523. * @augments KeyframeTrack
  31524. */
  31525. class VectorKeyframeTrack extends KeyframeTrack {
  31526. /**
  31527. * Constructs a new vector keyframe track.
  31528. *
  31529. * @param {string} name - The keyframe track's name.
  31530. * @param {Array<number>} times - A list of keyframe times.
  31531. * @param {Array<number>} values - A list of keyframe values.
  31532. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31533. */
  31534. constructor( name, times, values, interpolation ) {
  31535. super( name, times, values, interpolation );
  31536. }
  31537. }
  31538. /**
  31539. * The value type name.
  31540. *
  31541. * @type {string}
  31542. * @default 'vector'
  31543. */
  31544. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31545. /**
  31546. * A reusable set of keyframe tracks which represent an animation.
  31547. */
  31548. class AnimationClip {
  31549. /**
  31550. * Constructs a new animation clip.
  31551. *
  31552. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31553. * use the static interface of this class for creating clips. In most cases though, animation clips
  31554. * will automatically be created by loaders when importing animated 3D assets.
  31555. *
  31556. * @param {string} [name=''] - The clip's name.
  31557. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31558. * the duration will be calculated from the passed keyframes.
  31559. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31560. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31561. * is blended/combined when two or more animations are simultaneously played.
  31562. */
  31563. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31564. /**
  31565. * The clip's name.
  31566. *
  31567. * @type {string}
  31568. */
  31569. this.name = name;
  31570. /**
  31571. * An array of keyframe tracks.
  31572. *
  31573. * @type {Array<KeyframeTrack>}
  31574. */
  31575. this.tracks = tracks;
  31576. /**
  31577. * The clip's duration in seconds.
  31578. *
  31579. * @type {number}
  31580. */
  31581. this.duration = duration;
  31582. /**
  31583. * Defines how the animation is blended/combined when two or more animations
  31584. * are simultaneously played.
  31585. *
  31586. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31587. */
  31588. this.blendMode = blendMode;
  31589. /**
  31590. * The UUID of the animation clip.
  31591. *
  31592. * @type {string}
  31593. * @readonly
  31594. */
  31595. this.uuid = generateUUID();
  31596. /**
  31597. * An object that can be used to store custom data about the animation clip.
  31598. * It should not hold references to functions as these will not be cloned.
  31599. *
  31600. * @type {Object}
  31601. */
  31602. this.userData = {};
  31603. // this means it should figure out its duration by scanning the tracks
  31604. if ( this.duration < 0 ) {
  31605. this.resetDuration();
  31606. }
  31607. }
  31608. /**
  31609. * Factory method for creating an animation clip from the given JSON.
  31610. *
  31611. * @static
  31612. * @param {Object} json - The serialized animation clip.
  31613. * @return {AnimationClip} The new animation clip.
  31614. */
  31615. static parse( json ) {
  31616. const tracks = [],
  31617. jsonTracks = json.tracks,
  31618. frameTime = 1.0 / ( json.fps || 1.0 );
  31619. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31620. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31621. }
  31622. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31623. clip.uuid = json.uuid;
  31624. clip.userData = JSON.parse( json.userData || '{}' );
  31625. return clip;
  31626. }
  31627. /**
  31628. * Serializes the given animation clip into JSON.
  31629. *
  31630. * @static
  31631. * @param {AnimationClip} clip - The animation clip to serialize.
  31632. * @return {Object} The JSON object.
  31633. */
  31634. static toJSON( clip ) {
  31635. const tracks = [],
  31636. clipTracks = clip.tracks;
  31637. const json = {
  31638. 'name': clip.name,
  31639. 'duration': clip.duration,
  31640. 'tracks': tracks,
  31641. 'uuid': clip.uuid,
  31642. 'blendMode': clip.blendMode,
  31643. 'userData': JSON.stringify( clip.userData ),
  31644. };
  31645. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31646. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31647. }
  31648. return json;
  31649. }
  31650. /**
  31651. * Returns a new animation clip from the passed morph targets array of a
  31652. * geometry, taking a name and the number of frames per second.
  31653. *
  31654. * Note: The fps parameter is required, but the animation speed can be
  31655. * overridden via {@link AnimationAction#setDuration}.
  31656. *
  31657. * @static
  31658. * @param {string} name - The name of the animation clip.
  31659. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31660. * @param {number} fps - The Frames-Per-Second value.
  31661. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31662. * @return {AnimationClip} The new animation clip.
  31663. */
  31664. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31665. const numMorphTargets = morphTargetSequence.length;
  31666. const tracks = [];
  31667. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31668. let times = [];
  31669. let values = [];
  31670. times.push(
  31671. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31672. i,
  31673. ( i + 1 ) % numMorphTargets );
  31674. values.push( 0, 1, 0 );
  31675. const order = getKeyframeOrder( times );
  31676. times = sortedArray( times, 1, order );
  31677. values = sortedArray( values, 1, order );
  31678. // if there is a key at the first frame, duplicate it as the
  31679. // last frame as well for perfect loop.
  31680. if ( ! noLoop && times[ 0 ] === 0 ) {
  31681. times.push( numMorphTargets );
  31682. values.push( values[ 0 ] );
  31683. }
  31684. tracks.push(
  31685. new NumberKeyframeTrack(
  31686. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31687. times, values
  31688. ).scale( 1.0 / fps ) );
  31689. }
  31690. return new this( name, -1, tracks );
  31691. }
  31692. /**
  31693. * Searches for an animation clip by name, taking as its first parameter
  31694. * either an array of clips, or a mesh or geometry that contains an
  31695. * array named "animations" property.
  31696. *
  31697. * @static
  31698. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31699. * @param {string} name - The name to search for.
  31700. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31701. */
  31702. static findByName( objectOrClipArray, name ) {
  31703. let clipArray = objectOrClipArray;
  31704. if ( ! Array.isArray( objectOrClipArray ) ) {
  31705. const o = objectOrClipArray;
  31706. clipArray = o.geometry && o.geometry.animations || o.animations;
  31707. }
  31708. for ( let i = 0; i < clipArray.length; i ++ ) {
  31709. if ( clipArray[ i ].name === name ) {
  31710. return clipArray[ i ];
  31711. }
  31712. }
  31713. return null;
  31714. }
  31715. /**
  31716. * Returns an array of new AnimationClips created from the morph target
  31717. * sequences of a geometry, trying to sort morph target names into
  31718. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31719. *
  31720. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31721. *
  31722. * @static
  31723. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31724. * @param {number} fps - The Frames-Per-Second value.
  31725. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31726. * @return {Array<AnimationClip>} An array of new animation clips.
  31727. */
  31728. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31729. const animationToMorphTargets = {};
  31730. // tested with https://regex101.com/ on trick sequences
  31731. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31732. const pattern = /^([\w-]*?)([\d]+)$/;
  31733. // sort morph target names into animation groups based
  31734. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31735. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31736. const morphTarget = morphTargets[ i ];
  31737. const parts = morphTarget.name.match( pattern );
  31738. if ( parts && parts.length > 1 ) {
  31739. const name = parts[ 1 ];
  31740. let animationMorphTargets = animationToMorphTargets[ name ];
  31741. if ( ! animationMorphTargets ) {
  31742. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31743. }
  31744. animationMorphTargets.push( morphTarget );
  31745. }
  31746. }
  31747. const clips = [];
  31748. for ( const name in animationToMorphTargets ) {
  31749. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31750. }
  31751. return clips;
  31752. }
  31753. /**
  31754. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31755. *
  31756. * @static
  31757. * @deprecated since r175.
  31758. * @param {Object} animation - A serialized animation clip as JSON.
  31759. * @param {Array<Bones>} bones - An array of bones.
  31760. * @return {?AnimationClip} The new animation clip.
  31761. */
  31762. static parseAnimation( animation, bones ) {
  31763. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31764. if ( ! animation ) {
  31765. error( 'AnimationClip: No animation in JSONLoader data.' );
  31766. return null;
  31767. }
  31768. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31769. // only return track if there are actually keys.
  31770. if ( animationKeys.length !== 0 ) {
  31771. const times = [];
  31772. const values = [];
  31773. flattenJSON( animationKeys, times, values, propertyName );
  31774. // empty keys are filtered out, so check again
  31775. if ( times.length !== 0 ) {
  31776. destTracks.push( new trackType( trackName, times, values ) );
  31777. }
  31778. }
  31779. };
  31780. const tracks = [];
  31781. const clipName = animation.name || 'default';
  31782. const fps = animation.fps || 30;
  31783. const blendMode = animation.blendMode;
  31784. // automatic length determination in AnimationClip.
  31785. let duration = animation.length || -1;
  31786. const hierarchyTracks = animation.hierarchy || [];
  31787. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31788. const animationKeys = hierarchyTracks[ h ].keys;
  31789. // skip empty tracks
  31790. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31791. // process morph targets
  31792. if ( animationKeys[ 0 ].morphTargets ) {
  31793. // figure out all morph targets used in this track
  31794. const morphTargetNames = {};
  31795. let k;
  31796. for ( k = 0; k < animationKeys.length; k ++ ) {
  31797. if ( animationKeys[ k ].morphTargets ) {
  31798. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31799. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31800. }
  31801. }
  31802. }
  31803. // create a track for each morph target with all zero
  31804. // morphTargetInfluences except for the keys in which
  31805. // the morphTarget is named.
  31806. for ( const morphTargetName in morphTargetNames ) {
  31807. const times = [];
  31808. const values = [];
  31809. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31810. const animationKey = animationKeys[ k ];
  31811. times.push( animationKey.time );
  31812. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31813. }
  31814. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31815. }
  31816. duration = morphTargetNames.length * fps;
  31817. } else {
  31818. // ...assume skeletal animation
  31819. const boneName = '.bones[' + bones[ h ].name + ']';
  31820. addNonemptyTrack(
  31821. VectorKeyframeTrack, boneName + '.position',
  31822. animationKeys, 'pos', tracks );
  31823. addNonemptyTrack(
  31824. QuaternionKeyframeTrack, boneName + '.quaternion',
  31825. animationKeys, 'rot', tracks );
  31826. addNonemptyTrack(
  31827. VectorKeyframeTrack, boneName + '.scale',
  31828. animationKeys, 'scl', tracks );
  31829. }
  31830. }
  31831. if ( tracks.length === 0 ) {
  31832. return null;
  31833. }
  31834. const clip = new this( clipName, duration, tracks, blendMode );
  31835. return clip;
  31836. }
  31837. /**
  31838. * Sets the duration of this clip to the duration of its longest keyframe track.
  31839. *
  31840. * @return {AnimationClip} A reference to this animation clip.
  31841. */
  31842. resetDuration() {
  31843. const tracks = this.tracks;
  31844. let duration = 0;
  31845. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31846. const track = this.tracks[ i ];
  31847. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31848. }
  31849. this.duration = duration;
  31850. return this;
  31851. }
  31852. /**
  31853. * Trims all tracks to the clip's duration.
  31854. *
  31855. * @return {AnimationClip} A reference to this animation clip.
  31856. */
  31857. trim() {
  31858. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31859. this.tracks[ i ].trim( 0, this.duration );
  31860. }
  31861. return this;
  31862. }
  31863. /**
  31864. * Performs minimal validation on each track in the clip. Returns `true` if all
  31865. * tracks are valid.
  31866. *
  31867. * @return {boolean} Whether the clip's keyframes are valid or not.
  31868. */
  31869. validate() {
  31870. let valid = true;
  31871. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31872. valid = valid && this.tracks[ i ].validate();
  31873. }
  31874. return valid;
  31875. }
  31876. /**
  31877. * Optimizes each track by removing equivalent sequential keys (which are
  31878. * common in morph target sequences).
  31879. *
  31880. * @return {AnimationClip} A reference to this animation clip.
  31881. */
  31882. optimize() {
  31883. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31884. this.tracks[ i ].optimize();
  31885. }
  31886. return this;
  31887. }
  31888. /**
  31889. * Returns a new animation clip with copied values from this instance.
  31890. *
  31891. * @return {AnimationClip} A clone of this instance.
  31892. */
  31893. clone() {
  31894. const tracks = [];
  31895. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31896. tracks.push( this.tracks[ i ].clone() );
  31897. }
  31898. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31899. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31900. return clip;
  31901. }
  31902. /**
  31903. * Serializes this animation clip into JSON.
  31904. *
  31905. * @return {Object} The JSON object.
  31906. */
  31907. toJSON() {
  31908. return this.constructor.toJSON( this );
  31909. }
  31910. }
  31911. function getTrackTypeForValueTypeName( typeName ) {
  31912. switch ( typeName.toLowerCase() ) {
  31913. case 'scalar':
  31914. case 'double':
  31915. case 'float':
  31916. case 'number':
  31917. case 'integer':
  31918. return NumberKeyframeTrack;
  31919. case 'vector':
  31920. case 'vector2':
  31921. case 'vector3':
  31922. case 'vector4':
  31923. return VectorKeyframeTrack;
  31924. case 'color':
  31925. return ColorKeyframeTrack;
  31926. case 'quaternion':
  31927. return QuaternionKeyframeTrack;
  31928. case 'bool':
  31929. case 'boolean':
  31930. return BooleanKeyframeTrack;
  31931. case 'string':
  31932. return StringKeyframeTrack;
  31933. }
  31934. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31935. }
  31936. function parseKeyframeTrack( json ) {
  31937. if ( json.type === undefined ) {
  31938. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31939. }
  31940. const trackType = getTrackTypeForValueTypeName( json.type );
  31941. if ( json.times === undefined ) {
  31942. const times = [], values = [];
  31943. flattenJSON( json.keys, times, values, 'value' );
  31944. json.times = times;
  31945. json.values = values;
  31946. }
  31947. // derived classes can define a static parse method
  31948. if ( trackType.parse !== undefined ) {
  31949. return trackType.parse( json );
  31950. } else {
  31951. // by default, we assume a constructor compatible with the base
  31952. return new trackType( json.name, json.times, json.values, json.interpolation );
  31953. }
  31954. }
  31955. /**
  31956. * @class
  31957. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31958. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31959. * @hideconstructor
  31960. */
  31961. const Cache = {
  31962. /**
  31963. * Whether caching is enabled or not.
  31964. *
  31965. * @static
  31966. * @type {boolean}
  31967. * @default false
  31968. */
  31969. enabled: false,
  31970. /**
  31971. * A dictionary that holds cached files.
  31972. *
  31973. * @static
  31974. * @type {Object<string,Object>}
  31975. */
  31976. files: {},
  31977. /**
  31978. * Adds a cache entry with a key to reference the file. If this key already
  31979. * holds a file, it is overwritten.
  31980. *
  31981. * @static
  31982. * @param {string} key - The key to reference the cached file.
  31983. * @param {Object} file - The file to be cached.
  31984. */
  31985. add: function ( key, file ) {
  31986. if ( this.enabled === false ) return;
  31987. // log( 'Cache', 'Adding key:', key );
  31988. this.files[ key ] = file;
  31989. },
  31990. /**
  31991. * Gets the cached value for the given key.
  31992. *
  31993. * @static
  31994. * @param {string} key - The key to reference the cached file.
  31995. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31996. */
  31997. get: function ( key ) {
  31998. if ( this.enabled === false ) return;
  31999. // log( 'Cache', 'Checking key:', key );
  32000. return this.files[ key ];
  32001. },
  32002. /**
  32003. * Removes the cached file associated with the given key.
  32004. *
  32005. * @static
  32006. * @param {string} key - The key to reference the cached file.
  32007. */
  32008. remove: function ( key ) {
  32009. delete this.files[ key ];
  32010. },
  32011. /**
  32012. * Remove all values from the cache.
  32013. *
  32014. * @static
  32015. */
  32016. clear: function () {
  32017. this.files = {};
  32018. }
  32019. };
  32020. /**
  32021. * Handles and keeps track of loaded and pending data. A default global
  32022. * instance of this class is created and used by loaders if not supplied
  32023. * manually.
  32024. *
  32025. * In general that should be sufficient, however there are times when it can
  32026. * be useful to have separate loaders - for example if you want to show
  32027. * separate loading bars for objects and textures.
  32028. *
  32029. * ```js
  32030. * const manager = new THREE.LoadingManager();
  32031. * manager.onLoad = () => console.log( 'Loading complete!' );
  32032. *
  32033. * const loader1 = new OBJLoader( manager );
  32034. * const loader2 = new ColladaLoader( manager );
  32035. * ```
  32036. */
  32037. class LoadingManager {
  32038. /**
  32039. * Constructs a new loading manager.
  32040. *
  32041. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32042. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32043. * @param {Function} [onError] - Executes when an error occurs.
  32044. */
  32045. constructor( onLoad, onProgress, onError ) {
  32046. const scope = this;
  32047. let isLoading = false;
  32048. let itemsLoaded = 0;
  32049. let itemsTotal = 0;
  32050. let urlModifier = undefined;
  32051. const handlers = [];
  32052. // Refer to #5689 for the reason why we don't set .onStart
  32053. // in the constructor
  32054. /**
  32055. * Executes when an item starts loading.
  32056. *
  32057. * @type {Function|undefined}
  32058. * @default undefined
  32059. */
  32060. this.onStart = undefined;
  32061. /**
  32062. * Executes when all items have been loaded.
  32063. *
  32064. * @type {Function|undefined}
  32065. * @default undefined
  32066. */
  32067. this.onLoad = onLoad;
  32068. /**
  32069. * Executes when single items have been loaded.
  32070. *
  32071. * @type {Function|undefined}
  32072. * @default undefined
  32073. */
  32074. this.onProgress = onProgress;
  32075. /**
  32076. * Executes when an error occurs.
  32077. *
  32078. * @type {Function|undefined}
  32079. * @default undefined
  32080. */
  32081. this.onError = onError;
  32082. /**
  32083. * Used for aborting ongoing requests in loaders using this manager.
  32084. *
  32085. * @private
  32086. * @type {AbortController | null}
  32087. */
  32088. this._abortController = null;
  32089. /**
  32090. * This should be called by any loader using the manager when the loader
  32091. * starts loading an item.
  32092. *
  32093. * @param {string} url - The URL to load.
  32094. */
  32095. this.itemStart = function ( url ) {
  32096. itemsTotal ++;
  32097. if ( isLoading === false ) {
  32098. if ( scope.onStart !== undefined ) {
  32099. scope.onStart( url, itemsLoaded, itemsTotal );
  32100. }
  32101. }
  32102. isLoading = true;
  32103. };
  32104. /**
  32105. * This should be called by any loader using the manager when the loader
  32106. * ended loading an item.
  32107. *
  32108. * @param {string} url - The URL of the loaded item.
  32109. */
  32110. this.itemEnd = function ( url ) {
  32111. itemsLoaded ++;
  32112. if ( scope.onProgress !== undefined ) {
  32113. scope.onProgress( url, itemsLoaded, itemsTotal );
  32114. }
  32115. if ( itemsLoaded === itemsTotal ) {
  32116. isLoading = false;
  32117. if ( scope.onLoad !== undefined ) {
  32118. scope.onLoad();
  32119. }
  32120. }
  32121. };
  32122. /**
  32123. * This should be called by any loader using the manager when the loader
  32124. * encounters an error when loading an item.
  32125. *
  32126. * @param {string} url - The URL of the item that produces an error.
  32127. */
  32128. this.itemError = function ( url ) {
  32129. if ( scope.onError !== undefined ) {
  32130. scope.onError( url );
  32131. }
  32132. };
  32133. /**
  32134. * Given a URL, uses the URL modifier callback (if any) and returns a
  32135. * resolved URL. If no URL modifier is set, returns the original URL.
  32136. *
  32137. * @param {string} url - The URL to load.
  32138. * @return {string} The resolved URL.
  32139. */
  32140. this.resolveURL = function ( url ) {
  32141. if ( urlModifier ) {
  32142. return urlModifier( url );
  32143. }
  32144. return url;
  32145. };
  32146. /**
  32147. * If provided, the callback will be passed each resource URL before a
  32148. * request is sent. The callback may return the original URL, or a new URL to
  32149. * override loading behavior. This behavior can be used to load assets from
  32150. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32151. *
  32152. * ```js
  32153. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32154. *
  32155. * const manager = new THREE.LoadingManager();
  32156. *
  32157. * // Initialize loading manager with URL callback.
  32158. * const objectURLs = [];
  32159. * manager.setURLModifier( ( url ) => {
  32160. *
  32161. * url = URL.createObjectURL( blobs[ url ] );
  32162. * objectURLs.push( url );
  32163. * return url;
  32164. *
  32165. * } );
  32166. *
  32167. * // Load as usual, then revoke the blob URLs.
  32168. * const loader = new GLTFLoader( manager );
  32169. * loader.load( 'fish.gltf', (gltf) => {
  32170. *
  32171. * scene.add( gltf.scene );
  32172. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32173. *
  32174. * } );
  32175. * ```
  32176. *
  32177. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32178. * @return {LoadingManager} A reference to this loading manager.
  32179. */
  32180. this.setURLModifier = function ( transform ) {
  32181. urlModifier = transform;
  32182. return this;
  32183. };
  32184. /**
  32185. * Registers a loader with the given regular expression. Can be used to
  32186. * define what loader should be used in order to load specific files. A
  32187. * typical use case is to overwrite the default loader for textures.
  32188. *
  32189. * ```js
  32190. * // add handler for TGA textures
  32191. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32192. * ```
  32193. *
  32194. * @param {string} regex - A regular expression.
  32195. * @param {Loader} loader - A loader that should handle matched cases.
  32196. * @return {LoadingManager} A reference to this loading manager.
  32197. */
  32198. this.addHandler = function ( regex, loader ) {
  32199. handlers.push( regex, loader );
  32200. return this;
  32201. };
  32202. /**
  32203. * Removes the loader for the given regular expression.
  32204. *
  32205. * @param {string} regex - A regular expression.
  32206. * @return {LoadingManager} A reference to this loading manager.
  32207. */
  32208. this.removeHandler = function ( regex ) {
  32209. const index = handlers.indexOf( regex );
  32210. if ( index !== -1 ) {
  32211. handlers.splice( index, 2 );
  32212. }
  32213. return this;
  32214. };
  32215. /**
  32216. * Can be used to retrieve the registered loader for the given file path.
  32217. *
  32218. * @param {string} file - The file path.
  32219. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32220. */
  32221. this.getHandler = function ( file ) {
  32222. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32223. const regex = handlers[ i ];
  32224. const loader = handlers[ i + 1 ];
  32225. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32226. if ( regex.test( file ) ) {
  32227. return loader;
  32228. }
  32229. }
  32230. return null;
  32231. };
  32232. /**
  32233. * Can be used to abort ongoing loading requests in loaders using this manager.
  32234. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32235. * is supported in the browser.
  32236. *
  32237. * @return {LoadingManager} A reference to this loading manager.
  32238. */
  32239. this.abort = function () {
  32240. this.abortController.abort();
  32241. this._abortController = null;
  32242. return this;
  32243. };
  32244. }
  32245. // TODO: Revert this back to a single member variable once this issue has been fixed
  32246. // https://github.com/cloudflare/workerd/issues/3657
  32247. /**
  32248. * Used for aborting ongoing requests in loaders using this manager.
  32249. *
  32250. * @type {AbortController}
  32251. */
  32252. get abortController() {
  32253. if ( ! this._abortController ) {
  32254. this._abortController = new AbortController();
  32255. }
  32256. return this._abortController;
  32257. }
  32258. }
  32259. /**
  32260. * The global default loading manager.
  32261. *
  32262. * @constant
  32263. * @type {LoadingManager}
  32264. */
  32265. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32266. /**
  32267. * Abstract base class for loaders.
  32268. *
  32269. * @abstract
  32270. */
  32271. class Loader {
  32272. /**
  32273. * Constructs a new loader.
  32274. *
  32275. * @param {LoadingManager} [manager] - The loading manager.
  32276. */
  32277. constructor( manager ) {
  32278. /**
  32279. * The loading manager.
  32280. *
  32281. * @type {LoadingManager}
  32282. * @default DefaultLoadingManager
  32283. */
  32284. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32285. /**
  32286. * The crossOrigin string to implement CORS for loading the url from a
  32287. * different domain that allows CORS.
  32288. *
  32289. * @type {string}
  32290. * @default 'anonymous'
  32291. */
  32292. this.crossOrigin = 'anonymous';
  32293. /**
  32294. * Whether the XMLHttpRequest uses credentials.
  32295. *
  32296. * @type {boolean}
  32297. * @default false
  32298. */
  32299. this.withCredentials = false;
  32300. /**
  32301. * The base path from which the asset will be loaded.
  32302. *
  32303. * @type {string}
  32304. */
  32305. this.path = '';
  32306. /**
  32307. * The base path from which additional resources like textures will be loaded.
  32308. *
  32309. * @type {string}
  32310. */
  32311. this.resourcePath = '';
  32312. /**
  32313. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32314. * used in HTTP request.
  32315. *
  32316. * @type {Object<string, any>}
  32317. */
  32318. this.requestHeader = {};
  32319. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32320. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32321. }
  32322. }
  32323. /**
  32324. * This method needs to be implemented by all concrete loaders. It holds the
  32325. * logic for loading assets from the backend.
  32326. *
  32327. * @abstract
  32328. * @param {string} url - The path/URL of the file to be loaded.
  32329. * @param {Function} onLoad - Executed when the loading process has been finished.
  32330. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32331. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32332. */
  32333. load( /* url, onLoad, onProgress, onError */ ) {}
  32334. /**
  32335. * A async version of {@link Loader#load}.
  32336. *
  32337. * @param {string} url - The path/URL of the file to be loaded.
  32338. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32339. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32340. */
  32341. loadAsync( url, onProgress ) {
  32342. const scope = this;
  32343. return new Promise( function ( resolve, reject ) {
  32344. scope.load( url, resolve, onProgress, reject );
  32345. } );
  32346. }
  32347. /**
  32348. * This method needs to be implemented by all concrete loaders. It holds the
  32349. * logic for parsing the asset into three.js entities.
  32350. *
  32351. * @abstract
  32352. * @param {any} data - The data to parse.
  32353. */
  32354. parse( /* data */ ) {}
  32355. /**
  32356. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32357. * from a different domain that allows CORS.
  32358. *
  32359. * @param {string} crossOrigin - The `crossOrigin` value.
  32360. * @return {Loader} A reference to this instance.
  32361. */
  32362. setCrossOrigin( crossOrigin ) {
  32363. this.crossOrigin = crossOrigin;
  32364. return this;
  32365. }
  32366. /**
  32367. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32368. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32369. *
  32370. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32371. *
  32372. * @param {boolean} value - The `withCredentials` value.
  32373. * @return {Loader} A reference to this instance.
  32374. */
  32375. setWithCredentials( value ) {
  32376. this.withCredentials = value;
  32377. return this;
  32378. }
  32379. /**
  32380. * Sets the base path for the asset.
  32381. *
  32382. * @param {string} path - The base path.
  32383. * @return {Loader} A reference to this instance.
  32384. */
  32385. setPath( path ) {
  32386. this.path = path;
  32387. return this;
  32388. }
  32389. /**
  32390. * Sets the base path for dependent resources like textures.
  32391. *
  32392. * @param {string} resourcePath - The resource path.
  32393. * @return {Loader} A reference to this instance.
  32394. */
  32395. setResourcePath( resourcePath ) {
  32396. this.resourcePath = resourcePath;
  32397. return this;
  32398. }
  32399. /**
  32400. * Sets the given request header.
  32401. *
  32402. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32403. * for configuring the HTTP request.
  32404. * @return {Loader} A reference to this instance.
  32405. */
  32406. setRequestHeader( requestHeader ) {
  32407. this.requestHeader = requestHeader;
  32408. return this;
  32409. }
  32410. /**
  32411. * This method can be implemented in loaders for aborting ongoing requests.
  32412. *
  32413. * @abstract
  32414. * @return {Loader} A reference to this instance.
  32415. */
  32416. abort() {
  32417. return this;
  32418. }
  32419. }
  32420. /**
  32421. * Callback for onProgress in loaders.
  32422. *
  32423. * @callback onProgressCallback
  32424. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32425. */
  32426. /**
  32427. * Callback for onError in loaders.
  32428. *
  32429. * @callback onErrorCallback
  32430. * @param {Error} error - The error which occurred during the loading process.
  32431. */
  32432. /**
  32433. * The default material name that is used by loaders
  32434. * when creating materials for loaded 3D objects.
  32435. *
  32436. * Note: Not all loaders might honor this setting.
  32437. *
  32438. * @static
  32439. * @type {string}
  32440. * @default '__DEFAULT'
  32441. */
  32442. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32443. const loading = {};
  32444. class HttpError extends Error {
  32445. constructor( message, response ) {
  32446. super( message );
  32447. this.response = response;
  32448. }
  32449. }
  32450. /**
  32451. * A low level class for loading resources with the Fetch API, used internally by
  32452. * most loaders. It can also be used directly to load any file type that does
  32453. * not have a loader.
  32454. *
  32455. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32456. * once to your application.
  32457. *
  32458. * ```js
  32459. * const loader = new THREE.FileLoader();
  32460. * const data = await loader.loadAsync( 'example.txt' );
  32461. * ```
  32462. *
  32463. * @augments Loader
  32464. */
  32465. class FileLoader extends Loader {
  32466. /**
  32467. * Constructs a new file loader.
  32468. *
  32469. * @param {LoadingManager} [manager] - The loading manager.
  32470. */
  32471. constructor( manager ) {
  32472. super( manager );
  32473. /**
  32474. * The expected mime type. Valid values can be found
  32475. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32476. *
  32477. * @type {string}
  32478. */
  32479. this.mimeType = '';
  32480. /**
  32481. * The expected response type.
  32482. *
  32483. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32484. * @default ''
  32485. */
  32486. this.responseType = '';
  32487. /**
  32488. * Used for aborting requests.
  32489. *
  32490. * @private
  32491. * @type {AbortController}
  32492. */
  32493. this._abortController = new AbortController();
  32494. }
  32495. /**
  32496. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32497. *
  32498. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32499. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32500. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32501. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32502. * @return {any|undefined} The cached resource if available.
  32503. */
  32504. load( url, onLoad, onProgress, onError ) {
  32505. if ( url === undefined ) url = '';
  32506. if ( this.path !== undefined ) url = this.path + url;
  32507. url = this.manager.resolveURL( url );
  32508. const cached = Cache.get( `file:${url}` );
  32509. if ( cached !== undefined ) {
  32510. this.manager.itemStart( url );
  32511. setTimeout( () => {
  32512. if ( onLoad ) onLoad( cached );
  32513. this.manager.itemEnd( url );
  32514. }, 0 );
  32515. return cached;
  32516. }
  32517. // Check if request is duplicate
  32518. if ( loading[ url ] !== undefined ) {
  32519. loading[ url ].push( {
  32520. onLoad: onLoad,
  32521. onProgress: onProgress,
  32522. onError: onError
  32523. } );
  32524. return;
  32525. }
  32526. // Initialise array for duplicate requests
  32527. loading[ url ] = [];
  32528. loading[ url ].push( {
  32529. onLoad: onLoad,
  32530. onProgress: onProgress,
  32531. onError: onError,
  32532. } );
  32533. // create request
  32534. const req = new Request( url, {
  32535. headers: new Headers( this.requestHeader ),
  32536. credentials: this.withCredentials ? 'include' : 'same-origin',
  32537. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32538. } );
  32539. // record states ( avoid data race )
  32540. const mimeType = this.mimeType;
  32541. const responseType = this.responseType;
  32542. // start the fetch
  32543. fetch( req )
  32544. .then( response => {
  32545. if ( response.status === 200 || response.status === 0 ) {
  32546. // Some browsers return HTTP Status 0 when using non-http protocol
  32547. // e.g. 'file://' or 'data://'. Handle as success.
  32548. if ( response.status === 0 ) {
  32549. warn( 'FileLoader: HTTP Status 0 received.' );
  32550. }
  32551. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32552. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32553. return response;
  32554. }
  32555. const callbacks = loading[ url ];
  32556. const reader = response.body.getReader();
  32557. // Nginx needs X-File-Size check
  32558. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32559. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32560. const total = contentLength ? parseInt( contentLength ) : 0;
  32561. const lengthComputable = total !== 0;
  32562. let loaded = 0;
  32563. // periodically read data into the new stream tracking while download progress
  32564. const stream = new ReadableStream( {
  32565. start( controller ) {
  32566. readData();
  32567. function readData() {
  32568. reader.read().then( ( { done, value } ) => {
  32569. if ( done ) {
  32570. controller.close();
  32571. } else {
  32572. loaded += value.byteLength;
  32573. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32574. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32575. const callback = callbacks[ i ];
  32576. if ( callback.onProgress ) callback.onProgress( event );
  32577. }
  32578. controller.enqueue( value );
  32579. readData();
  32580. }
  32581. }, ( e ) => {
  32582. controller.error( e );
  32583. } );
  32584. }
  32585. }
  32586. } );
  32587. return new Response( stream );
  32588. } else {
  32589. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32590. }
  32591. } )
  32592. .then( response => {
  32593. switch ( responseType ) {
  32594. case 'arraybuffer':
  32595. return response.arrayBuffer();
  32596. case 'blob':
  32597. return response.blob();
  32598. case 'document':
  32599. return response.text()
  32600. .then( text => {
  32601. const parser = new DOMParser();
  32602. return parser.parseFromString( text, mimeType );
  32603. } );
  32604. case 'json':
  32605. return response.json();
  32606. default:
  32607. if ( mimeType === '' ) {
  32608. return response.text();
  32609. } else {
  32610. // sniff encoding
  32611. const re = /charset="?([^;"\s]*)"?/i;
  32612. const exec = re.exec( mimeType );
  32613. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32614. const decoder = new TextDecoder( label );
  32615. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32616. }
  32617. }
  32618. } )
  32619. .then( data => {
  32620. // Add to cache only on HTTP success, so that we do not cache
  32621. // error response bodies as proper responses to requests.
  32622. Cache.add( `file:${url}`, data );
  32623. const callbacks = loading[ url ];
  32624. delete loading[ url ];
  32625. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32626. const callback = callbacks[ i ];
  32627. if ( callback.onLoad ) callback.onLoad( data );
  32628. }
  32629. } )
  32630. .catch( err => {
  32631. // Abort errors and other errors are handled the same
  32632. const callbacks = loading[ url ];
  32633. if ( callbacks === undefined ) {
  32634. // When onLoad was called and url was deleted in `loading`
  32635. this.manager.itemError( url );
  32636. throw err;
  32637. }
  32638. delete loading[ url ];
  32639. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32640. const callback = callbacks[ i ];
  32641. if ( callback.onError ) callback.onError( err );
  32642. }
  32643. this.manager.itemError( url );
  32644. } )
  32645. .finally( () => {
  32646. this.manager.itemEnd( url );
  32647. } );
  32648. this.manager.itemStart( url );
  32649. }
  32650. /**
  32651. * Sets the expected response type.
  32652. *
  32653. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32654. * @return {FileLoader} A reference to this file loader.
  32655. */
  32656. setResponseType( value ) {
  32657. this.responseType = value;
  32658. return this;
  32659. }
  32660. /**
  32661. * Sets the expected mime type of the loaded file.
  32662. *
  32663. * @param {string} value - The mime type.
  32664. * @return {FileLoader} A reference to this file loader.
  32665. */
  32666. setMimeType( value ) {
  32667. this.mimeType = value;
  32668. return this;
  32669. }
  32670. /**
  32671. * Aborts ongoing fetch requests.
  32672. *
  32673. * @return {FileLoader} A reference to this instance.
  32674. */
  32675. abort() {
  32676. this._abortController.abort();
  32677. this._abortController = new AbortController();
  32678. return this;
  32679. }
  32680. }
  32681. /**
  32682. * Class for loading animation clips in the JSON format. The files are internally
  32683. * loaded via {@link FileLoader}.
  32684. *
  32685. * ```js
  32686. * const loader = new THREE.AnimationLoader();
  32687. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32688. * ```
  32689. *
  32690. * @augments Loader
  32691. */
  32692. class AnimationLoader extends Loader {
  32693. /**
  32694. * Constructs a new animation loader.
  32695. *
  32696. * @param {LoadingManager} [manager] - The loading manager.
  32697. */
  32698. constructor( manager ) {
  32699. super( manager );
  32700. }
  32701. /**
  32702. * Starts loading from the given URL and pass the loaded animations as an array
  32703. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32704. *
  32705. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32706. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32707. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32708. * @param {onErrorCallback} onError - Executed when errors occur.
  32709. */
  32710. load( url, onLoad, onProgress, onError ) {
  32711. const scope = this;
  32712. const loader = new FileLoader( this.manager );
  32713. loader.setPath( this.path );
  32714. loader.setRequestHeader( this.requestHeader );
  32715. loader.setWithCredentials( this.withCredentials );
  32716. loader.load( url, function ( text ) {
  32717. try {
  32718. onLoad( scope.parse( JSON.parse( text ) ) );
  32719. } catch ( e ) {
  32720. if ( onError ) {
  32721. onError( e );
  32722. } else {
  32723. error( e );
  32724. }
  32725. scope.manager.itemError( url );
  32726. }
  32727. }, onProgress, onError );
  32728. }
  32729. /**
  32730. * Parses the given JSON object and returns an array of animation clips.
  32731. *
  32732. * @param {Object} json - The serialized animation clips.
  32733. * @return {Array<AnimationClip>} The parsed animation clips.
  32734. */
  32735. parse( json ) {
  32736. const animations = [];
  32737. for ( let i = 0; i < json.length; i ++ ) {
  32738. const clip = AnimationClip.parse( json[ i ] );
  32739. animations.push( clip );
  32740. }
  32741. return animations;
  32742. }
  32743. }
  32744. /**
  32745. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32746. * Textures are internally loaded via {@link FileLoader}.
  32747. *
  32748. * Derived classes have to implement the `parse()` method which holds the parsing
  32749. * for the respective format.
  32750. *
  32751. * @abstract
  32752. * @augments Loader
  32753. */
  32754. class CompressedTextureLoader extends Loader {
  32755. /**
  32756. * Constructs a new compressed texture loader.
  32757. *
  32758. * @param {LoadingManager} [manager] - The loading manager.
  32759. */
  32760. constructor( manager ) {
  32761. super( manager );
  32762. }
  32763. /**
  32764. * Starts loading from the given URL and passes the loaded compressed texture
  32765. * to the `onLoad()` callback. The method also returns a new texture object which can
  32766. * directly be used for material creation. If you do it this way, the texture
  32767. * may pop up in your scene once the respective loading process is finished.
  32768. *
  32769. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32770. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32771. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32772. * @param {onErrorCallback} onError - Executed when errors occur.
  32773. * @return {CompressedTexture} The compressed texture.
  32774. */
  32775. load( url, onLoad, onProgress, onError ) {
  32776. const scope = this;
  32777. const images = [];
  32778. const texture = new CompressedTexture();
  32779. const loader = new FileLoader( this.manager );
  32780. loader.setPath( this.path );
  32781. loader.setResponseType( 'arraybuffer' );
  32782. loader.setRequestHeader( this.requestHeader );
  32783. loader.setWithCredentials( scope.withCredentials );
  32784. let loaded = 0;
  32785. function loadTexture( i ) {
  32786. loader.load( url[ i ], function ( buffer ) {
  32787. const texDatas = scope.parse( buffer, true );
  32788. images[ i ] = {
  32789. width: texDatas.width,
  32790. height: texDatas.height,
  32791. format: texDatas.format,
  32792. mipmaps: texDatas.mipmaps
  32793. };
  32794. loaded += 1;
  32795. if ( loaded === 6 ) {
  32796. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32797. texture.image = images;
  32798. texture.format = texDatas.format;
  32799. texture.needsUpdate = true;
  32800. if ( onLoad ) onLoad( texture );
  32801. }
  32802. }, onProgress, onError );
  32803. }
  32804. if ( Array.isArray( url ) ) {
  32805. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32806. loadTexture( i );
  32807. }
  32808. } else {
  32809. // compressed cubemap texture stored in a single DDS file
  32810. loader.load( url, function ( buffer ) {
  32811. const texDatas = scope.parse( buffer, true );
  32812. if ( texDatas.isCubemap ) {
  32813. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32814. for ( let f = 0; f < faces; f ++ ) {
  32815. images[ f ] = { mipmaps: [] };
  32816. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32817. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32818. images[ f ].format = texDatas.format;
  32819. images[ f ].width = texDatas.width;
  32820. images[ f ].height = texDatas.height;
  32821. }
  32822. }
  32823. texture.image = images;
  32824. } else {
  32825. texture.image.width = texDatas.width;
  32826. texture.image.height = texDatas.height;
  32827. texture.mipmaps = texDatas.mipmaps;
  32828. }
  32829. if ( texDatas.mipmapCount === 1 ) {
  32830. texture.minFilter = LinearFilter;
  32831. }
  32832. texture.format = texDatas.format;
  32833. texture.needsUpdate = true;
  32834. if ( onLoad ) onLoad( texture );
  32835. }, onProgress, onError );
  32836. }
  32837. return texture;
  32838. }
  32839. }
  32840. const _loading = new WeakMap();
  32841. /**
  32842. * A loader for loading images. The class loads images with the HTML `Image` API.
  32843. *
  32844. * ```js
  32845. * const loader = new THREE.ImageLoader();
  32846. * const image = await loader.loadAsync( 'image.png' );
  32847. * ```
  32848. * Please note that `ImageLoader` has dropped support for progress
  32849. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32850. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32851. *
  32852. * @augments Loader
  32853. */
  32854. class ImageLoader extends Loader {
  32855. /**
  32856. * Constructs a new image loader.
  32857. *
  32858. * @param {LoadingManager} [manager] - The loading manager.
  32859. */
  32860. constructor( manager ) {
  32861. super( manager );
  32862. }
  32863. /**
  32864. * Starts loading from the given URL and passes the loaded image
  32865. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32866. * directly be used for texture creation. If you do it this way, the texture
  32867. * may pop up in your scene once the respective loading process is finished.
  32868. *
  32869. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32870. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32871. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32872. * @param {onErrorCallback} onError - Executed when errors occur.
  32873. * @return {Image} The image.
  32874. */
  32875. load( url, onLoad, onProgress, onError ) {
  32876. if ( this.path !== undefined ) url = this.path + url;
  32877. url = this.manager.resolveURL( url );
  32878. const scope = this;
  32879. const cached = Cache.get( `image:${url}` );
  32880. if ( cached !== undefined ) {
  32881. if ( cached.complete === true ) {
  32882. scope.manager.itemStart( url );
  32883. setTimeout( function () {
  32884. if ( onLoad ) onLoad( cached );
  32885. scope.manager.itemEnd( url );
  32886. }, 0 );
  32887. } else {
  32888. let arr = _loading.get( cached );
  32889. if ( arr === undefined ) {
  32890. arr = [];
  32891. _loading.set( cached, arr );
  32892. }
  32893. arr.push( { onLoad, onError } );
  32894. }
  32895. return cached;
  32896. }
  32897. const image = createElementNS( 'img' );
  32898. function onImageLoad() {
  32899. removeEventListeners();
  32900. if ( onLoad ) onLoad( this );
  32901. //
  32902. const callbacks = _loading.get( this ) || [];
  32903. for ( let i = 0; i < callbacks.length; i ++ ) {
  32904. const callback = callbacks[ i ];
  32905. if ( callback.onLoad ) callback.onLoad( this );
  32906. }
  32907. _loading.delete( this );
  32908. scope.manager.itemEnd( url );
  32909. }
  32910. function onImageError( event ) {
  32911. removeEventListeners();
  32912. if ( onError ) onError( event );
  32913. Cache.remove( `image:${url}` );
  32914. //
  32915. const callbacks = _loading.get( this ) || [];
  32916. for ( let i = 0; i < callbacks.length; i ++ ) {
  32917. const callback = callbacks[ i ];
  32918. if ( callback.onError ) callback.onError( event );
  32919. }
  32920. _loading.delete( this );
  32921. scope.manager.itemError( url );
  32922. scope.manager.itemEnd( url );
  32923. }
  32924. function removeEventListeners() {
  32925. image.removeEventListener( 'load', onImageLoad, false );
  32926. image.removeEventListener( 'error', onImageError, false );
  32927. }
  32928. image.addEventListener( 'load', onImageLoad, false );
  32929. image.addEventListener( 'error', onImageError, false );
  32930. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32931. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32932. }
  32933. Cache.add( `image:${url}`, image );
  32934. scope.manager.itemStart( url );
  32935. image.src = url;
  32936. return image;
  32937. }
  32938. }
  32939. /**
  32940. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32941. *
  32942. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32943. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32944. * like vertical and horizontal cross, column and row layouts are not supported.
  32945. *
  32946. * Note that, by convention, cube maps are specified in a coordinate system
  32947. * in which positive-x is to the right when looking up the positive-z axis --
  32948. * in other words, using a left-handed coordinate system. Since three.js uses
  32949. * a right-handed coordinate system, environment maps used in three.js will
  32950. * have pos-x and neg-x swapped.
  32951. *
  32952. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32953. * is set to `SRGBColorSpace` by default.
  32954. *
  32955. * ```js
  32956. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32957. * const cubeTexture = await loader.loadAsync( [
  32958. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32959. * ] );
  32960. * scene.background = cubeTexture;
  32961. * ```
  32962. *
  32963. * @augments Loader
  32964. */
  32965. class CubeTextureLoader extends Loader {
  32966. /**
  32967. * Constructs a new cube texture loader.
  32968. *
  32969. * @param {LoadingManager} [manager] - The loading manager.
  32970. */
  32971. constructor( manager ) {
  32972. super( manager );
  32973. }
  32974. /**
  32975. * Starts loading from the given URL and pass the fully loaded cube texture
  32976. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32977. * directly be used for material creation. If you do it this way, the cube texture
  32978. * may pop up in your scene once the respective loading process is finished.
  32979. *
  32980. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32981. * cube texture. The urls should be specified in the following order: pos-x,
  32982. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32983. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32984. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32985. * @param {onErrorCallback} onError - Executed when errors occur.
  32986. * @return {CubeTexture} The cube texture.
  32987. */
  32988. load( urls, onLoad, onProgress, onError ) {
  32989. const texture = new CubeTexture();
  32990. texture.colorSpace = SRGBColorSpace;
  32991. const loader = new ImageLoader( this.manager );
  32992. loader.setCrossOrigin( this.crossOrigin );
  32993. loader.setPath( this.path );
  32994. let loaded = 0;
  32995. function loadTexture( i ) {
  32996. loader.load( urls[ i ], function ( image ) {
  32997. texture.images[ i ] = image;
  32998. loaded ++;
  32999. if ( loaded === 6 ) {
  33000. texture.needsUpdate = true;
  33001. if ( onLoad ) onLoad( texture );
  33002. }
  33003. }, undefined, onError );
  33004. }
  33005. for ( let i = 0; i < urls.length; ++ i ) {
  33006. loadTexture( i );
  33007. }
  33008. return texture;
  33009. }
  33010. }
  33011. /**
  33012. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33013. * Textures are internally loaded via {@link FileLoader}.
  33014. *
  33015. * Derived classes have to implement the `parse()` method which holds the parsing
  33016. * for the respective format.
  33017. *
  33018. * @abstract
  33019. * @augments Loader
  33020. */
  33021. class DataTextureLoader extends Loader {
  33022. /**
  33023. * Constructs a new data texture loader.
  33024. *
  33025. * @param {LoadingManager} [manager] - The loading manager.
  33026. */
  33027. constructor( manager ) {
  33028. super( manager );
  33029. }
  33030. /**
  33031. * Starts loading from the given URL and passes the loaded data texture
  33032. * to the `onLoad()` callback. The method also returns a new texture object which can
  33033. * directly be used for material creation. If you do it this way, the texture
  33034. * may pop up in your scene once the respective loading process is finished.
  33035. *
  33036. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33037. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33038. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33039. * @param {onErrorCallback} onError - Executed when errors occur.
  33040. * @return {DataTexture} The data texture.
  33041. */
  33042. load( url, onLoad, onProgress, onError ) {
  33043. const scope = this;
  33044. const texture = new DataTexture();
  33045. const loader = new FileLoader( this.manager );
  33046. loader.setResponseType( 'arraybuffer' );
  33047. loader.setRequestHeader( this.requestHeader );
  33048. loader.setPath( this.path );
  33049. loader.setWithCredentials( scope.withCredentials );
  33050. loader.load( url, function ( buffer ) {
  33051. let texData;
  33052. try {
  33053. texData = scope.parse( buffer );
  33054. } catch ( error ) {
  33055. if ( onError !== undefined ) {
  33056. onError( error );
  33057. } else {
  33058. error( error );
  33059. return;
  33060. }
  33061. }
  33062. if ( texData.image !== undefined ) {
  33063. texture.image = texData.image;
  33064. } else if ( texData.data !== undefined ) {
  33065. texture.image.width = texData.width;
  33066. texture.image.height = texData.height;
  33067. texture.image.data = texData.data;
  33068. }
  33069. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33070. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33071. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33072. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33073. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33074. if ( texData.colorSpace !== undefined ) {
  33075. texture.colorSpace = texData.colorSpace;
  33076. }
  33077. if ( texData.flipY !== undefined ) {
  33078. texture.flipY = texData.flipY;
  33079. }
  33080. if ( texData.format !== undefined ) {
  33081. texture.format = texData.format;
  33082. }
  33083. if ( texData.type !== undefined ) {
  33084. texture.type = texData.type;
  33085. }
  33086. if ( texData.mipmaps !== undefined ) {
  33087. texture.mipmaps = texData.mipmaps;
  33088. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33089. }
  33090. if ( texData.mipmapCount === 1 ) {
  33091. texture.minFilter = LinearFilter;
  33092. }
  33093. if ( texData.generateMipmaps !== undefined ) {
  33094. texture.generateMipmaps = texData.generateMipmaps;
  33095. }
  33096. texture.needsUpdate = true;
  33097. if ( onLoad ) onLoad( texture, texData );
  33098. }, onProgress, onError );
  33099. return texture;
  33100. }
  33101. }
  33102. /**
  33103. * Class for loading textures. Images are internally
  33104. * loaded via {@link ImageLoader}.
  33105. *
  33106. * ```js
  33107. * const loader = new THREE.TextureLoader();
  33108. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33109. *
  33110. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33111. * ```
  33112. * Please note that `TextureLoader` has dropped support for progress
  33113. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33114. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33115. *
  33116. * @augments Loader
  33117. */
  33118. class TextureLoader extends Loader {
  33119. /**
  33120. * Constructs a new texture loader.
  33121. *
  33122. * @param {LoadingManager} [manager] - The loading manager.
  33123. */
  33124. constructor( manager ) {
  33125. super( manager );
  33126. }
  33127. /**
  33128. * Starts loading from the given URL and pass the fully loaded texture
  33129. * to the `onLoad()` callback. The method also returns a new texture object which can
  33130. * directly be used for material creation. If you do it this way, the texture
  33131. * may pop up in your scene once the respective loading process is finished.
  33132. *
  33133. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33134. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33135. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33136. * @param {onErrorCallback} onError - Executed when errors occur.
  33137. * @return {Texture} The texture.
  33138. */
  33139. load( url, onLoad, onProgress, onError ) {
  33140. const texture = new Texture();
  33141. const loader = new ImageLoader( this.manager );
  33142. loader.setCrossOrigin( this.crossOrigin );
  33143. loader.setPath( this.path );
  33144. loader.load( url, function ( image ) {
  33145. texture.image = image;
  33146. texture.needsUpdate = true;
  33147. if ( onLoad !== undefined ) {
  33148. onLoad( texture );
  33149. }
  33150. }, onProgress, onError );
  33151. return texture;
  33152. }
  33153. }
  33154. /**
  33155. * Abstract base class for lights - all other light types inherit the
  33156. * properties and methods described here.
  33157. *
  33158. * @abstract
  33159. * @augments Object3D
  33160. */
  33161. class Light extends Object3D {
  33162. /**
  33163. * Constructs a new light.
  33164. *
  33165. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33166. * @param {number} [intensity=1] - The light's strength/intensity.
  33167. */
  33168. constructor( color, intensity = 1 ) {
  33169. super();
  33170. /**
  33171. * This flag can be used for type testing.
  33172. *
  33173. * @type {boolean}
  33174. * @readonly
  33175. * @default true
  33176. */
  33177. this.isLight = true;
  33178. this.type = 'Light';
  33179. /**
  33180. * The light's color.
  33181. *
  33182. * @type {Color}
  33183. */
  33184. this.color = new Color( color );
  33185. /**
  33186. * The light's intensity.
  33187. *
  33188. * @type {number}
  33189. * @default 1
  33190. */
  33191. this.intensity = intensity;
  33192. }
  33193. /**
  33194. * Frees the GPU-related resources allocated by this instance. Call this
  33195. * method whenever this instance is no longer used in your app.
  33196. */
  33197. dispose() {
  33198. this.dispatchEvent( { type: 'dispose' } );
  33199. }
  33200. copy( source, recursive ) {
  33201. super.copy( source, recursive );
  33202. this.color.copy( source.color );
  33203. this.intensity = source.intensity;
  33204. return this;
  33205. }
  33206. toJSON( meta ) {
  33207. const data = super.toJSON( meta );
  33208. data.object.color = this.color.getHex();
  33209. data.object.intensity = this.intensity;
  33210. return data;
  33211. }
  33212. }
  33213. /**
  33214. * A light source positioned directly above the scene, with color fading from
  33215. * the sky color to the ground color.
  33216. *
  33217. * This light cannot be used to cast shadows.
  33218. *
  33219. * ```js
  33220. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33221. * scene.add( light );
  33222. * ```
  33223. *
  33224. * @augments Light
  33225. */
  33226. class HemisphereLight extends Light {
  33227. /**
  33228. * Constructs a new hemisphere light.
  33229. *
  33230. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33231. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33232. * @param {number} [intensity=1] - The light's strength/intensity.
  33233. */
  33234. constructor( skyColor, groundColor, intensity ) {
  33235. super( skyColor, intensity );
  33236. /**
  33237. * This flag can be used for type testing.
  33238. *
  33239. * @type {boolean}
  33240. * @readonly
  33241. * @default true
  33242. */
  33243. this.isHemisphereLight = true;
  33244. this.type = 'HemisphereLight';
  33245. this.position.copy( Object3D.DEFAULT_UP );
  33246. this.updateMatrix();
  33247. /**
  33248. * The light's ground color.
  33249. *
  33250. * @type {Color}
  33251. */
  33252. this.groundColor = new Color( groundColor );
  33253. }
  33254. copy( source, recursive ) {
  33255. super.copy( source, recursive );
  33256. this.groundColor.copy( source.groundColor );
  33257. return this;
  33258. }
  33259. toJSON( meta ) {
  33260. const data = super.toJSON( meta );
  33261. data.object.groundColor = this.groundColor.getHex();
  33262. return data;
  33263. }
  33264. }
  33265. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33266. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33267. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33268. /**
  33269. * Abstract base class for light shadow classes. These classes
  33270. * represent the shadow configuration for different light types.
  33271. *
  33272. * @abstract
  33273. */
  33274. class LightShadow {
  33275. /**
  33276. * Constructs a new light shadow.
  33277. *
  33278. * @param {Camera} camera - The light's view of the world.
  33279. */
  33280. constructor( camera ) {
  33281. /**
  33282. * The light's view of the world.
  33283. *
  33284. * @type {Camera}
  33285. */
  33286. this.camera = camera;
  33287. /**
  33288. * The intensity of the shadow. The default is `1`.
  33289. * Valid values are in the range `[0, 1]`.
  33290. *
  33291. * @type {number}
  33292. * @default 1
  33293. */
  33294. this.intensity = 1;
  33295. /**
  33296. * Shadow map bias, how much to add or subtract from the normalized depth
  33297. * when deciding whether a surface is in shadow.
  33298. *
  33299. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33300. * may help reduce artifacts in shadows.
  33301. *
  33302. * @type {number}
  33303. * @default 0
  33304. */
  33305. this.bias = 0;
  33306. /**
  33307. * Defines how much the position used to query the shadow map is offset along
  33308. * the object normal. The default is `0`. Increasing this value can be used to
  33309. * reduce shadow acne especially in large scenes where light shines onto
  33310. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33311. *
  33312. * @type {number}
  33313. * @default 0
  33314. */
  33315. this.normalBias = 0;
  33316. /**
  33317. * Setting this to values greater than 1 will blur the edges of the shadow.
  33318. * High values will cause unwanted banding effects in the shadows - a greater
  33319. * map size will allow for a higher value to be used here before these effects
  33320. * become visible.
  33321. *
  33322. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33323. *
  33324. * @type {number}
  33325. * @default 1
  33326. */
  33327. this.radius = 1;
  33328. /**
  33329. * The amount of samples to use when blurring a VSM shadow map.
  33330. *
  33331. * @type {number}
  33332. * @default 8
  33333. */
  33334. this.blurSamples = 8;
  33335. /**
  33336. * Defines the width and height of the shadow map. Higher values give better quality
  33337. * shadows at the cost of computation time. Values must be powers of two.
  33338. *
  33339. * @type {Vector2}
  33340. * @default (512,512)
  33341. */
  33342. this.mapSize = new Vector2( 512, 512 );
  33343. /**
  33344. * The type of shadow texture. The default is `UnsignedByteType`.
  33345. *
  33346. * @type {number}
  33347. * @default UnsignedByteType
  33348. */
  33349. this.mapType = UnsignedByteType;
  33350. /**
  33351. * The depth map generated using the internal camera; a location beyond a
  33352. * pixel's depth is in shadow. Computed internally during rendering.
  33353. *
  33354. * @type {?RenderTarget}
  33355. * @default null
  33356. */
  33357. this.map = null;
  33358. /**
  33359. * The distribution map generated using the internal camera; an occlusion is
  33360. * calculated based on the distribution of depths. Computed internally during
  33361. * rendering.
  33362. *
  33363. * @type {?RenderTarget}
  33364. * @default null
  33365. */
  33366. this.mapPass = null;
  33367. /**
  33368. * Model to shadow camera space, to compute location and depth in shadow map.
  33369. * This is computed internally during rendering.
  33370. *
  33371. * @type {Matrix4}
  33372. */
  33373. this.matrix = new Matrix4();
  33374. /**
  33375. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33376. * lighting / shadows, you may set this to `false`.
  33377. *
  33378. * @type {boolean}
  33379. * @default true
  33380. */
  33381. this.autoUpdate = true;
  33382. /**
  33383. * When set to `true`, shadow maps will be updated in the next `render` call.
  33384. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33385. * set this property to `true` and then make a render call to update the light's shadow.
  33386. *
  33387. * @type {boolean}
  33388. * @default false
  33389. */
  33390. this.needsUpdate = false;
  33391. this._frustum = new Frustum();
  33392. this._frameExtents = new Vector2( 1, 1 );
  33393. this._viewportCount = 1;
  33394. this._viewports = [
  33395. new Vector4( 0, 0, 1, 1 )
  33396. ];
  33397. }
  33398. /**
  33399. * Used internally by the renderer to get the number of viewports that need
  33400. * to be rendered for this shadow.
  33401. *
  33402. * @return {number} The viewport count.
  33403. */
  33404. getViewportCount() {
  33405. return this._viewportCount;
  33406. }
  33407. /**
  33408. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33409. *
  33410. * @return {Frustum} The shadow camera frustum.
  33411. */
  33412. getFrustum() {
  33413. return this._frustum;
  33414. }
  33415. /**
  33416. * Update the matrices for the camera and shadow, used internally by the renderer.
  33417. *
  33418. * @param {Light} light - The light for which the shadow is being rendered.
  33419. */
  33420. updateMatrices( light ) {
  33421. const shadowCamera = this.camera;
  33422. const shadowMatrix = this.matrix;
  33423. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33424. shadowCamera.position.copy( _lightPositionWorld$1 );
  33425. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33426. shadowCamera.lookAt( _lookTarget$1 );
  33427. shadowCamera.updateMatrixWorld();
  33428. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33429. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33430. if ( shadowCamera.reversedDepth ) {
  33431. shadowMatrix.set(
  33432. 0.5, 0.0, 0.0, 0.5,
  33433. 0.0, 0.5, 0.0, 0.5,
  33434. 0.0, 0.0, 1.0, 0.0,
  33435. 0.0, 0.0, 0.0, 1.0
  33436. );
  33437. } else {
  33438. shadowMatrix.set(
  33439. 0.5, 0.0, 0.0, 0.5,
  33440. 0.0, 0.5, 0.0, 0.5,
  33441. 0.0, 0.0, 0.5, 0.5,
  33442. 0.0, 0.0, 0.0, 1.0
  33443. );
  33444. }
  33445. shadowMatrix.multiply( _projScreenMatrix$1 );
  33446. }
  33447. /**
  33448. * Returns a viewport definition for the given viewport index.
  33449. *
  33450. * @param {number} viewportIndex - The viewport index.
  33451. * @return {Vector4} The viewport.
  33452. */
  33453. getViewport( viewportIndex ) {
  33454. return this._viewports[ viewportIndex ];
  33455. }
  33456. /**
  33457. * Returns the frame extends.
  33458. *
  33459. * @return {Vector2} The frame extends.
  33460. */
  33461. getFrameExtents() {
  33462. return this._frameExtents;
  33463. }
  33464. /**
  33465. * Frees the GPU-related resources allocated by this instance. Call this
  33466. * method whenever this instance is no longer used in your app.
  33467. */
  33468. dispose() {
  33469. if ( this.map ) {
  33470. this.map.dispose();
  33471. }
  33472. if ( this.mapPass ) {
  33473. this.mapPass.dispose();
  33474. }
  33475. }
  33476. /**
  33477. * Copies the values of the given light shadow instance to this instance.
  33478. *
  33479. * @param {LightShadow} source - The light shadow to copy.
  33480. * @return {LightShadow} A reference to this light shadow instance.
  33481. */
  33482. copy( source ) {
  33483. this.camera = source.camera.clone();
  33484. this.intensity = source.intensity;
  33485. this.bias = source.bias;
  33486. this.radius = source.radius;
  33487. this.autoUpdate = source.autoUpdate;
  33488. this.needsUpdate = source.needsUpdate;
  33489. this.normalBias = source.normalBias;
  33490. this.blurSamples = source.blurSamples;
  33491. this.mapSize.copy( source.mapSize );
  33492. return this;
  33493. }
  33494. /**
  33495. * Returns a new light shadow instance with copied values from this instance.
  33496. *
  33497. * @return {LightShadow} A clone of this instance.
  33498. */
  33499. clone() {
  33500. return new this.constructor().copy( this );
  33501. }
  33502. /**
  33503. * Serializes the light shadow into JSON.
  33504. *
  33505. * @return {Object} A JSON object representing the serialized light shadow.
  33506. * @see {@link ObjectLoader#parse}
  33507. */
  33508. toJSON() {
  33509. const object = {};
  33510. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33511. if ( this.bias !== 0 ) object.bias = this.bias;
  33512. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33513. if ( this.radius !== 1 ) object.radius = this.radius;
  33514. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33515. object.camera = this.camera.toJSON( false ).object;
  33516. delete object.camera.matrix;
  33517. return object;
  33518. }
  33519. }
  33520. /**
  33521. * Represents the shadow configuration of directional lights.
  33522. *
  33523. * @augments LightShadow
  33524. */
  33525. class SpotLightShadow extends LightShadow {
  33526. /**
  33527. * Constructs a new spot light shadow.
  33528. */
  33529. constructor() {
  33530. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33531. /**
  33532. * This flag can be used for type testing.
  33533. *
  33534. * @type {boolean}
  33535. * @readonly
  33536. * @default true
  33537. */
  33538. this.isSpotLightShadow = true;
  33539. /**
  33540. * Used to focus the shadow camera. The camera's field of view is set as a
  33541. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33542. *
  33543. * @type {number}
  33544. * @default 1
  33545. */
  33546. this.focus = 1;
  33547. /**
  33548. * Texture aspect ratio.
  33549. *
  33550. * @type {number}
  33551. * @default 1
  33552. */
  33553. this.aspect = 1;
  33554. }
  33555. updateMatrices( light ) {
  33556. const camera = this.camera;
  33557. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33558. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33559. const far = light.distance || camera.far;
  33560. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33561. camera.fov = fov;
  33562. camera.aspect = aspect;
  33563. camera.far = far;
  33564. camera.updateProjectionMatrix();
  33565. }
  33566. super.updateMatrices( light );
  33567. }
  33568. copy( source ) {
  33569. super.copy( source );
  33570. this.focus = source.focus;
  33571. return this;
  33572. }
  33573. }
  33574. /**
  33575. * This light gets emitted from a single point in one direction, along a cone
  33576. * that increases in size the further from the light it gets.
  33577. *
  33578. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33579. *
  33580. * ```js
  33581. * // white spotlight shining from the side, modulated by a texture
  33582. * const spotLight = new THREE.SpotLight( 0xffffff );
  33583. * spotLight.position.set( 100, 1000, 100 );
  33584. * spotLight.map = new THREE.TextureLoader().load( url );
  33585. *
  33586. * spotLight.castShadow = true;
  33587. * spotLight.shadow.mapSize.width = 1024;
  33588. * spotLight.shadow.mapSize.height = 1024;
  33589. * spotLight.shadow.camera.near = 500;
  33590. * spotLight.shadow.camera.far = 4000;
  33591. * spotLight.shadow.camera.fov = 30;s
  33592. * ```
  33593. *
  33594. * @augments Light
  33595. */
  33596. class SpotLight extends Light {
  33597. /**
  33598. * Constructs a new spot light.
  33599. *
  33600. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33601. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33602. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33603. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33604. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33605. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33606. */
  33607. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33608. super( color, intensity );
  33609. /**
  33610. * This flag can be used for type testing.
  33611. *
  33612. * @type {boolean}
  33613. * @readonly
  33614. * @default true
  33615. */
  33616. this.isSpotLight = true;
  33617. this.type = 'SpotLight';
  33618. this.position.copy( Object3D.DEFAULT_UP );
  33619. this.updateMatrix();
  33620. /**
  33621. * The spot light points from its position to the
  33622. * target's position.
  33623. *
  33624. * For the target's position to be changed to anything other
  33625. * than the default, it must be added to the scene.
  33626. *
  33627. * It is also possible to set the target to be another 3D object
  33628. * in the scene. The light will now track the target object.
  33629. *
  33630. * @type {Object3D}
  33631. */
  33632. this.target = new Object3D();
  33633. /**
  33634. * Maximum range of the light. `0` means no limit.
  33635. *
  33636. * @type {number}
  33637. * @default 0
  33638. */
  33639. this.distance = distance;
  33640. /**
  33641. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33642. *
  33643. * @type {number}
  33644. * @default Math.PI/3
  33645. */
  33646. this.angle = angle;
  33647. /**
  33648. * Percent of the spotlight cone that is attenuated due to penumbra.
  33649. * Value range is `[0,1]`.
  33650. *
  33651. * @type {number}
  33652. * @default 0
  33653. */
  33654. this.penumbra = penumbra;
  33655. /**
  33656. * The amount the light dims along the distance of the light. In context of
  33657. * physically-correct rendering the default value should not be changed.
  33658. *
  33659. * @type {number}
  33660. * @default 2
  33661. */
  33662. this.decay = decay;
  33663. /**
  33664. * A texture used to modulate the color of the light. The spot light
  33665. * color is mixed with the RGB value of this texture, with a ratio
  33666. * corresponding to its alpha value. The cookie-like masking effect is
  33667. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33668. *
  33669. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33670. *
  33671. * @type {?Texture}
  33672. * @default null
  33673. */
  33674. this.map = null;
  33675. /**
  33676. * This property holds the light's shadow configuration.
  33677. *
  33678. * @type {SpotLightShadow}
  33679. */
  33680. this.shadow = new SpotLightShadow();
  33681. }
  33682. /**
  33683. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33684. * Changing the power will also change the light's intensity.
  33685. *
  33686. * @type {number}
  33687. */
  33688. get power() {
  33689. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33690. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33691. return this.intensity * Math.PI;
  33692. }
  33693. set power( power ) {
  33694. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33695. this.intensity = power / Math.PI;
  33696. }
  33697. dispose() {
  33698. super.dispose();
  33699. this.shadow.dispose();
  33700. }
  33701. copy( source, recursive ) {
  33702. super.copy( source, recursive );
  33703. this.distance = source.distance;
  33704. this.angle = source.angle;
  33705. this.penumbra = source.penumbra;
  33706. this.decay = source.decay;
  33707. this.target = source.target.clone();
  33708. this.map = source.map;
  33709. this.shadow = source.shadow.clone();
  33710. return this;
  33711. }
  33712. toJSON( meta ) {
  33713. const data = super.toJSON( meta );
  33714. data.object.distance = this.distance;
  33715. data.object.angle = this.angle;
  33716. data.object.decay = this.decay;
  33717. data.object.penumbra = this.penumbra;
  33718. data.object.target = this.target.uuid;
  33719. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33720. data.object.shadow = this.shadow.toJSON();
  33721. return data;
  33722. }
  33723. }
  33724. /**
  33725. * Represents the shadow configuration of point lights.
  33726. *
  33727. * @augments LightShadow
  33728. */
  33729. class PointLightShadow extends LightShadow {
  33730. /**
  33731. * Constructs a new point light shadow.
  33732. */
  33733. constructor() {
  33734. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33735. /**
  33736. * This flag can be used for type testing.
  33737. *
  33738. * @type {boolean}
  33739. * @readonly
  33740. * @default true
  33741. */
  33742. this.isPointLightShadow = true;
  33743. }
  33744. }
  33745. /**
  33746. * A light that gets emitted from a single point in all directions. A common
  33747. * use case for this is to replicate the light emitted from a bare
  33748. * lightbulb.
  33749. *
  33750. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33751. *
  33752. * ```js
  33753. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33754. * light.position.set( 50, 50, 50 );
  33755. * scene.add( light );
  33756. * ```
  33757. *
  33758. * @augments Light
  33759. */
  33760. class PointLight extends Light {
  33761. /**
  33762. * Constructs a new point light.
  33763. *
  33764. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33765. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33766. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33767. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33768. */
  33769. constructor( color, intensity, distance = 0, decay = 2 ) {
  33770. super( color, intensity );
  33771. /**
  33772. * This flag can be used for type testing.
  33773. *
  33774. * @type {boolean}
  33775. * @readonly
  33776. * @default true
  33777. */
  33778. this.isPointLight = true;
  33779. this.type = 'PointLight';
  33780. /**
  33781. * When distance is zero, light will attenuate according to inverse-square
  33782. * law to infinite distance. When distance is non-zero, light will attenuate
  33783. * according to inverse-square law until near the distance cutoff, where it
  33784. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33785. * physically correct.
  33786. *
  33787. * @type {number}
  33788. * @default 0
  33789. */
  33790. this.distance = distance;
  33791. /**
  33792. * The amount the light dims along the distance of the light. In context of
  33793. * physically-correct rendering the default value should not be changed.
  33794. *
  33795. * @type {number}
  33796. * @default 2
  33797. */
  33798. this.decay = decay;
  33799. /**
  33800. * This property holds the light's shadow configuration.
  33801. *
  33802. * @type {PointLightShadow}
  33803. */
  33804. this.shadow = new PointLightShadow();
  33805. }
  33806. /**
  33807. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33808. * Changing the power will also change the light's intensity.
  33809. *
  33810. * @type {number}
  33811. */
  33812. get power() {
  33813. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33814. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33815. return this.intensity * 4 * Math.PI;
  33816. }
  33817. set power( power ) {
  33818. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33819. this.intensity = power / ( 4 * Math.PI );
  33820. }
  33821. dispose() {
  33822. super.dispose();
  33823. this.shadow.dispose();
  33824. }
  33825. copy( source, recursive ) {
  33826. super.copy( source, recursive );
  33827. this.distance = source.distance;
  33828. this.decay = source.decay;
  33829. this.shadow = source.shadow.clone();
  33830. return this;
  33831. }
  33832. toJSON( meta ) {
  33833. const data = super.toJSON( meta );
  33834. data.object.distance = this.distance;
  33835. data.object.decay = this.decay;
  33836. data.object.shadow = this.shadow.toJSON();
  33837. return data;
  33838. }
  33839. }
  33840. /**
  33841. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33842. *
  33843. * In this projection mode, an object's size in the rendered image stays
  33844. * constant regardless of its distance from the camera. This can be useful
  33845. * for rendering 2D scenes and UI elements, amongst other things.
  33846. *
  33847. * ```js
  33848. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33849. * scene.add( camera );
  33850. * ```
  33851. *
  33852. * @augments Camera
  33853. */
  33854. class OrthographicCamera extends Camera {
  33855. /**
  33856. * Constructs a new orthographic camera.
  33857. *
  33858. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33859. * @param {number} [right=1] - The right plane of the camera's frustum.
  33860. * @param {number} [top=1] - The top plane of the camera's frustum.
  33861. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33862. * @param {number} [near=0.1] - The camera's near plane.
  33863. * @param {number} [far=2000] - The camera's far plane.
  33864. */
  33865. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33866. super();
  33867. /**
  33868. * This flag can be used for type testing.
  33869. *
  33870. * @type {boolean}
  33871. * @readonly
  33872. * @default true
  33873. */
  33874. this.isOrthographicCamera = true;
  33875. this.type = 'OrthographicCamera';
  33876. /**
  33877. * The zoom factor of the camera.
  33878. *
  33879. * @type {number}
  33880. * @default 1
  33881. */
  33882. this.zoom = 1;
  33883. /**
  33884. * Represents the frustum window specification. This property should not be edited
  33885. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33886. *
  33887. * @type {?Object}
  33888. * @default null
  33889. */
  33890. this.view = null;
  33891. /**
  33892. * The left plane of the camera's frustum.
  33893. *
  33894. * @type {number}
  33895. * @default -1
  33896. */
  33897. this.left = left;
  33898. /**
  33899. * The right plane of the camera's frustum.
  33900. *
  33901. * @type {number}
  33902. * @default 1
  33903. */
  33904. this.right = right;
  33905. /**
  33906. * The top plane of the camera's frustum.
  33907. *
  33908. * @type {number}
  33909. * @default 1
  33910. */
  33911. this.top = top;
  33912. /**
  33913. * The bottom plane of the camera's frustum.
  33914. *
  33915. * @type {number}
  33916. * @default -1
  33917. */
  33918. this.bottom = bottom;
  33919. /**
  33920. * The camera's near plane. The valid range is greater than `0`
  33921. * and less than the current value of {@link OrthographicCamera#far}.
  33922. *
  33923. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33924. * valid value for an orthographic camera's near plane.
  33925. *
  33926. * @type {number}
  33927. * @default 0.1
  33928. */
  33929. this.near = near;
  33930. /**
  33931. * The camera's far plane. Must be greater than the
  33932. * current value of {@link OrthographicCamera#near}.
  33933. *
  33934. * @type {number}
  33935. * @default 2000
  33936. */
  33937. this.far = far;
  33938. this.updateProjectionMatrix();
  33939. }
  33940. copy( source, recursive ) {
  33941. super.copy( source, recursive );
  33942. this.left = source.left;
  33943. this.right = source.right;
  33944. this.top = source.top;
  33945. this.bottom = source.bottom;
  33946. this.near = source.near;
  33947. this.far = source.far;
  33948. this.zoom = source.zoom;
  33949. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33950. return this;
  33951. }
  33952. /**
  33953. * Sets an offset in a larger frustum. This is useful for multi-window or
  33954. * multi-monitor/multi-machine setups.
  33955. *
  33956. * @param {number} fullWidth - The full width of multiview setup.
  33957. * @param {number} fullHeight - The full height of multiview setup.
  33958. * @param {number} x - The horizontal offset of the subcamera.
  33959. * @param {number} y - The vertical offset of the subcamera.
  33960. * @param {number} width - The width of subcamera.
  33961. * @param {number} height - The height of subcamera.
  33962. * @see {@link PerspectiveCamera#setViewOffset}
  33963. */
  33964. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33965. if ( this.view === null ) {
  33966. this.view = {
  33967. enabled: true,
  33968. fullWidth: 1,
  33969. fullHeight: 1,
  33970. offsetX: 0,
  33971. offsetY: 0,
  33972. width: 1,
  33973. height: 1
  33974. };
  33975. }
  33976. this.view.enabled = true;
  33977. this.view.fullWidth = fullWidth;
  33978. this.view.fullHeight = fullHeight;
  33979. this.view.offsetX = x;
  33980. this.view.offsetY = y;
  33981. this.view.width = width;
  33982. this.view.height = height;
  33983. this.updateProjectionMatrix();
  33984. }
  33985. /**
  33986. * Removes the view offset from the projection matrix.
  33987. */
  33988. clearViewOffset() {
  33989. if ( this.view !== null ) {
  33990. this.view.enabled = false;
  33991. }
  33992. this.updateProjectionMatrix();
  33993. }
  33994. /**
  33995. * Updates the camera's projection matrix. Must be called after any change of
  33996. * camera properties.
  33997. */
  33998. updateProjectionMatrix() {
  33999. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34000. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34001. const cx = ( this.right + this.left ) / 2;
  34002. const cy = ( this.top + this.bottom ) / 2;
  34003. let left = cx - dx;
  34004. let right = cx + dx;
  34005. let top = cy + dy;
  34006. let bottom = cy - dy;
  34007. if ( this.view !== null && this.view.enabled ) {
  34008. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34009. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34010. left += scaleW * this.view.offsetX;
  34011. right = left + scaleW * this.view.width;
  34012. top -= scaleH * this.view.offsetY;
  34013. bottom = top - scaleH * this.view.height;
  34014. }
  34015. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34016. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34017. }
  34018. toJSON( meta ) {
  34019. const data = super.toJSON( meta );
  34020. data.object.zoom = this.zoom;
  34021. data.object.left = this.left;
  34022. data.object.right = this.right;
  34023. data.object.top = this.top;
  34024. data.object.bottom = this.bottom;
  34025. data.object.near = this.near;
  34026. data.object.far = this.far;
  34027. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34028. return data;
  34029. }
  34030. }
  34031. /**
  34032. * Represents the shadow configuration of directional lights.
  34033. *
  34034. * @augments LightShadow
  34035. */
  34036. class DirectionalLightShadow extends LightShadow {
  34037. /**
  34038. * Constructs a new directional light shadow.
  34039. */
  34040. constructor() {
  34041. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34042. /**
  34043. * This flag can be used for type testing.
  34044. *
  34045. * @type {boolean}
  34046. * @readonly
  34047. * @default true
  34048. */
  34049. this.isDirectionalLightShadow = true;
  34050. }
  34051. }
  34052. /**
  34053. * A light that gets emitted in a specific direction. This light will behave
  34054. * as though it is infinitely far away and the rays produced from it are all
  34055. * parallel. The common use case for this is to simulate daylight; the sun is
  34056. * far enough away that its position can be considered to be infinite, and
  34057. * all light rays coming from it are parallel.
  34058. *
  34059. * A common point of confusion for directional lights is that setting the
  34060. * rotation has no effect. This is because three.js's DirectionalLight is the
  34061. * equivalent to what is often called a 'Target Direct Light' in other
  34062. * applications.
  34063. *
  34064. * This means that its direction is calculated as pointing from the light's
  34065. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34066. * (as opposed to a 'Free Direct Light' that just has a rotation
  34067. * component).
  34068. *
  34069. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34070. *
  34071. * ```js
  34072. * // White directional light at half intensity shining from the top.
  34073. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34074. * scene.add( directionalLight );
  34075. * ```
  34076. *
  34077. * @augments Light
  34078. */
  34079. class DirectionalLight extends Light {
  34080. /**
  34081. * Constructs a new directional light.
  34082. *
  34083. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34084. * @param {number} [intensity=1] - The light's strength/intensity.
  34085. */
  34086. constructor( color, intensity ) {
  34087. super( color, intensity );
  34088. /**
  34089. * This flag can be used for type testing.
  34090. *
  34091. * @type {boolean}
  34092. * @readonly
  34093. * @default true
  34094. */
  34095. this.isDirectionalLight = true;
  34096. this.type = 'DirectionalLight';
  34097. this.position.copy( Object3D.DEFAULT_UP );
  34098. this.updateMatrix();
  34099. /**
  34100. * The directional light points from its position to the
  34101. * target's position.
  34102. *
  34103. * For the target's position to be changed to anything other
  34104. * than the default, it must be added to the scene.
  34105. *
  34106. * It is also possible to set the target to be another 3D object
  34107. * in the scene. The light will now track the target object.
  34108. *
  34109. * @type {Object3D}
  34110. */
  34111. this.target = new Object3D();
  34112. /**
  34113. * This property holds the light's shadow configuration.
  34114. *
  34115. * @type {DirectionalLightShadow}
  34116. */
  34117. this.shadow = new DirectionalLightShadow();
  34118. }
  34119. dispose() {
  34120. super.dispose();
  34121. this.shadow.dispose();
  34122. }
  34123. copy( source ) {
  34124. super.copy( source );
  34125. this.target = source.target.clone();
  34126. this.shadow = source.shadow.clone();
  34127. return this;
  34128. }
  34129. toJSON( meta ) {
  34130. const data = super.toJSON( meta );
  34131. data.object.shadow = this.shadow.toJSON();
  34132. data.object.target = this.target.uuid;
  34133. return data;
  34134. }
  34135. }
  34136. /**
  34137. * This light globally illuminates all objects in the scene equally.
  34138. *
  34139. * It cannot be used to cast shadows as it does not have a direction.
  34140. *
  34141. * ```js
  34142. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34143. * scene.add( light );
  34144. * ```
  34145. *
  34146. * @augments Light
  34147. */
  34148. class AmbientLight extends Light {
  34149. /**
  34150. * Constructs a new ambient light.
  34151. *
  34152. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34153. * @param {number} [intensity=1] - The light's strength/intensity.
  34154. */
  34155. constructor( color, intensity ) {
  34156. super( color, intensity );
  34157. /**
  34158. * This flag can be used for type testing.
  34159. *
  34160. * @type {boolean}
  34161. * @readonly
  34162. * @default true
  34163. */
  34164. this.isAmbientLight = true;
  34165. this.type = 'AmbientLight';
  34166. }
  34167. }
  34168. /**
  34169. * This class emits light uniformly across the face a rectangular plane.
  34170. * This light type can be used to simulate light sources such as bright
  34171. * windows or strip lighting.
  34172. *
  34173. * Important Notes:
  34174. *
  34175. * - There is no shadow support.
  34176. * - Only PBR materials are supported.
  34177. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34178. * into your app and init the uniforms/textures.
  34179. *
  34180. * ```js
  34181. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34182. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34183. *
  34184. * const intensity = 1; const width = 10; const height = 10;
  34185. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34186. * rectLight.position.set( 5, 5, 0 );
  34187. * rectLight.lookAt( 0, 0, 0 );
  34188. * scene.add( rectLight )
  34189. * ```
  34190. *
  34191. * @augments Light
  34192. */
  34193. class RectAreaLight extends Light {
  34194. /**
  34195. * Constructs a new area light.
  34196. *
  34197. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34198. * @param {number} [intensity=1] - The light's strength/intensity.
  34199. * @param {number} [width=10] - The width of the light.
  34200. * @param {number} [height=10] - The height of the light.
  34201. */
  34202. constructor( color, intensity, width = 10, height = 10 ) {
  34203. super( color, intensity );
  34204. /**
  34205. * This flag can be used for type testing.
  34206. *
  34207. * @type {boolean}
  34208. * @readonly
  34209. * @default true
  34210. */
  34211. this.isRectAreaLight = true;
  34212. this.type = 'RectAreaLight';
  34213. /**
  34214. * The width of the light.
  34215. *
  34216. * @type {number}
  34217. * @default 10
  34218. */
  34219. this.width = width;
  34220. /**
  34221. * The height of the light.
  34222. *
  34223. * @type {number}
  34224. * @default 10
  34225. */
  34226. this.height = height;
  34227. }
  34228. /**
  34229. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34230. * Changing the power will also change the light's intensity.
  34231. *
  34232. * @type {number}
  34233. */
  34234. get power() {
  34235. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34236. return this.intensity * this.width * this.height * Math.PI;
  34237. }
  34238. set power( power ) {
  34239. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34240. this.intensity = power / ( this.width * this.height * Math.PI );
  34241. }
  34242. copy( source ) {
  34243. super.copy( source );
  34244. this.width = source.width;
  34245. this.height = source.height;
  34246. return this;
  34247. }
  34248. toJSON( meta ) {
  34249. const data = super.toJSON( meta );
  34250. data.object.width = this.width;
  34251. data.object.height = this.height;
  34252. return data;
  34253. }
  34254. }
  34255. /**
  34256. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34257. * to encode lighting information.
  34258. *
  34259. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34260. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34261. */
  34262. class SphericalHarmonics3 {
  34263. /**
  34264. * Constructs a new spherical harmonics.
  34265. */
  34266. constructor() {
  34267. /**
  34268. * This flag can be used for type testing.
  34269. *
  34270. * @type {boolean}
  34271. * @readonly
  34272. * @default true
  34273. */
  34274. this.isSphericalHarmonics3 = true;
  34275. /**
  34276. * An array holding the (9) SH coefficients.
  34277. *
  34278. * @type {Array<Vector3>}
  34279. */
  34280. this.coefficients = [];
  34281. for ( let i = 0; i < 9; i ++ ) {
  34282. this.coefficients.push( new Vector3() );
  34283. }
  34284. }
  34285. /**
  34286. * Sets the given SH coefficients to this instance by copying
  34287. * the values.
  34288. *
  34289. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34290. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34291. */
  34292. set( coefficients ) {
  34293. for ( let i = 0; i < 9; i ++ ) {
  34294. this.coefficients[ i ].copy( coefficients[ i ] );
  34295. }
  34296. return this;
  34297. }
  34298. /**
  34299. * Sets all SH coefficients to `0`.
  34300. *
  34301. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34302. */
  34303. zero() {
  34304. for ( let i = 0; i < 9; i ++ ) {
  34305. this.coefficients[ i ].set( 0, 0, 0 );
  34306. }
  34307. return this;
  34308. }
  34309. /**
  34310. * Returns the radiance in the direction of the given normal.
  34311. *
  34312. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34313. * @param {Vector3} target - The target vector that is used to store the method's result.
  34314. * @return {Vector3} The radiance.
  34315. */
  34316. getAt( normal, target ) {
  34317. // normal is assumed to be unit length
  34318. const x = normal.x, y = normal.y, z = normal.z;
  34319. const coeff = this.coefficients;
  34320. // band 0
  34321. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34322. // band 1
  34323. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34324. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34325. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34326. // band 2
  34327. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34328. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34329. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34330. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34331. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34332. return target;
  34333. }
  34334. /**
  34335. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34336. * direction of the given normal.
  34337. *
  34338. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34339. * @param {Vector3} target - The target vector that is used to store the method's result.
  34340. * @return {Vector3} The irradiance.
  34341. */
  34342. getIrradianceAt( normal, target ) {
  34343. // normal is assumed to be unit length
  34344. const x = normal.x, y = normal.y, z = normal.z;
  34345. const coeff = this.coefficients;
  34346. // band 0
  34347. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34348. // band 1
  34349. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34350. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34351. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34352. // band 2
  34353. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34354. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34355. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34356. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34357. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34358. return target;
  34359. }
  34360. /**
  34361. * Adds the given SH to this instance.
  34362. *
  34363. * @param {SphericalHarmonics3} sh - The SH to add.
  34364. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34365. */
  34366. add( sh ) {
  34367. for ( let i = 0; i < 9; i ++ ) {
  34368. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34369. }
  34370. return this;
  34371. }
  34372. /**
  34373. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34374. * {@link SphericalHarmonics3#scale} at once.
  34375. *
  34376. * @param {SphericalHarmonics3} sh - The SH to add.
  34377. * @param {number} s - The scale factor.
  34378. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34379. */
  34380. addScaledSH( sh, s ) {
  34381. for ( let i = 0; i < 9; i ++ ) {
  34382. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34383. }
  34384. return this;
  34385. }
  34386. /**
  34387. * Scales this SH by the given scale factor.
  34388. *
  34389. * @param {number} s - The scale factor.
  34390. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34391. */
  34392. scale( s ) {
  34393. for ( let i = 0; i < 9; i ++ ) {
  34394. this.coefficients[ i ].multiplyScalar( s );
  34395. }
  34396. return this;
  34397. }
  34398. /**
  34399. * Linear interpolates between the given SH and this instance by the given
  34400. * alpha factor.
  34401. *
  34402. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34403. * @param {number} alpha - The alpha factor.
  34404. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34405. */
  34406. lerp( sh, alpha ) {
  34407. for ( let i = 0; i < 9; i ++ ) {
  34408. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34409. }
  34410. return this;
  34411. }
  34412. /**
  34413. * Returns `true` if this spherical harmonics is equal with the given one.
  34414. *
  34415. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34416. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34417. */
  34418. equals( sh ) {
  34419. for ( let i = 0; i < 9; i ++ ) {
  34420. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34421. return false;
  34422. }
  34423. }
  34424. return true;
  34425. }
  34426. /**
  34427. * Copies the values of the given spherical harmonics to this instance.
  34428. *
  34429. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34430. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34431. */
  34432. copy( sh ) {
  34433. return this.set( sh.coefficients );
  34434. }
  34435. /**
  34436. * Returns a new spherical harmonics with copied values from this instance.
  34437. *
  34438. * @return {SphericalHarmonics3} A clone of this instance.
  34439. */
  34440. clone() {
  34441. return new this.constructor().copy( this );
  34442. }
  34443. /**
  34444. * Sets the SH coefficients of this instance from the given array.
  34445. *
  34446. * @param {Array<number>} array - An array holding the SH coefficients.
  34447. * @param {number} [offset=0] - The array offset where to start copying.
  34448. * @return {SphericalHarmonics3} A clone of this instance.
  34449. */
  34450. fromArray( array, offset = 0 ) {
  34451. const coefficients = this.coefficients;
  34452. for ( let i = 0; i < 9; i ++ ) {
  34453. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34454. }
  34455. return this;
  34456. }
  34457. /**
  34458. * Returns an array with the SH coefficients, or copies them into the provided
  34459. * array. The coefficients are represented as numbers.
  34460. *
  34461. * @param {Array<number>} [array=[]] - The target array.
  34462. * @param {number} [offset=0] - The array offset where to start copying.
  34463. * @return {Array<number>} An array with flat SH coefficients.
  34464. */
  34465. toArray( array = [], offset = 0 ) {
  34466. const coefficients = this.coefficients;
  34467. for ( let i = 0; i < 9; i ++ ) {
  34468. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34469. }
  34470. return array;
  34471. }
  34472. /**
  34473. * Computes the SH basis for the given normal vector.
  34474. *
  34475. * @param {Vector3} normal - The normal.
  34476. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34477. */
  34478. static getBasisAt( normal, shBasis ) {
  34479. // normal is assumed to be unit length
  34480. const x = normal.x, y = normal.y, z = normal.z;
  34481. // band 0
  34482. shBasis[ 0 ] = 0.282095;
  34483. // band 1
  34484. shBasis[ 1 ] = 0.488603 * y;
  34485. shBasis[ 2 ] = 0.488603 * z;
  34486. shBasis[ 3 ] = 0.488603 * x;
  34487. // band 2
  34488. shBasis[ 4 ] = 1.092548 * x * y;
  34489. shBasis[ 5 ] = 1.092548 * y * z;
  34490. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34491. shBasis[ 7 ] = 1.092548 * x * z;
  34492. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34493. }
  34494. }
  34495. /**
  34496. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34497. * classical light sources (e.g. directional, point or spot lights), light
  34498. * probes do not emit light. Instead they store information about light
  34499. * passing through 3D space. During rendering, the light that hits a 3D
  34500. * object is approximated by using the data from the light probe.
  34501. *
  34502. * Light probes are usually created from (radiance) environment maps. The
  34503. * class {@link LightProbeGenerator} can be used to create light probes from
  34504. * cube textures or render targets. However, light estimation data could also
  34505. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34506. * augmented reality content that reacts to real world lighting.
  34507. *
  34508. * The current probe implementation in three.js supports so-called diffuse
  34509. * light probes. This type of light probe is functionally equivalent to an
  34510. * irradiance environment map.
  34511. *
  34512. * @augments Light
  34513. */
  34514. class LightProbe extends Light {
  34515. /**
  34516. * Constructs a new light probe.
  34517. *
  34518. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34519. * @param {number} [intensity=1] - The light's strength/intensity.
  34520. */
  34521. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34522. super( undefined, intensity );
  34523. /**
  34524. * This flag can be used for type testing.
  34525. *
  34526. * @type {boolean}
  34527. * @readonly
  34528. * @default true
  34529. */
  34530. this.isLightProbe = true;
  34531. /**
  34532. * A light probe uses spherical harmonics to encode lighting information.
  34533. *
  34534. * @type {SphericalHarmonics3}
  34535. */
  34536. this.sh = sh;
  34537. }
  34538. copy( source ) {
  34539. super.copy( source );
  34540. this.sh.copy( source.sh );
  34541. return this;
  34542. }
  34543. toJSON( meta ) {
  34544. const data = super.toJSON( meta );
  34545. data.object.sh = this.sh.toArray();
  34546. return data;
  34547. }
  34548. }
  34549. /**
  34550. * Class for loading materials. The files are internally
  34551. * loaded via {@link FileLoader}.
  34552. *
  34553. * ```js
  34554. * const loader = new THREE.MaterialLoader();
  34555. * const material = await loader.loadAsync( 'material.json' );
  34556. * ```
  34557. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34558. *
  34559. * @augments Loader
  34560. */
  34561. class MaterialLoader extends Loader {
  34562. /**
  34563. * Constructs a new material loader.
  34564. *
  34565. * @param {LoadingManager} [manager] - The loading manager.
  34566. */
  34567. constructor( manager ) {
  34568. super( manager );
  34569. /**
  34570. * A dictionary holding textures used by the material.
  34571. *
  34572. * @type {Object<string,Texture>}
  34573. */
  34574. this.textures = {};
  34575. }
  34576. /**
  34577. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34578. *
  34579. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34580. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34581. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34582. * @param {onErrorCallback} onError - Executed when errors occur.
  34583. */
  34584. load( url, onLoad, onProgress, onError ) {
  34585. const scope = this;
  34586. const loader = new FileLoader( scope.manager );
  34587. loader.setPath( scope.path );
  34588. loader.setRequestHeader( scope.requestHeader );
  34589. loader.setWithCredentials( scope.withCredentials );
  34590. loader.load( url, function ( text ) {
  34591. try {
  34592. onLoad( scope.parse( JSON.parse( text ) ) );
  34593. } catch ( e ) {
  34594. if ( onError ) {
  34595. onError( e );
  34596. } else {
  34597. error( e );
  34598. }
  34599. scope.manager.itemError( url );
  34600. }
  34601. }, onProgress, onError );
  34602. }
  34603. /**
  34604. * Parses the given JSON object and returns a material.
  34605. *
  34606. * @param {Object} json - The serialized material.
  34607. * @return {Material} The parsed material.
  34608. */
  34609. parse( json ) {
  34610. const textures = this.textures;
  34611. function getTexture( name ) {
  34612. if ( textures[ name ] === undefined ) {
  34613. warn( 'MaterialLoader: Undefined texture', name );
  34614. }
  34615. return textures[ name ];
  34616. }
  34617. const material = this.createMaterialFromType( json.type );
  34618. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34619. if ( json.name !== undefined ) material.name = json.name;
  34620. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34621. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34622. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34623. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34624. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34625. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34626. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34627. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34628. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34629. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34630. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34631. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34632. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34633. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34634. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34635. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34636. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34637. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34638. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34639. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34640. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34641. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34642. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34643. if ( json.fog !== undefined ) material.fog = json.fog;
  34644. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34645. if ( json.blending !== undefined ) material.blending = json.blending;
  34646. if ( json.combine !== undefined ) material.combine = json.combine;
  34647. if ( json.side !== undefined ) material.side = json.side;
  34648. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34649. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34650. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34651. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34652. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34653. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34654. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34655. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34656. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34657. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34658. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34659. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34660. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34661. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34662. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34663. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34664. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34665. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34666. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34667. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34668. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34669. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34670. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34671. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34672. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34673. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34674. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34675. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34676. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34677. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34678. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34679. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34680. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34681. if ( json.scale !== undefined ) material.scale = json.scale;
  34682. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34683. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34684. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34685. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34686. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34687. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34688. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34689. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34690. if ( json.visible !== undefined ) material.visible = json.visible;
  34691. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34692. if ( json.userData !== undefined ) material.userData = json.userData;
  34693. if ( json.vertexColors !== undefined ) {
  34694. if ( typeof json.vertexColors === 'number' ) {
  34695. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34696. } else {
  34697. material.vertexColors = json.vertexColors;
  34698. }
  34699. }
  34700. // Shader Material
  34701. if ( json.uniforms !== undefined ) {
  34702. for ( const name in json.uniforms ) {
  34703. const uniform = json.uniforms[ name ];
  34704. material.uniforms[ name ] = {};
  34705. switch ( uniform.type ) {
  34706. case 't':
  34707. material.uniforms[ name ].value = getTexture( uniform.value );
  34708. break;
  34709. case 'c':
  34710. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34711. break;
  34712. case 'v2':
  34713. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34714. break;
  34715. case 'v3':
  34716. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34717. break;
  34718. case 'v4':
  34719. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34720. break;
  34721. case 'm3':
  34722. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34723. break;
  34724. case 'm4':
  34725. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34726. break;
  34727. default:
  34728. material.uniforms[ name ].value = uniform.value;
  34729. }
  34730. }
  34731. }
  34732. if ( json.defines !== undefined ) material.defines = json.defines;
  34733. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34734. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34735. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34736. if ( json.extensions !== undefined ) {
  34737. for ( const key in json.extensions ) {
  34738. material.extensions[ key ] = json.extensions[ key ];
  34739. }
  34740. }
  34741. if ( json.lights !== undefined ) material.lights = json.lights;
  34742. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34743. // for PointsMaterial
  34744. if ( json.size !== undefined ) material.size = json.size;
  34745. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34746. // maps
  34747. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34748. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34749. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34750. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34751. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34752. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34753. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34754. if ( json.normalScale !== undefined ) {
  34755. let normalScale = json.normalScale;
  34756. if ( Array.isArray( normalScale ) === false ) {
  34757. // Blender exporter used to export a scalar. See #7459
  34758. normalScale = [ normalScale, normalScale ];
  34759. }
  34760. material.normalScale = new Vector2().fromArray( normalScale );
  34761. }
  34762. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34763. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34764. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34765. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34766. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34767. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34768. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34769. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34770. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34771. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34772. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34773. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34774. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34775. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34776. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34777. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34778. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34779. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34780. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34781. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34782. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34783. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34784. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34785. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34786. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34787. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34788. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34789. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34790. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34791. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34792. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34793. return material;
  34794. }
  34795. /**
  34796. * Textures are not embedded in the material JSON so they have
  34797. * to be injected before the loading process starts.
  34798. *
  34799. * @param {Object} value - A dictionary holding textures for material properties.
  34800. * @return {MaterialLoader} A reference to this material loader.
  34801. */
  34802. setTextures( value ) {
  34803. this.textures = value;
  34804. return this;
  34805. }
  34806. /**
  34807. * Creates a material for the given type.
  34808. *
  34809. * @param {string} type - The material type.
  34810. * @return {Material} The new material.
  34811. */
  34812. createMaterialFromType( type ) {
  34813. return MaterialLoader.createMaterialFromType( type );
  34814. }
  34815. /**
  34816. * Creates a material for the given type.
  34817. *
  34818. * @static
  34819. * @param {string} type - The material type.
  34820. * @return {Material} The new material.
  34821. */
  34822. static createMaterialFromType( type ) {
  34823. const materialLib = {
  34824. ShadowMaterial,
  34825. SpriteMaterial,
  34826. RawShaderMaterial,
  34827. ShaderMaterial,
  34828. PointsMaterial,
  34829. MeshPhysicalMaterial,
  34830. MeshStandardMaterial,
  34831. MeshPhongMaterial,
  34832. MeshToonMaterial,
  34833. MeshNormalMaterial,
  34834. MeshLambertMaterial,
  34835. MeshDepthMaterial,
  34836. MeshDistanceMaterial,
  34837. MeshBasicMaterial,
  34838. MeshMatcapMaterial,
  34839. LineDashedMaterial,
  34840. LineBasicMaterial,
  34841. Material
  34842. };
  34843. return new materialLib[ type ]();
  34844. }
  34845. }
  34846. /**
  34847. * A class with loader utility functions.
  34848. */
  34849. class LoaderUtils {
  34850. /**
  34851. * Extracts the base URL from the given URL.
  34852. *
  34853. * @param {string} url -The URL to extract the base URL from.
  34854. * @return {string} The extracted base URL.
  34855. */
  34856. static extractUrlBase( url ) {
  34857. const index = url.lastIndexOf( '/' );
  34858. if ( index === -1 ) return './';
  34859. return url.slice( 0, index + 1 );
  34860. }
  34861. /**
  34862. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34863. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34864. * string.
  34865. *
  34866. * @param {string} url -The URL to resolve.
  34867. * @param {string} path - The base path for relative URLs to be resolved against.
  34868. * @return {string} The resolved URL.
  34869. */
  34870. static resolveURL( url, path ) {
  34871. // Invalid URL
  34872. if ( typeof url !== 'string' || url === '' ) return '';
  34873. // Host Relative URL
  34874. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34875. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34876. }
  34877. // Absolute URL http://,https://,//
  34878. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34879. // Data URI
  34880. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34881. // Blob URL
  34882. if ( /^blob:.*$/i.test( url ) ) return url;
  34883. // Relative URL
  34884. return path + url;
  34885. }
  34886. }
  34887. /**
  34888. * An instanced version of a geometry.
  34889. */
  34890. class InstancedBufferGeometry extends BufferGeometry {
  34891. /**
  34892. * Constructs a new instanced buffer geometry.
  34893. */
  34894. constructor() {
  34895. super();
  34896. /**
  34897. * This flag can be used for type testing.
  34898. *
  34899. * @type {boolean}
  34900. * @readonly
  34901. * @default true
  34902. */
  34903. this.isInstancedBufferGeometry = true;
  34904. this.type = 'InstancedBufferGeometry';
  34905. /**
  34906. * The instance count.
  34907. *
  34908. * @type {number}
  34909. * @default Infinity
  34910. */
  34911. this.instanceCount = Infinity;
  34912. }
  34913. copy( source ) {
  34914. super.copy( source );
  34915. this.instanceCount = source.instanceCount;
  34916. return this;
  34917. }
  34918. toJSON() {
  34919. const data = super.toJSON();
  34920. data.instanceCount = this.instanceCount;
  34921. data.isInstancedBufferGeometry = true;
  34922. return data;
  34923. }
  34924. }
  34925. /**
  34926. * Class for loading geometries. The files are internally
  34927. * loaded via {@link FileLoader}.
  34928. *
  34929. * ```js
  34930. * const loader = new THREE.BufferGeometryLoader();
  34931. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34932. *
  34933. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34934. * const object = new THREE.Mesh( geometry, material );
  34935. * scene.add( object );
  34936. * ```
  34937. *
  34938. * @augments Loader
  34939. */
  34940. class BufferGeometryLoader extends Loader {
  34941. /**
  34942. * Constructs a new geometry loader.
  34943. *
  34944. * @param {LoadingManager} [manager] - The loading manager.
  34945. */
  34946. constructor( manager ) {
  34947. super( manager );
  34948. }
  34949. /**
  34950. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34951. *
  34952. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34953. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34954. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34955. * @param {onErrorCallback} onError - Executed when errors occur.
  34956. */
  34957. load( url, onLoad, onProgress, onError ) {
  34958. const scope = this;
  34959. const loader = new FileLoader( scope.manager );
  34960. loader.setPath( scope.path );
  34961. loader.setRequestHeader( scope.requestHeader );
  34962. loader.setWithCredentials( scope.withCredentials );
  34963. loader.load( url, function ( text ) {
  34964. try {
  34965. onLoad( scope.parse( JSON.parse( text ) ) );
  34966. } catch ( e ) {
  34967. if ( onError ) {
  34968. onError( e );
  34969. } else {
  34970. error( e );
  34971. }
  34972. scope.manager.itemError( url );
  34973. }
  34974. }, onProgress, onError );
  34975. }
  34976. /**
  34977. * Parses the given JSON object and returns a geometry.
  34978. *
  34979. * @param {Object} json - The serialized geometry.
  34980. * @return {BufferGeometry} The parsed geometry.
  34981. */
  34982. parse( json ) {
  34983. const interleavedBufferMap = {};
  34984. const arrayBufferMap = {};
  34985. function getInterleavedBuffer( json, uuid ) {
  34986. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34987. const interleavedBuffers = json.interleavedBuffers;
  34988. const interleavedBuffer = interleavedBuffers[ uuid ];
  34989. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34990. const array = getTypedArray( interleavedBuffer.type, buffer );
  34991. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34992. ib.uuid = interleavedBuffer.uuid;
  34993. interleavedBufferMap[ uuid ] = ib;
  34994. return ib;
  34995. }
  34996. function getArrayBuffer( json, uuid ) {
  34997. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34998. const arrayBuffers = json.arrayBuffers;
  34999. const arrayBuffer = arrayBuffers[ uuid ];
  35000. const ab = new Uint32Array( arrayBuffer ).buffer;
  35001. arrayBufferMap[ uuid ] = ab;
  35002. return ab;
  35003. }
  35004. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35005. const index = json.data.index;
  35006. if ( index !== undefined ) {
  35007. const typedArray = getTypedArray( index.type, index.array );
  35008. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35009. }
  35010. const attributes = json.data.attributes;
  35011. for ( const key in attributes ) {
  35012. const attribute = attributes[ key ];
  35013. let bufferAttribute;
  35014. if ( attribute.isInterleavedBufferAttribute ) {
  35015. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35016. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35017. } else {
  35018. const typedArray = getTypedArray( attribute.type, attribute.array );
  35019. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35020. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35021. }
  35022. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35023. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35024. geometry.setAttribute( key, bufferAttribute );
  35025. }
  35026. const morphAttributes = json.data.morphAttributes;
  35027. if ( morphAttributes ) {
  35028. for ( const key in morphAttributes ) {
  35029. const attributeArray = morphAttributes[ key ];
  35030. const array = [];
  35031. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35032. const attribute = attributeArray[ i ];
  35033. let bufferAttribute;
  35034. if ( attribute.isInterleavedBufferAttribute ) {
  35035. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35036. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35037. } else {
  35038. const typedArray = getTypedArray( attribute.type, attribute.array );
  35039. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35040. }
  35041. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35042. array.push( bufferAttribute );
  35043. }
  35044. geometry.morphAttributes[ key ] = array;
  35045. }
  35046. }
  35047. const morphTargetsRelative = json.data.morphTargetsRelative;
  35048. if ( morphTargetsRelative ) {
  35049. geometry.morphTargetsRelative = true;
  35050. }
  35051. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35052. if ( groups !== undefined ) {
  35053. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35054. const group = groups[ i ];
  35055. geometry.addGroup( group.start, group.count, group.materialIndex );
  35056. }
  35057. }
  35058. const boundingSphere = json.data.boundingSphere;
  35059. if ( boundingSphere !== undefined ) {
  35060. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35061. }
  35062. if ( json.name ) geometry.name = json.name;
  35063. if ( json.userData ) geometry.userData = json.userData;
  35064. return geometry;
  35065. }
  35066. }
  35067. /**
  35068. * 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).
  35069. * The files are internally loaded via {@link FileLoader}.
  35070. *
  35071. * ```js
  35072. * const loader = new THREE.ObjectLoader();
  35073. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35074. * scene.add( obj );
  35075. *
  35076. * // Alternatively, to parse a previously loaded JSON structure
  35077. * const object = await loader.parseAsync( a_json_object );
  35078. * scene.add( object );
  35079. * ```
  35080. *
  35081. * @augments Loader
  35082. */
  35083. class ObjectLoader extends Loader {
  35084. /**
  35085. * Constructs a new object loader.
  35086. *
  35087. * @param {LoadingManager} [manager] - The loading manager.
  35088. */
  35089. constructor( manager ) {
  35090. super( manager );
  35091. }
  35092. /**
  35093. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35094. *
  35095. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35096. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35097. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35098. * @param {onErrorCallback} onError - Executed when errors occur.
  35099. */
  35100. load( url, onLoad, onProgress, onError ) {
  35101. const scope = this;
  35102. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35103. this.resourcePath = this.resourcePath || path;
  35104. const loader = new FileLoader( this.manager );
  35105. loader.setPath( this.path );
  35106. loader.setRequestHeader( this.requestHeader );
  35107. loader.setWithCredentials( this.withCredentials );
  35108. loader.load( url, function ( text ) {
  35109. let json = null;
  35110. try {
  35111. json = JSON.parse( text );
  35112. } catch ( error ) {
  35113. if ( onError !== undefined ) onError( error );
  35114. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35115. return;
  35116. }
  35117. const metadata = json.metadata;
  35118. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35119. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35120. error( 'ObjectLoader: Can\'t load ' + url );
  35121. return;
  35122. }
  35123. scope.parse( json, onLoad );
  35124. }, onProgress, onError );
  35125. }
  35126. /**
  35127. * Async version of {@link ObjectLoader#load}.
  35128. *
  35129. * @async
  35130. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35131. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35132. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35133. */
  35134. async loadAsync( url, onProgress ) {
  35135. const scope = this;
  35136. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35137. this.resourcePath = this.resourcePath || path;
  35138. const loader = new FileLoader( this.manager );
  35139. loader.setPath( this.path );
  35140. loader.setRequestHeader( this.requestHeader );
  35141. loader.setWithCredentials( this.withCredentials );
  35142. const text = await loader.loadAsync( url, onProgress );
  35143. const json = JSON.parse( text );
  35144. const metadata = json.metadata;
  35145. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35146. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35147. }
  35148. return await scope.parseAsync( json );
  35149. }
  35150. /**
  35151. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35152. * but can also be used directly to parse a previously loaded JSON structure.
  35153. *
  35154. * @param {Object} json - The serialized 3D object.
  35155. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35156. * @return {Object3D} The parsed 3D object.
  35157. */
  35158. parse( json, onLoad ) {
  35159. const animations = this.parseAnimations( json.animations );
  35160. const shapes = this.parseShapes( json.shapes );
  35161. const geometries = this.parseGeometries( json.geometries, shapes );
  35162. const images = this.parseImages( json.images, function () {
  35163. if ( onLoad !== undefined ) onLoad( object );
  35164. } );
  35165. const textures = this.parseTextures( json.textures, images );
  35166. const materials = this.parseMaterials( json.materials, textures );
  35167. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35168. const skeletons = this.parseSkeletons( json.skeletons, object );
  35169. this.bindSkeletons( object, skeletons );
  35170. this.bindLightTargets( object );
  35171. //
  35172. if ( onLoad !== undefined ) {
  35173. let hasImages = false;
  35174. for ( const uuid in images ) {
  35175. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35176. hasImages = true;
  35177. break;
  35178. }
  35179. }
  35180. if ( hasImages === false ) onLoad( object );
  35181. }
  35182. return object;
  35183. }
  35184. /**
  35185. * Async version of {@link ObjectLoader#parse}.
  35186. *
  35187. * @param {Object} json - The serialized 3D object.
  35188. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35189. */
  35190. async parseAsync( json ) {
  35191. const animations = this.parseAnimations( json.animations );
  35192. const shapes = this.parseShapes( json.shapes );
  35193. const geometries = this.parseGeometries( json.geometries, shapes );
  35194. const images = await this.parseImagesAsync( json.images );
  35195. const textures = this.parseTextures( json.textures, images );
  35196. const materials = this.parseMaterials( json.materials, textures );
  35197. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35198. const skeletons = this.parseSkeletons( json.skeletons, object );
  35199. this.bindSkeletons( object, skeletons );
  35200. this.bindLightTargets( object );
  35201. return object;
  35202. }
  35203. // internals
  35204. parseShapes( json ) {
  35205. const shapes = {};
  35206. if ( json !== undefined ) {
  35207. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35208. const shape = new Shape().fromJSON( json[ i ] );
  35209. shapes[ shape.uuid ] = shape;
  35210. }
  35211. }
  35212. return shapes;
  35213. }
  35214. parseSkeletons( json, object ) {
  35215. const skeletons = {};
  35216. const bones = {};
  35217. // generate bone lookup table
  35218. object.traverse( function ( child ) {
  35219. if ( child.isBone ) bones[ child.uuid ] = child;
  35220. } );
  35221. // create skeletons
  35222. if ( json !== undefined ) {
  35223. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35224. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35225. skeletons[ skeleton.uuid ] = skeleton;
  35226. }
  35227. }
  35228. return skeletons;
  35229. }
  35230. parseGeometries( json, shapes ) {
  35231. const geometries = {};
  35232. if ( json !== undefined ) {
  35233. const bufferGeometryLoader = new BufferGeometryLoader();
  35234. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35235. let geometry;
  35236. const data = json[ i ];
  35237. switch ( data.type ) {
  35238. case 'BufferGeometry':
  35239. case 'InstancedBufferGeometry':
  35240. geometry = bufferGeometryLoader.parse( data );
  35241. break;
  35242. default:
  35243. if ( data.type in Geometries ) {
  35244. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35245. } else {
  35246. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35247. }
  35248. }
  35249. geometry.uuid = data.uuid;
  35250. if ( data.name !== undefined ) geometry.name = data.name;
  35251. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35252. geometries[ data.uuid ] = geometry;
  35253. }
  35254. }
  35255. return geometries;
  35256. }
  35257. parseMaterials( json, textures ) {
  35258. const cache = {}; // MultiMaterial
  35259. const materials = {};
  35260. if ( json !== undefined ) {
  35261. const loader = new MaterialLoader();
  35262. loader.setTextures( textures );
  35263. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35264. const data = json[ i ];
  35265. if ( cache[ data.uuid ] === undefined ) {
  35266. cache[ data.uuid ] = loader.parse( data );
  35267. }
  35268. materials[ data.uuid ] = cache[ data.uuid ];
  35269. }
  35270. }
  35271. return materials;
  35272. }
  35273. parseAnimations( json ) {
  35274. const animations = {};
  35275. if ( json !== undefined ) {
  35276. for ( let i = 0; i < json.length; i ++ ) {
  35277. const data = json[ i ];
  35278. const clip = AnimationClip.parse( data );
  35279. animations[ clip.uuid ] = clip;
  35280. }
  35281. }
  35282. return animations;
  35283. }
  35284. parseImages( json, onLoad ) {
  35285. const scope = this;
  35286. const images = {};
  35287. let loader;
  35288. function loadImage( url ) {
  35289. scope.manager.itemStart( url );
  35290. return loader.load( url, function () {
  35291. scope.manager.itemEnd( url );
  35292. }, undefined, function () {
  35293. scope.manager.itemError( url );
  35294. scope.manager.itemEnd( url );
  35295. } );
  35296. }
  35297. function deserializeImage( image ) {
  35298. if ( typeof image === 'string' ) {
  35299. const url = image;
  35300. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35301. return loadImage( path );
  35302. } else {
  35303. if ( image.data ) {
  35304. return {
  35305. data: getTypedArray( image.type, image.data ),
  35306. width: image.width,
  35307. height: image.height
  35308. };
  35309. } else {
  35310. return null;
  35311. }
  35312. }
  35313. }
  35314. if ( json !== undefined && json.length > 0 ) {
  35315. const manager = new LoadingManager( onLoad );
  35316. loader = new ImageLoader( manager );
  35317. loader.setCrossOrigin( this.crossOrigin );
  35318. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35319. const image = json[ i ];
  35320. const url = image.url;
  35321. if ( Array.isArray( url ) ) {
  35322. // load array of images e.g CubeTexture
  35323. const imageArray = [];
  35324. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35325. const currentUrl = url[ j ];
  35326. const deserializedImage = deserializeImage( currentUrl );
  35327. if ( deserializedImage !== null ) {
  35328. if ( deserializedImage instanceof HTMLImageElement ) {
  35329. imageArray.push( deserializedImage );
  35330. } else {
  35331. // special case: handle array of data textures for cube textures
  35332. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35333. }
  35334. }
  35335. }
  35336. images[ image.uuid ] = new Source( imageArray );
  35337. } else {
  35338. // load single image
  35339. const deserializedImage = deserializeImage( image.url );
  35340. images[ image.uuid ] = new Source( deserializedImage );
  35341. }
  35342. }
  35343. }
  35344. return images;
  35345. }
  35346. async parseImagesAsync( json ) {
  35347. const scope = this;
  35348. const images = {};
  35349. let loader;
  35350. async function deserializeImage( image ) {
  35351. if ( typeof image === 'string' ) {
  35352. const url = image;
  35353. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35354. return await loader.loadAsync( path );
  35355. } else {
  35356. if ( image.data ) {
  35357. return {
  35358. data: getTypedArray( image.type, image.data ),
  35359. width: image.width,
  35360. height: image.height
  35361. };
  35362. } else {
  35363. return null;
  35364. }
  35365. }
  35366. }
  35367. if ( json !== undefined && json.length > 0 ) {
  35368. loader = new ImageLoader( this.manager );
  35369. loader.setCrossOrigin( this.crossOrigin );
  35370. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35371. const image = json[ i ];
  35372. const url = image.url;
  35373. if ( Array.isArray( url ) ) {
  35374. // load array of images e.g CubeTexture
  35375. const imageArray = [];
  35376. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35377. const currentUrl = url[ j ];
  35378. const deserializedImage = await deserializeImage( currentUrl );
  35379. if ( deserializedImage !== null ) {
  35380. if ( deserializedImage instanceof HTMLImageElement ) {
  35381. imageArray.push( deserializedImage );
  35382. } else {
  35383. // special case: handle array of data textures for cube textures
  35384. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35385. }
  35386. }
  35387. }
  35388. images[ image.uuid ] = new Source( imageArray );
  35389. } else {
  35390. // load single image
  35391. const deserializedImage = await deserializeImage( image.url );
  35392. images[ image.uuid ] = new Source( deserializedImage );
  35393. }
  35394. }
  35395. }
  35396. return images;
  35397. }
  35398. parseTextures( json, images ) {
  35399. function parseConstant( value, type ) {
  35400. if ( typeof value === 'number' ) return value;
  35401. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35402. return type[ value ];
  35403. }
  35404. const textures = {};
  35405. if ( json !== undefined ) {
  35406. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35407. const data = json[ i ];
  35408. if ( data.image === undefined ) {
  35409. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35410. }
  35411. if ( images[ data.image ] === undefined ) {
  35412. warn( 'ObjectLoader: Undefined image', data.image );
  35413. }
  35414. const source = images[ data.image ];
  35415. const image = source.data;
  35416. let texture;
  35417. if ( Array.isArray( image ) ) {
  35418. texture = new CubeTexture();
  35419. if ( image.length === 6 ) texture.needsUpdate = true;
  35420. } else {
  35421. if ( image && image.data ) {
  35422. texture = new DataTexture();
  35423. } else {
  35424. texture = new Texture();
  35425. }
  35426. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35427. }
  35428. texture.source = source;
  35429. texture.uuid = data.uuid;
  35430. if ( data.name !== undefined ) texture.name = data.name;
  35431. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35432. if ( data.channel !== undefined ) texture.channel = data.channel;
  35433. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35434. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35435. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35436. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35437. if ( data.wrap !== undefined ) {
  35438. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35439. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35440. }
  35441. if ( data.format !== undefined ) texture.format = data.format;
  35442. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35443. if ( data.type !== undefined ) texture.type = data.type;
  35444. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35445. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35446. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35447. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35448. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35449. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35450. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35451. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35452. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35453. if ( data.userData !== undefined ) texture.userData = data.userData;
  35454. textures[ data.uuid ] = texture;
  35455. }
  35456. }
  35457. return textures;
  35458. }
  35459. parseObject( data, geometries, materials, textures, animations ) {
  35460. let object;
  35461. function getGeometry( name ) {
  35462. if ( geometries[ name ] === undefined ) {
  35463. warn( 'ObjectLoader: Undefined geometry', name );
  35464. }
  35465. return geometries[ name ];
  35466. }
  35467. function getMaterial( name ) {
  35468. if ( name === undefined ) return undefined;
  35469. if ( Array.isArray( name ) ) {
  35470. const array = [];
  35471. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35472. const uuid = name[ i ];
  35473. if ( materials[ uuid ] === undefined ) {
  35474. warn( 'ObjectLoader: Undefined material', uuid );
  35475. }
  35476. array.push( materials[ uuid ] );
  35477. }
  35478. return array;
  35479. }
  35480. if ( materials[ name ] === undefined ) {
  35481. warn( 'ObjectLoader: Undefined material', name );
  35482. }
  35483. return materials[ name ];
  35484. }
  35485. function getTexture( uuid ) {
  35486. if ( textures[ uuid ] === undefined ) {
  35487. warn( 'ObjectLoader: Undefined texture', uuid );
  35488. }
  35489. return textures[ uuid ];
  35490. }
  35491. let geometry, material;
  35492. switch ( data.type ) {
  35493. case 'Scene':
  35494. object = new Scene();
  35495. if ( data.background !== undefined ) {
  35496. if ( Number.isInteger( data.background ) ) {
  35497. object.background = new Color( data.background );
  35498. } else {
  35499. object.background = getTexture( data.background );
  35500. }
  35501. }
  35502. if ( data.environment !== undefined ) {
  35503. object.environment = getTexture( data.environment );
  35504. }
  35505. if ( data.fog !== undefined ) {
  35506. if ( data.fog.type === 'Fog' ) {
  35507. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35508. } else if ( data.fog.type === 'FogExp2' ) {
  35509. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35510. }
  35511. if ( data.fog.name !== '' ) {
  35512. object.fog.name = data.fog.name;
  35513. }
  35514. }
  35515. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35516. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35517. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35518. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35519. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35520. break;
  35521. case 'PerspectiveCamera':
  35522. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35523. if ( data.focus !== undefined ) object.focus = data.focus;
  35524. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35525. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35526. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35527. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35528. break;
  35529. case 'OrthographicCamera':
  35530. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35531. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35532. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35533. break;
  35534. case 'AmbientLight':
  35535. object = new AmbientLight( data.color, data.intensity );
  35536. break;
  35537. case 'DirectionalLight':
  35538. object = new DirectionalLight( data.color, data.intensity );
  35539. object.target = data.target || '';
  35540. break;
  35541. case 'PointLight':
  35542. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35543. break;
  35544. case 'RectAreaLight':
  35545. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35546. break;
  35547. case 'SpotLight':
  35548. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35549. object.target = data.target || '';
  35550. break;
  35551. case 'HemisphereLight':
  35552. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35553. break;
  35554. case 'LightProbe':
  35555. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35556. object = new LightProbe( sh, data.intensity );
  35557. break;
  35558. case 'SkinnedMesh':
  35559. geometry = getGeometry( data.geometry );
  35560. material = getMaterial( data.material );
  35561. object = new SkinnedMesh( geometry, material );
  35562. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35563. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35564. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35565. break;
  35566. case 'Mesh':
  35567. geometry = getGeometry( data.geometry );
  35568. material = getMaterial( data.material );
  35569. object = new Mesh( geometry, material );
  35570. break;
  35571. case 'InstancedMesh':
  35572. geometry = getGeometry( data.geometry );
  35573. material = getMaterial( data.material );
  35574. const count = data.count;
  35575. const instanceMatrix = data.instanceMatrix;
  35576. const instanceColor = data.instanceColor;
  35577. object = new InstancedMesh( geometry, material, count );
  35578. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35579. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35580. break;
  35581. case 'BatchedMesh':
  35582. geometry = getGeometry( data.geometry );
  35583. material = getMaterial( data.material );
  35584. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35585. object.geometry = geometry;
  35586. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35587. object.sortObjects = data.sortObjects;
  35588. object._drawRanges = data.drawRanges;
  35589. object._reservedRanges = data.reservedRanges;
  35590. object._geometryInfo = data.geometryInfo.map( info => {
  35591. let box = null;
  35592. let sphere = null;
  35593. if ( info.boundingBox !== undefined ) {
  35594. box = new Box3().fromJSON( info.boundingBox );
  35595. }
  35596. if ( info.boundingSphere !== undefined ) {
  35597. sphere = new Sphere().fromJSON( info.boundingSphere );
  35598. }
  35599. return {
  35600. ...info,
  35601. boundingBox: box,
  35602. boundingSphere: sphere
  35603. };
  35604. } );
  35605. object._instanceInfo = data.instanceInfo;
  35606. object._availableInstanceIds = data._availableInstanceIds;
  35607. object._availableGeometryIds = data._availableGeometryIds;
  35608. object._nextIndexStart = data.nextIndexStart;
  35609. object._nextVertexStart = data.nextVertexStart;
  35610. object._geometryCount = data.geometryCount;
  35611. object._maxInstanceCount = data.maxInstanceCount;
  35612. object._maxVertexCount = data.maxVertexCount;
  35613. object._maxIndexCount = data.maxIndexCount;
  35614. object._geometryInitialized = data.geometryInitialized;
  35615. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35616. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35617. if ( data.colorsTexture !== undefined ) {
  35618. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35619. }
  35620. if ( data.boundingSphere !== undefined ) {
  35621. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35622. }
  35623. if ( data.boundingBox !== undefined ) {
  35624. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35625. }
  35626. break;
  35627. case 'LOD':
  35628. object = new LOD();
  35629. break;
  35630. case 'Line':
  35631. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35632. break;
  35633. case 'LineLoop':
  35634. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35635. break;
  35636. case 'LineSegments':
  35637. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35638. break;
  35639. case 'PointCloud':
  35640. case 'Points':
  35641. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35642. break;
  35643. case 'Sprite':
  35644. object = new Sprite( getMaterial( data.material ) );
  35645. break;
  35646. case 'Group':
  35647. object = new Group();
  35648. break;
  35649. case 'Bone':
  35650. object = new Bone();
  35651. break;
  35652. default:
  35653. object = new Object3D();
  35654. }
  35655. object.uuid = data.uuid;
  35656. if ( data.name !== undefined ) object.name = data.name;
  35657. if ( data.matrix !== undefined ) {
  35658. object.matrix.fromArray( data.matrix );
  35659. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35660. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35661. } else {
  35662. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35663. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35664. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35665. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35666. }
  35667. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35668. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35669. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35670. if ( data.shadow ) {
  35671. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35672. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35673. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35674. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35675. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35676. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35677. }
  35678. if ( data.visible !== undefined ) object.visible = data.visible;
  35679. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35680. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35681. if ( data.userData !== undefined ) object.userData = data.userData;
  35682. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35683. if ( data.children !== undefined ) {
  35684. const children = data.children;
  35685. for ( let i = 0; i < children.length; i ++ ) {
  35686. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35687. }
  35688. }
  35689. if ( data.animations !== undefined ) {
  35690. const objectAnimations = data.animations;
  35691. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35692. const uuid = objectAnimations[ i ];
  35693. object.animations.push( animations[ uuid ] );
  35694. }
  35695. }
  35696. if ( data.type === 'LOD' ) {
  35697. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35698. const levels = data.levels;
  35699. for ( let l = 0; l < levels.length; l ++ ) {
  35700. const level = levels[ l ];
  35701. const child = object.getObjectByProperty( 'uuid', level.object );
  35702. if ( child !== undefined ) {
  35703. object.addLevel( child, level.distance, level.hysteresis );
  35704. }
  35705. }
  35706. }
  35707. return object;
  35708. }
  35709. bindSkeletons( object, skeletons ) {
  35710. if ( Object.keys( skeletons ).length === 0 ) return;
  35711. object.traverse( function ( child ) {
  35712. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35713. const skeleton = skeletons[ child.skeleton ];
  35714. if ( skeleton === undefined ) {
  35715. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35716. } else {
  35717. child.bind( skeleton, child.bindMatrix );
  35718. }
  35719. }
  35720. } );
  35721. }
  35722. bindLightTargets( object ) {
  35723. object.traverse( function ( child ) {
  35724. if ( child.isDirectionalLight || child.isSpotLight ) {
  35725. const uuid = child.target;
  35726. const target = object.getObjectByProperty( 'uuid', uuid );
  35727. if ( target !== undefined ) {
  35728. child.target = target;
  35729. } else {
  35730. child.target = new Object3D();
  35731. }
  35732. }
  35733. } );
  35734. }
  35735. }
  35736. const TEXTURE_MAPPING = {
  35737. UVMapping: UVMapping,
  35738. CubeReflectionMapping: CubeReflectionMapping,
  35739. CubeRefractionMapping: CubeRefractionMapping,
  35740. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35741. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35742. CubeUVReflectionMapping: CubeUVReflectionMapping
  35743. };
  35744. const TEXTURE_WRAPPING = {
  35745. RepeatWrapping: RepeatWrapping,
  35746. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35747. MirroredRepeatWrapping: MirroredRepeatWrapping
  35748. };
  35749. const TEXTURE_FILTER = {
  35750. NearestFilter: NearestFilter,
  35751. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35752. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35753. LinearFilter: LinearFilter,
  35754. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35755. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35756. };
  35757. const _errorMap = new WeakMap();
  35758. /**
  35759. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35760. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35761. * textures for rendering.
  35762. *
  35763. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35764. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35765. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35766. *
  35767. * To match the default behaviour of {@link Texture}, the following options are needed:
  35768. *
  35769. * ```js
  35770. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35771. * ```
  35772. *
  35773. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35774. *
  35775. * ```js
  35776. * const loader = new THREE.ImageBitmapLoader();
  35777. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35778. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35779. *
  35780. * const texture = new THREE.Texture( imageBitmap );
  35781. * texture.needsUpdate = true;
  35782. * ```
  35783. *
  35784. * @augments Loader
  35785. */
  35786. class ImageBitmapLoader extends Loader {
  35787. /**
  35788. * Constructs a new image bitmap loader.
  35789. *
  35790. * @param {LoadingManager} [manager] - The loading manager.
  35791. */
  35792. constructor( manager ) {
  35793. super( manager );
  35794. /**
  35795. * This flag can be used for type testing.
  35796. *
  35797. * @type {boolean}
  35798. * @readonly
  35799. * @default true
  35800. */
  35801. this.isImageBitmapLoader = true;
  35802. if ( typeof createImageBitmap === 'undefined' ) {
  35803. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35804. }
  35805. if ( typeof fetch === 'undefined' ) {
  35806. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35807. }
  35808. /**
  35809. * Represents the loader options.
  35810. *
  35811. * @type {Object}
  35812. * @default {premultiplyAlpha:'none'}
  35813. */
  35814. this.options = { premultiplyAlpha: 'none' };
  35815. /**
  35816. * Used for aborting requests.
  35817. *
  35818. * @private
  35819. * @type {AbortController}
  35820. */
  35821. this._abortController = new AbortController();
  35822. }
  35823. /**
  35824. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35825. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35826. *
  35827. * @param {Object} options - The loader options to set.
  35828. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35829. */
  35830. setOptions( options ) {
  35831. this.options = options;
  35832. return this;
  35833. }
  35834. /**
  35835. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35836. *
  35837. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35838. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35839. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35840. * @param {onErrorCallback} onError - Executed when errors occur.
  35841. * @return {ImageBitmap|undefined} The image bitmap.
  35842. */
  35843. load( url, onLoad, onProgress, onError ) {
  35844. if ( url === undefined ) url = '';
  35845. if ( this.path !== undefined ) url = this.path + url;
  35846. url = this.manager.resolveURL( url );
  35847. const scope = this;
  35848. const cached = Cache.get( `image-bitmap:${url}` );
  35849. if ( cached !== undefined ) {
  35850. scope.manager.itemStart( url );
  35851. // If cached is a promise, wait for it to resolve
  35852. if ( cached.then ) {
  35853. cached.then( imageBitmap => {
  35854. // check if there is an error for the cached promise
  35855. if ( _errorMap.has( cached ) === true ) {
  35856. if ( onError ) onError( _errorMap.get( cached ) );
  35857. scope.manager.itemError( url );
  35858. scope.manager.itemEnd( url );
  35859. } else {
  35860. if ( onLoad ) onLoad( imageBitmap );
  35861. scope.manager.itemEnd( url );
  35862. return imageBitmap;
  35863. }
  35864. } );
  35865. return;
  35866. }
  35867. // If cached is not a promise (i.e., it's already an imageBitmap)
  35868. setTimeout( function () {
  35869. if ( onLoad ) onLoad( cached );
  35870. scope.manager.itemEnd( url );
  35871. }, 0 );
  35872. return cached;
  35873. }
  35874. const fetchOptions = {};
  35875. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35876. fetchOptions.headers = this.requestHeader;
  35877. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35878. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35879. return res.blob();
  35880. } ).then( function ( blob ) {
  35881. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35882. } ).then( function ( imageBitmap ) {
  35883. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35884. if ( onLoad ) onLoad( imageBitmap );
  35885. scope.manager.itemEnd( url );
  35886. return imageBitmap;
  35887. } ).catch( function ( e ) {
  35888. if ( onError ) onError( e );
  35889. _errorMap.set( promise, e );
  35890. Cache.remove( `image-bitmap:${url}` );
  35891. scope.manager.itemError( url );
  35892. scope.manager.itemEnd( url );
  35893. } );
  35894. Cache.add( `image-bitmap:${url}`, promise );
  35895. scope.manager.itemStart( url );
  35896. }
  35897. /**
  35898. * Aborts ongoing fetch requests.
  35899. *
  35900. * @return {ImageBitmapLoader} A reference to this instance.
  35901. */
  35902. abort() {
  35903. this._abortController.abort();
  35904. this._abortController = new AbortController();
  35905. return this;
  35906. }
  35907. }
  35908. let _context;
  35909. /**
  35910. * Manages the global audio context in the engine.
  35911. *
  35912. * @hideconstructor
  35913. */
  35914. class AudioContext {
  35915. /**
  35916. * Returns the global native audio context.
  35917. *
  35918. * @return {AudioContext} The native audio context.
  35919. */
  35920. static getContext() {
  35921. if ( _context === undefined ) {
  35922. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35923. }
  35924. return _context;
  35925. }
  35926. /**
  35927. * Allows to set the global native audio context from outside.
  35928. *
  35929. * @param {AudioContext} value - The native context to set.
  35930. */
  35931. static setContext( value ) {
  35932. _context = value;
  35933. }
  35934. }
  35935. /**
  35936. * Class for loading audio buffers. Audios are internally
  35937. * loaded via {@link FileLoader}.
  35938. *
  35939. * ```js
  35940. * const audioListener = new THREE.AudioListener();
  35941. * const ambientSound = new THREE.Audio( audioListener );
  35942. *
  35943. * const loader = new THREE.AudioLoader();
  35944. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35945. *
  35946. * ambientSound.setBuffer( audioBuffer );
  35947. * ambientSound.play();
  35948. * ```
  35949. *
  35950. * @augments Loader
  35951. */
  35952. class AudioLoader extends Loader {
  35953. /**
  35954. * Constructs a new audio loader.
  35955. *
  35956. * @param {LoadingManager} [manager] - The loading manager.
  35957. */
  35958. constructor( manager ) {
  35959. super( manager );
  35960. }
  35961. /**
  35962. * Starts loading from the given URL and passes the loaded audio buffer
  35963. * to the `onLoad()` callback.
  35964. *
  35965. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35966. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35967. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35968. * @param {onErrorCallback} onError - Executed when errors occur.
  35969. */
  35970. load( url, onLoad, onProgress, onError ) {
  35971. const scope = this;
  35972. const loader = new FileLoader( this.manager );
  35973. loader.setResponseType( 'arraybuffer' );
  35974. loader.setPath( this.path );
  35975. loader.setRequestHeader( this.requestHeader );
  35976. loader.setWithCredentials( this.withCredentials );
  35977. loader.load( url, function ( buffer ) {
  35978. try {
  35979. // Create a copy of the buffer. The `decodeAudioData` method
  35980. // detaches the buffer when complete, preventing reuse.
  35981. const bufferCopy = buffer.slice( 0 );
  35982. const context = AudioContext.getContext();
  35983. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35984. onLoad( audioBuffer );
  35985. } ).catch( handleError );
  35986. } catch ( e ) {
  35987. handleError( e );
  35988. }
  35989. }, onProgress, onError );
  35990. function handleError( e ) {
  35991. if ( onError ) {
  35992. onError( e );
  35993. } else {
  35994. error( e );
  35995. }
  35996. scope.manager.itemError( url );
  35997. }
  35998. }
  35999. }
  36000. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36001. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36002. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36003. /**
  36004. * A special type of camera that uses two perspective cameras with
  36005. * stereoscopic projection. Can be used for rendering stereo effects
  36006. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36007. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36008. */
  36009. class StereoCamera {
  36010. /**
  36011. * Constructs a new stereo camera.
  36012. */
  36013. constructor() {
  36014. /**
  36015. * The type property is used for detecting the object type
  36016. * in context of serialization/deserialization.
  36017. *
  36018. * @type {string}
  36019. * @readonly
  36020. */
  36021. this.type = 'StereoCamera';
  36022. /**
  36023. * The aspect.
  36024. *
  36025. * @type {number}
  36026. * @default 1
  36027. */
  36028. this.aspect = 1;
  36029. /**
  36030. * The eye separation which represents the distance
  36031. * between the left and right camera.
  36032. *
  36033. * @type {number}
  36034. * @default 0.064
  36035. */
  36036. this.eyeSep = 0.064;
  36037. /**
  36038. * The camera representing the left eye. This is added to layer `1` so objects to be
  36039. * rendered by the left camera must also be added to this layer.
  36040. *
  36041. * @type {PerspectiveCamera}
  36042. */
  36043. this.cameraL = new PerspectiveCamera();
  36044. this.cameraL.layers.enable( 1 );
  36045. this.cameraL.matrixAutoUpdate = false;
  36046. /**
  36047. * The camera representing the right eye. This is added to layer `2` so objects to be
  36048. * rendered by the right camera must also be added to this layer.
  36049. *
  36050. * @type {PerspectiveCamera}
  36051. */
  36052. this.cameraR = new PerspectiveCamera();
  36053. this.cameraR.layers.enable( 2 );
  36054. this.cameraR.matrixAutoUpdate = false;
  36055. this._cache = {
  36056. focus: null,
  36057. fov: null,
  36058. aspect: null,
  36059. near: null,
  36060. far: null,
  36061. zoom: null,
  36062. eyeSep: null
  36063. };
  36064. }
  36065. /**
  36066. * Updates the stereo camera based on the given perspective camera.
  36067. *
  36068. * @param {PerspectiveCamera} camera - The perspective camera.
  36069. */
  36070. update( camera ) {
  36071. const cache = this._cache;
  36072. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36073. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36074. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36075. if ( needsUpdate ) {
  36076. cache.focus = camera.focus;
  36077. cache.fov = camera.fov;
  36078. cache.aspect = camera.aspect * this.aspect;
  36079. cache.near = camera.near;
  36080. cache.far = camera.far;
  36081. cache.zoom = camera.zoom;
  36082. cache.eyeSep = this.eyeSep;
  36083. // Off-axis stereoscopic effect based on
  36084. // http://paulbourke.net/stereographics/stereorender/
  36085. _projectionMatrix.copy( camera.projectionMatrix );
  36086. const eyeSepHalf = cache.eyeSep / 2;
  36087. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36088. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36089. let xmin, xmax;
  36090. // translate xOffset
  36091. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36092. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36093. // for left eye
  36094. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36095. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36096. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36097. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36098. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36099. // for right eye
  36100. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36101. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36102. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36103. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36104. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36105. }
  36106. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36107. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36108. }
  36109. }
  36110. /**
  36111. * This type of camera can be used in order to efficiently render a scene with a
  36112. * predefined set of cameras. This is an important performance aspect for
  36113. * rendering VR scenes.
  36114. *
  36115. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36116. * to define for each sub camera the `viewport` property which determines the
  36117. * part of the viewport that is rendered with this camera.
  36118. *
  36119. * @augments PerspectiveCamera
  36120. */
  36121. class ArrayCamera extends PerspectiveCamera {
  36122. /**
  36123. * Constructs a new array camera.
  36124. *
  36125. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36126. */
  36127. constructor( array = [] ) {
  36128. super();
  36129. /**
  36130. * This flag can be used for type testing.
  36131. *
  36132. * @type {boolean}
  36133. * @readonly
  36134. * @default true
  36135. */
  36136. this.isArrayCamera = true;
  36137. /**
  36138. * Whether this camera is used with multiview rendering or not.
  36139. *
  36140. * @type {boolean}
  36141. * @readonly
  36142. * @default false
  36143. */
  36144. this.isMultiViewCamera = false;
  36145. /**
  36146. * An array of perspective sub cameras.
  36147. *
  36148. * @type {Array<PerspectiveCamera>}
  36149. */
  36150. this.cameras = array;
  36151. }
  36152. }
  36153. /**
  36154. * Class for keeping track of time.
  36155. */
  36156. class Clock {
  36157. /**
  36158. * Constructs a new clock.
  36159. *
  36160. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36161. * `getDelta()` is called for the first time.
  36162. */
  36163. constructor( autoStart = true ) {
  36164. /**
  36165. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36166. * for the first time.
  36167. *
  36168. * @type {boolean}
  36169. * @default true
  36170. */
  36171. this.autoStart = autoStart;
  36172. /**
  36173. * Holds the time at which the clock's `start()` method was last called.
  36174. *
  36175. * @type {number}
  36176. * @default 0
  36177. */
  36178. this.startTime = 0;
  36179. /**
  36180. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36181. * `getDelta()` methods were last called.
  36182. *
  36183. * @type {number}
  36184. * @default 0
  36185. */
  36186. this.oldTime = 0;
  36187. /**
  36188. * Keeps track of the total time that the clock has been running.
  36189. *
  36190. * @type {number}
  36191. * @default 0
  36192. */
  36193. this.elapsedTime = 0;
  36194. /**
  36195. * Whether the clock is running or not.
  36196. *
  36197. * @type {boolean}
  36198. * @default true
  36199. */
  36200. this.running = false;
  36201. }
  36202. /**
  36203. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36204. * called by the class.
  36205. */
  36206. start() {
  36207. this.startTime = performance.now();
  36208. this.oldTime = this.startTime;
  36209. this.elapsedTime = 0;
  36210. this.running = true;
  36211. }
  36212. /**
  36213. * Stops the clock.
  36214. */
  36215. stop() {
  36216. this.getElapsedTime();
  36217. this.running = false;
  36218. this.autoStart = false;
  36219. }
  36220. /**
  36221. * Returns the elapsed time in seconds.
  36222. *
  36223. * @return {number} The elapsed time.
  36224. */
  36225. getElapsedTime() {
  36226. this.getDelta();
  36227. return this.elapsedTime;
  36228. }
  36229. /**
  36230. * Returns the delta time in seconds.
  36231. *
  36232. * @return {number} The delta time.
  36233. */
  36234. getDelta() {
  36235. let diff = 0;
  36236. if ( this.autoStart && ! this.running ) {
  36237. this.start();
  36238. return 0;
  36239. }
  36240. if ( this.running ) {
  36241. const newTime = performance.now();
  36242. diff = ( newTime - this.oldTime ) / 1000;
  36243. this.oldTime = newTime;
  36244. this.elapsedTime += diff;
  36245. }
  36246. return diff;
  36247. }
  36248. }
  36249. const _position$1 = /*@__PURE__*/ new Vector3();
  36250. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36251. const _scale$1 = /*@__PURE__*/ new Vector3();
  36252. const _forward = /*@__PURE__*/ new Vector3();
  36253. const _up = /*@__PURE__*/ new Vector3();
  36254. /**
  36255. * The class represents a virtual listener of the all positional and non-positional audio effects
  36256. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36257. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36258. *
  36259. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36260. * camera represents the 3D transformation of the listener.
  36261. *
  36262. * @augments Object3D
  36263. */
  36264. class AudioListener extends Object3D {
  36265. /**
  36266. * Constructs a new audio listener.
  36267. */
  36268. constructor() {
  36269. super();
  36270. this.type = 'AudioListener';
  36271. /**
  36272. * The native audio context.
  36273. *
  36274. * @type {AudioContext}
  36275. * @readonly
  36276. */
  36277. this.context = AudioContext.getContext();
  36278. /**
  36279. * The gain node used for volume control.
  36280. *
  36281. * @type {GainNode}
  36282. * @readonly
  36283. */
  36284. this.gain = this.context.createGain();
  36285. this.gain.connect( this.context.destination );
  36286. /**
  36287. * An optional filter.
  36288. *
  36289. * Defined via {@link AudioListener#setFilter}.
  36290. *
  36291. * @type {?AudioNode}
  36292. * @default null
  36293. * @readonly
  36294. */
  36295. this.filter = null;
  36296. /**
  36297. * Time delta values required for `linearRampToValueAtTime()` usage.
  36298. *
  36299. * @type {number}
  36300. * @default 0
  36301. * @readonly
  36302. */
  36303. this.timeDelta = 0;
  36304. // private
  36305. this._clock = new Clock();
  36306. }
  36307. /**
  36308. * Returns the listener's input node.
  36309. *
  36310. * This method is used by other audio nodes to connect to this listener.
  36311. *
  36312. * @return {GainNode} The input node.
  36313. */
  36314. getInput() {
  36315. return this.gain;
  36316. }
  36317. /**
  36318. * Removes the current filter from this listener.
  36319. *
  36320. * @return {AudioListener} A reference to this listener.
  36321. */
  36322. removeFilter() {
  36323. if ( this.filter !== null ) {
  36324. this.gain.disconnect( this.filter );
  36325. this.filter.disconnect( this.context.destination );
  36326. this.gain.connect( this.context.destination );
  36327. this.filter = null;
  36328. }
  36329. return this;
  36330. }
  36331. /**
  36332. * Returns the current set filter.
  36333. *
  36334. * @return {?AudioNode} The filter.
  36335. */
  36336. getFilter() {
  36337. return this.filter;
  36338. }
  36339. /**
  36340. * Sets the given filter to this listener.
  36341. *
  36342. * @param {AudioNode} value - The filter to set.
  36343. * @return {AudioListener} A reference to this listener.
  36344. */
  36345. setFilter( value ) {
  36346. if ( this.filter !== null ) {
  36347. this.gain.disconnect( this.filter );
  36348. this.filter.disconnect( this.context.destination );
  36349. } else {
  36350. this.gain.disconnect( this.context.destination );
  36351. }
  36352. this.filter = value;
  36353. this.gain.connect( this.filter );
  36354. this.filter.connect( this.context.destination );
  36355. return this;
  36356. }
  36357. /**
  36358. * Returns the applications master volume.
  36359. *
  36360. * @return {number} The master volume.
  36361. */
  36362. getMasterVolume() {
  36363. return this.gain.gain.value;
  36364. }
  36365. /**
  36366. * Sets the applications master volume. This volume setting affects
  36367. * all audio nodes in the scene.
  36368. *
  36369. * @param {number} value - The master volume to set.
  36370. * @return {AudioListener} A reference to this listener.
  36371. */
  36372. setMasterVolume( value ) {
  36373. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36374. return this;
  36375. }
  36376. updateMatrixWorld( force ) {
  36377. super.updateMatrixWorld( force );
  36378. const listener = this.context.listener;
  36379. this.timeDelta = this._clock.getDelta();
  36380. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36381. // the initial forward and up directions must be orthogonal
  36382. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36383. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36384. if ( listener.positionX ) {
  36385. // code path for Chrome (see #14393)
  36386. const endTime = this.context.currentTime + this.timeDelta;
  36387. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36388. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36389. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36390. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36391. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36392. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36393. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36394. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36395. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36396. } else {
  36397. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36398. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36399. }
  36400. }
  36401. }
  36402. /**
  36403. * Represents a non-positional ( global ) audio object.
  36404. *
  36405. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36406. *
  36407. * ```js
  36408. * // create an AudioListener and add it to the camera
  36409. * const listener = new THREE.AudioListener();
  36410. * camera.add( listener );
  36411. *
  36412. * // create a global audio source
  36413. * const sound = new THREE.Audio( listener );
  36414. *
  36415. * // load a sound and set it as the Audio object's buffer
  36416. * const audioLoader = new THREE.AudioLoader();
  36417. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36418. * sound.setBuffer( buffer );
  36419. * sound.setLoop( true );
  36420. * sound.setVolume( 0.5 );
  36421. * sound.play();
  36422. * });
  36423. * ```
  36424. *
  36425. * @augments Object3D
  36426. */
  36427. class Audio extends Object3D {
  36428. /**
  36429. * Constructs a new audio.
  36430. *
  36431. * @param {AudioListener} listener - The global audio listener.
  36432. */
  36433. constructor( listener ) {
  36434. super();
  36435. this.type = 'Audio';
  36436. /**
  36437. * The global audio listener.
  36438. *
  36439. * @type {AudioListener}
  36440. * @readonly
  36441. */
  36442. this.listener = listener;
  36443. /**
  36444. * The audio context.
  36445. *
  36446. * @type {AudioContext}
  36447. * @readonly
  36448. */
  36449. this.context = listener.context;
  36450. /**
  36451. * The gain node used for volume control.
  36452. *
  36453. * @type {GainNode}
  36454. * @readonly
  36455. */
  36456. this.gain = this.context.createGain();
  36457. this.gain.connect( listener.getInput() );
  36458. /**
  36459. * Whether to start playback automatically or not.
  36460. *
  36461. * @type {boolean}
  36462. * @default false
  36463. */
  36464. this.autoplay = false;
  36465. /**
  36466. * A reference to an audio buffer.
  36467. *
  36468. * Defined via {@link Audio#setBuffer}.
  36469. *
  36470. * @type {?AudioBuffer}
  36471. * @default null
  36472. * @readonly
  36473. */
  36474. this.buffer = null;
  36475. /**
  36476. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36477. * +/- 1200 is an octave.
  36478. *
  36479. * Defined via {@link Audio#setDetune}.
  36480. *
  36481. * @type {number}
  36482. * @default 0
  36483. * @readonly
  36484. */
  36485. this.detune = 0;
  36486. /**
  36487. * Whether the audio should loop or not.
  36488. *
  36489. * Defined via {@link Audio#setLoop}.
  36490. *
  36491. * @type {boolean}
  36492. * @default false
  36493. * @readonly
  36494. */
  36495. this.loop = false;
  36496. /**
  36497. * Defines where in the audio buffer the replay should
  36498. * start, in seconds.
  36499. *
  36500. * @type {number}
  36501. * @default 0
  36502. */
  36503. this.loopStart = 0;
  36504. /**
  36505. * Defines where in the audio buffer the replay should
  36506. * stop, in seconds.
  36507. *
  36508. * @type {number}
  36509. * @default 0
  36510. */
  36511. this.loopEnd = 0;
  36512. /**
  36513. * An offset to the time within the audio buffer the playback
  36514. * should begin, in seconds.
  36515. *
  36516. * @type {number}
  36517. * @default 0
  36518. */
  36519. this.offset = 0;
  36520. /**
  36521. * Overrides the default duration of the audio.
  36522. *
  36523. * @type {undefined|number}
  36524. * @default undefined
  36525. */
  36526. this.duration = undefined;
  36527. /**
  36528. * The playback speed.
  36529. *
  36530. * Defined via {@link Audio#setPlaybackRate}.
  36531. *
  36532. * @type {number}
  36533. * @readonly
  36534. * @default 1
  36535. */
  36536. this.playbackRate = 1;
  36537. /**
  36538. * Indicates whether the audio is playing or not.
  36539. *
  36540. * This flag will be automatically set when using {@link Audio#play},
  36541. * {@link Audio#pause}, {@link Audio#stop}.
  36542. *
  36543. * @type {boolean}
  36544. * @readonly
  36545. * @default false
  36546. */
  36547. this.isPlaying = false;
  36548. /**
  36549. * Indicates whether the audio playback can be controlled
  36550. * with method like {@link Audio#play} or {@link Audio#pause}.
  36551. *
  36552. * This flag will be automatically set when audio sources are
  36553. * defined.
  36554. *
  36555. * @type {boolean}
  36556. * @readonly
  36557. * @default true
  36558. */
  36559. this.hasPlaybackControl = true;
  36560. /**
  36561. * Holds a reference to the current audio source.
  36562. *
  36563. * The property is automatically by one of the `set*()` methods.
  36564. *
  36565. * @type {?AudioNode}
  36566. * @readonly
  36567. * @default null
  36568. */
  36569. this.source = null;
  36570. /**
  36571. * Defines the source type.
  36572. *
  36573. * The property is automatically set by one of the `set*()` methods.
  36574. *
  36575. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36576. * @readonly
  36577. * @default 'empty'
  36578. */
  36579. this.sourceType = 'empty';
  36580. this._startedAt = 0;
  36581. this._progress = 0;
  36582. this._connected = false;
  36583. /**
  36584. * Can be used to apply a variety of low-order filters to create
  36585. * more complex sound effects e.g. via `BiquadFilterNode`.
  36586. *
  36587. * The property is automatically set by {@link Audio#setFilters}.
  36588. *
  36589. * @type {Array<AudioNode>}
  36590. * @readonly
  36591. */
  36592. this.filters = [];
  36593. }
  36594. /**
  36595. * Returns the output audio node.
  36596. *
  36597. * @return {GainNode} The output node.
  36598. */
  36599. getOutput() {
  36600. return this.gain;
  36601. }
  36602. /**
  36603. * Sets the given audio node as the source of this instance.
  36604. *
  36605. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36606. *
  36607. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36608. * @return {Audio} A reference to this instance.
  36609. */
  36610. setNodeSource( audioNode ) {
  36611. this.hasPlaybackControl = false;
  36612. this.sourceType = 'audioNode';
  36613. this.source = audioNode;
  36614. this.connect();
  36615. return this;
  36616. }
  36617. /**
  36618. * Sets the given media element as the source of this instance.
  36619. *
  36620. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36621. *
  36622. * @param {HTMLMediaElement} mediaElement - The media element.
  36623. * @return {Audio} A reference to this instance.
  36624. */
  36625. setMediaElementSource( mediaElement ) {
  36626. this.hasPlaybackControl = false;
  36627. this.sourceType = 'mediaNode';
  36628. this.source = this.context.createMediaElementSource( mediaElement );
  36629. this.connect();
  36630. return this;
  36631. }
  36632. /**
  36633. * Sets the given media stream as the source of this instance.
  36634. *
  36635. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36636. *
  36637. * @param {MediaStream} mediaStream - The media stream.
  36638. * @return {Audio} A reference to this instance.
  36639. */
  36640. setMediaStreamSource( mediaStream ) {
  36641. this.hasPlaybackControl = false;
  36642. this.sourceType = 'mediaStreamNode';
  36643. this.source = this.context.createMediaStreamSource( mediaStream );
  36644. this.connect();
  36645. return this;
  36646. }
  36647. /**
  36648. * Sets the given audio buffer as the source of this instance.
  36649. *
  36650. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36651. *
  36652. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36653. * @return {Audio} A reference to this instance.
  36654. */
  36655. setBuffer( audioBuffer ) {
  36656. this.buffer = audioBuffer;
  36657. this.sourceType = 'buffer';
  36658. if ( this.autoplay ) this.play();
  36659. return this;
  36660. }
  36661. /**
  36662. * Starts the playback of the audio.
  36663. *
  36664. * Can only be used with compatible audio sources that allow playback control.
  36665. *
  36666. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36667. * @return {Audio|undefined} A reference to this instance.
  36668. */
  36669. play( delay = 0 ) {
  36670. if ( this.isPlaying === true ) {
  36671. warn( 'Audio: Audio is already playing.' );
  36672. return;
  36673. }
  36674. if ( this.hasPlaybackControl === false ) {
  36675. warn( 'Audio: this Audio has no playback control.' );
  36676. return;
  36677. }
  36678. this._startedAt = this.context.currentTime + delay;
  36679. const source = this.context.createBufferSource();
  36680. source.buffer = this.buffer;
  36681. source.loop = this.loop;
  36682. source.loopStart = this.loopStart;
  36683. source.loopEnd = this.loopEnd;
  36684. source.onended = this.onEnded.bind( this );
  36685. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36686. this.isPlaying = true;
  36687. this.source = source;
  36688. this.setDetune( this.detune );
  36689. this.setPlaybackRate( this.playbackRate );
  36690. return this.connect();
  36691. }
  36692. /**
  36693. * Pauses the playback of the audio.
  36694. *
  36695. * Can only be used with compatible audio sources that allow playback control.
  36696. *
  36697. * @return {Audio|undefined} A reference to this instance.
  36698. */
  36699. pause() {
  36700. if ( this.hasPlaybackControl === false ) {
  36701. warn( 'Audio: this Audio has no playback control.' );
  36702. return;
  36703. }
  36704. if ( this.isPlaying === true ) {
  36705. // update current progress
  36706. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36707. if ( this.loop === true ) {
  36708. // ensure _progress does not exceed duration with looped audios
  36709. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36710. }
  36711. this.source.stop();
  36712. this.source.onended = null;
  36713. this.isPlaying = false;
  36714. }
  36715. return this;
  36716. }
  36717. /**
  36718. * Stops the playback of the audio.
  36719. *
  36720. * Can only be used with compatible audio sources that allow playback control.
  36721. *
  36722. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36723. * @return {Audio|undefined} A reference to this instance.
  36724. */
  36725. stop( delay = 0 ) {
  36726. if ( this.hasPlaybackControl === false ) {
  36727. warn( 'Audio: this Audio has no playback control.' );
  36728. return;
  36729. }
  36730. this._progress = 0;
  36731. if ( this.source !== null ) {
  36732. this.source.stop( this.context.currentTime + delay );
  36733. this.source.onended = null;
  36734. }
  36735. this.isPlaying = false;
  36736. return this;
  36737. }
  36738. /**
  36739. * Connects to the audio source. This is used internally on
  36740. * initialisation and when setting / removing filters.
  36741. *
  36742. * @return {Audio} A reference to this instance.
  36743. */
  36744. connect() {
  36745. if ( this.filters.length > 0 ) {
  36746. this.source.connect( this.filters[ 0 ] );
  36747. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36748. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36749. }
  36750. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36751. } else {
  36752. this.source.connect( this.getOutput() );
  36753. }
  36754. this._connected = true;
  36755. return this;
  36756. }
  36757. /**
  36758. * Disconnects to the audio source. This is used internally on
  36759. * initialisation and when setting / removing filters.
  36760. *
  36761. * @return {Audio|undefined} A reference to this instance.
  36762. */
  36763. disconnect() {
  36764. if ( this._connected === false ) {
  36765. return;
  36766. }
  36767. if ( this.filters.length > 0 ) {
  36768. this.source.disconnect( this.filters[ 0 ] );
  36769. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36770. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36771. }
  36772. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36773. } else {
  36774. this.source.disconnect( this.getOutput() );
  36775. }
  36776. this._connected = false;
  36777. return this;
  36778. }
  36779. /**
  36780. * Returns the current set filters.
  36781. *
  36782. * @return {Array<AudioNode>} The list of filters.
  36783. */
  36784. getFilters() {
  36785. return this.filters;
  36786. }
  36787. /**
  36788. * Sets an array of filters and connects them with the audio source.
  36789. *
  36790. * @param {Array<AudioNode>} [value] - A list of filters.
  36791. * @return {Audio} A reference to this instance.
  36792. */
  36793. setFilters( value ) {
  36794. if ( ! value ) value = [];
  36795. if ( this._connected === true ) {
  36796. this.disconnect();
  36797. this.filters = value.slice();
  36798. this.connect();
  36799. } else {
  36800. this.filters = value.slice();
  36801. }
  36802. return this;
  36803. }
  36804. /**
  36805. * Defines the detuning of oscillation in cents.
  36806. *
  36807. * @param {number} value - The detuning of oscillation in cents.
  36808. * @return {Audio} A reference to this instance.
  36809. */
  36810. setDetune( value ) {
  36811. this.detune = value;
  36812. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36813. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36814. }
  36815. return this;
  36816. }
  36817. /**
  36818. * Returns the detuning of oscillation in cents.
  36819. *
  36820. * @return {number} The detuning of oscillation in cents.
  36821. */
  36822. getDetune() {
  36823. return this.detune;
  36824. }
  36825. /**
  36826. * Returns the first filter in the list of filters.
  36827. *
  36828. * @return {AudioNode|undefined} The first filter in the list of filters.
  36829. */
  36830. getFilter() {
  36831. return this.getFilters()[ 0 ];
  36832. }
  36833. /**
  36834. * Applies a single filter node to the audio.
  36835. *
  36836. * @param {AudioNode} [filter] - The filter to set.
  36837. * @return {Audio} A reference to this instance.
  36838. */
  36839. setFilter( filter ) {
  36840. return this.setFilters( filter ? [ filter ] : [] );
  36841. }
  36842. /**
  36843. * Sets the playback rate.
  36844. *
  36845. * Can only be used with compatible audio sources that allow playback control.
  36846. *
  36847. * @param {number} [value] - The playback rate to set.
  36848. * @return {Audio|undefined} A reference to this instance.
  36849. */
  36850. setPlaybackRate( value ) {
  36851. if ( this.hasPlaybackControl === false ) {
  36852. warn( 'Audio: this Audio has no playback control.' );
  36853. return;
  36854. }
  36855. this.playbackRate = value;
  36856. if ( this.isPlaying === true ) {
  36857. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36858. }
  36859. return this;
  36860. }
  36861. /**
  36862. * Returns the current playback rate.
  36863. * @return {number} The playback rate.
  36864. */
  36865. getPlaybackRate() {
  36866. return this.playbackRate;
  36867. }
  36868. /**
  36869. * Automatically called when playback finished.
  36870. */
  36871. onEnded() {
  36872. this.isPlaying = false;
  36873. this._progress = 0;
  36874. }
  36875. /**
  36876. * Returns the loop flag.
  36877. *
  36878. * Can only be used with compatible audio sources that allow playback control.
  36879. *
  36880. * @return {boolean} Whether the audio should loop or not.
  36881. */
  36882. getLoop() {
  36883. if ( this.hasPlaybackControl === false ) {
  36884. warn( 'Audio: this Audio has no playback control.' );
  36885. return false;
  36886. }
  36887. return this.loop;
  36888. }
  36889. /**
  36890. * Sets the loop flag.
  36891. *
  36892. * Can only be used with compatible audio sources that allow playback control.
  36893. *
  36894. * @param {boolean} value - Whether the audio should loop or not.
  36895. * @return {Audio|undefined} A reference to this instance.
  36896. */
  36897. setLoop( value ) {
  36898. if ( this.hasPlaybackControl === false ) {
  36899. warn( 'Audio: this Audio has no playback control.' );
  36900. return;
  36901. }
  36902. this.loop = value;
  36903. if ( this.isPlaying === true ) {
  36904. this.source.loop = this.loop;
  36905. }
  36906. return this;
  36907. }
  36908. /**
  36909. * Sets the loop start value which defines where in the audio buffer the replay should
  36910. * start, in seconds.
  36911. *
  36912. * @param {number} value - The loop start value.
  36913. * @return {Audio} A reference to this instance.
  36914. */
  36915. setLoopStart( value ) {
  36916. this.loopStart = value;
  36917. return this;
  36918. }
  36919. /**
  36920. * Sets the loop end value which defines where in the audio buffer the replay should
  36921. * stop, in seconds.
  36922. *
  36923. * @param {number} value - The loop end value.
  36924. * @return {Audio} A reference to this instance.
  36925. */
  36926. setLoopEnd( value ) {
  36927. this.loopEnd = value;
  36928. return this;
  36929. }
  36930. /**
  36931. * Returns the volume.
  36932. *
  36933. * @return {number} The volume.
  36934. */
  36935. getVolume() {
  36936. return this.gain.gain.value;
  36937. }
  36938. /**
  36939. * Sets the volume.
  36940. *
  36941. * @param {number} value - The volume to set.
  36942. * @return {Audio} A reference to this instance.
  36943. */
  36944. setVolume( value ) {
  36945. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36946. return this;
  36947. }
  36948. copy( source, recursive ) {
  36949. super.copy( source, recursive );
  36950. if ( source.sourceType !== 'buffer' ) {
  36951. warn( 'Audio: Audio source type cannot be copied.' );
  36952. return this;
  36953. }
  36954. this.autoplay = source.autoplay;
  36955. this.buffer = source.buffer;
  36956. this.detune = source.detune;
  36957. this.loop = source.loop;
  36958. this.loopStart = source.loopStart;
  36959. this.loopEnd = source.loopEnd;
  36960. this.offset = source.offset;
  36961. this.duration = source.duration;
  36962. this.playbackRate = source.playbackRate;
  36963. this.hasPlaybackControl = source.hasPlaybackControl;
  36964. this.sourceType = source.sourceType;
  36965. this.filters = source.filters.slice();
  36966. return this;
  36967. }
  36968. clone( recursive ) {
  36969. return new this.constructor( this.listener ).copy( this, recursive );
  36970. }
  36971. }
  36972. const _position = /*@__PURE__*/ new Vector3();
  36973. const _quaternion = /*@__PURE__*/ new Quaternion();
  36974. const _scale = /*@__PURE__*/ new Vector3();
  36975. const _orientation = /*@__PURE__*/ new Vector3();
  36976. /**
  36977. * Represents a positional audio object.
  36978. *
  36979. * ```js
  36980. * // create an AudioListener and add it to the camera
  36981. * const listener = new THREE.AudioListener();
  36982. * camera.add( listener );
  36983. *
  36984. * // create the PositionalAudio object (passing in the listener)
  36985. * const sound = new THREE.PositionalAudio( listener );
  36986. *
  36987. * // load a sound and set it as the PositionalAudio object's buffer
  36988. * const audioLoader = new THREE.AudioLoader();
  36989. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36990. * sound.setBuffer( buffer );
  36991. * sound.setRefDistance( 20 );
  36992. * sound.play();
  36993. * });
  36994. *
  36995. * // create an object for the sound to play from
  36996. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36997. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36998. * const mesh = new THREE.Mesh( sphere, material );
  36999. * scene.add( mesh );
  37000. *
  37001. * // finally add the sound to the mesh
  37002. * mesh.add( sound );
  37003. *
  37004. * @augments Audio
  37005. */
  37006. class PositionalAudio extends Audio {
  37007. /**
  37008. * Constructs a positional audio.
  37009. *
  37010. * @param {AudioListener} listener - The global audio listener.
  37011. */
  37012. constructor( listener ) {
  37013. super( listener );
  37014. /**
  37015. * The panner node represents the location, direction, and behavior of an audio
  37016. * source in 3D space.
  37017. *
  37018. * @type {PannerNode}
  37019. * @readonly
  37020. */
  37021. this.panner = this.context.createPanner();
  37022. this.panner.panningModel = 'HRTF';
  37023. this.panner.connect( this.gain );
  37024. }
  37025. connect() {
  37026. super.connect();
  37027. this.panner.connect( this.gain );
  37028. return this;
  37029. }
  37030. disconnect() {
  37031. super.disconnect();
  37032. this.panner.disconnect( this.gain );
  37033. return this;
  37034. }
  37035. getOutput() {
  37036. return this.panner;
  37037. }
  37038. /**
  37039. * Returns the current reference distance.
  37040. *
  37041. * @return {number} The reference distance.
  37042. */
  37043. getRefDistance() {
  37044. return this.panner.refDistance;
  37045. }
  37046. /**
  37047. * Defines the reference distance for reducing volume as the audio source moves
  37048. * further from the listener – i.e. the distance at which the volume reduction
  37049. * starts taking effect.
  37050. *
  37051. * @param {number} value - The reference distance to set.
  37052. * @return {PositionalAudio} A reference to this instance.
  37053. */
  37054. setRefDistance( value ) {
  37055. this.panner.refDistance = value;
  37056. return this;
  37057. }
  37058. /**
  37059. * Returns the current rolloff factor.
  37060. *
  37061. * @return {number} The rolloff factor.
  37062. */
  37063. getRolloffFactor() {
  37064. return this.panner.rolloffFactor;
  37065. }
  37066. /**
  37067. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37068. *
  37069. * @param {number} value - The rolloff factor.
  37070. * @return {PositionalAudio} A reference to this instance.
  37071. */
  37072. setRolloffFactor( value ) {
  37073. this.panner.rolloffFactor = value;
  37074. return this;
  37075. }
  37076. /**
  37077. * Returns the current distance model.
  37078. *
  37079. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37080. */
  37081. getDistanceModel() {
  37082. return this.panner.distanceModel;
  37083. }
  37084. /**
  37085. * Defines which algorithm to use to reduce the volume of the audio source
  37086. * as it moves away from the listener.
  37087. *
  37088. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37089. * for more details.
  37090. *
  37091. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37092. * @return {PositionalAudio} A reference to this instance.
  37093. */
  37094. setDistanceModel( value ) {
  37095. this.panner.distanceModel = value;
  37096. return this;
  37097. }
  37098. /**
  37099. * Returns the current max distance.
  37100. *
  37101. * @return {number} The max distance.
  37102. */
  37103. getMaxDistance() {
  37104. return this.panner.maxDistance;
  37105. }
  37106. /**
  37107. * Defines the maximum distance between the audio source and the listener,
  37108. * after which the volume is not reduced any further.
  37109. *
  37110. * This value is used only by the `linear` distance model.
  37111. *
  37112. * @param {number} value - The max distance.
  37113. * @return {PositionalAudio} A reference to this instance.
  37114. */
  37115. setMaxDistance( value ) {
  37116. this.panner.maxDistance = value;
  37117. return this;
  37118. }
  37119. /**
  37120. * Sets the directional cone in which the audio can be listened.
  37121. *
  37122. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37123. * @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.
  37124. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37125. * @return {PositionalAudio} A reference to this instance.
  37126. */
  37127. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37128. this.panner.coneInnerAngle = coneInnerAngle;
  37129. this.panner.coneOuterAngle = coneOuterAngle;
  37130. this.panner.coneOuterGain = coneOuterGain;
  37131. return this;
  37132. }
  37133. updateMatrixWorld( force ) {
  37134. super.updateMatrixWorld( force );
  37135. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37136. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37137. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37138. const panner = this.panner;
  37139. if ( panner.positionX ) {
  37140. // code path for Chrome and Firefox (see #14393)
  37141. const endTime = this.context.currentTime + this.listener.timeDelta;
  37142. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37143. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37144. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37145. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37146. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37147. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37148. } else {
  37149. panner.setPosition( _position.x, _position.y, _position.z );
  37150. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37151. }
  37152. }
  37153. }
  37154. /**
  37155. * This class can be used to analyse audio data.
  37156. *
  37157. * ```js
  37158. * // create an AudioListener and add it to the camera
  37159. * const listener = new THREE.AudioListener();
  37160. * camera.add( listener );
  37161. *
  37162. * // create an Audio source
  37163. * const sound = new THREE.Audio( listener );
  37164. *
  37165. * // load a sound and set it as the Audio object's buffer
  37166. * const audioLoader = new THREE.AudioLoader();
  37167. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37168. * sound.setBuffer( buffer );
  37169. * sound.setLoop(true);
  37170. * sound.setVolume(0.5);
  37171. * sound.play();
  37172. * });
  37173. *
  37174. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37175. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37176. *
  37177. * // get the average frequency of the sound
  37178. * const data = analyser.getAverageFrequency();
  37179. * ```
  37180. */
  37181. class AudioAnalyser {
  37182. /**
  37183. * Constructs a new audio analyzer.
  37184. *
  37185. * @param {Audio} audio - The audio to analyze.
  37186. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37187. */
  37188. constructor( audio, fftSize = 2048 ) {
  37189. /**
  37190. * The global audio listener.
  37191. *
  37192. * @type {AnalyserNode}
  37193. */
  37194. this.analyser = audio.context.createAnalyser();
  37195. this.analyser.fftSize = fftSize;
  37196. /**
  37197. * Holds the analyzed data.
  37198. *
  37199. * @type {Uint8Array}
  37200. */
  37201. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37202. audio.getOutput().connect( this.analyser );
  37203. }
  37204. /**
  37205. * Returns an array with frequency data of the audio.
  37206. *
  37207. * Each item in the array represents the decibel value for a specific frequency.
  37208. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37209. * For example, for 48000 sample rate, the last item of the array will represent
  37210. * the decibel value for 24000 Hz.
  37211. *
  37212. * @return {Uint8Array} The frequency data.
  37213. */
  37214. getFrequencyData() {
  37215. this.analyser.getByteFrequencyData( this.data );
  37216. return this.data;
  37217. }
  37218. /**
  37219. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37220. *
  37221. * @return {number} The average frequency.
  37222. */
  37223. getAverageFrequency() {
  37224. let value = 0;
  37225. const data = this.getFrequencyData();
  37226. for ( let i = 0; i < data.length; i ++ ) {
  37227. value += data[ i ];
  37228. }
  37229. return value / data.length;
  37230. }
  37231. }
  37232. /**
  37233. * Buffered scene graph property that allows weighted accumulation; used internally.
  37234. */
  37235. class PropertyMixer {
  37236. /**
  37237. * Constructs a new property mixer.
  37238. *
  37239. * @param {PropertyBinding} binding - The property binding.
  37240. * @param {string} typeName - The keyframe track type name.
  37241. * @param {number} valueSize - The keyframe track value size.
  37242. */
  37243. constructor( binding, typeName, valueSize ) {
  37244. /**
  37245. * The property binding.
  37246. *
  37247. * @type {PropertyBinding}
  37248. */
  37249. this.binding = binding;
  37250. /**
  37251. * The keyframe track value size.
  37252. *
  37253. * @type {number}
  37254. */
  37255. this.valueSize = valueSize;
  37256. let mixFunction,
  37257. mixFunctionAdditive,
  37258. setIdentity;
  37259. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37260. //
  37261. // interpolators can use .buffer as their .result
  37262. // the data then goes to 'incoming'
  37263. //
  37264. // 'accu0' and 'accu1' are used frame-interleaved for
  37265. // the cumulative result and are compared to detect
  37266. // changes
  37267. //
  37268. // 'orig' stores the original state of the property
  37269. //
  37270. // 'add' is used for additive cumulative results
  37271. //
  37272. // 'work' is optional and is only present for quaternion types. It is used
  37273. // to store intermediate quaternion multiplication results
  37274. switch ( typeName ) {
  37275. case 'quaternion':
  37276. mixFunction = this._slerp;
  37277. mixFunctionAdditive = this._slerpAdditive;
  37278. setIdentity = this._setAdditiveIdentityQuaternion;
  37279. this.buffer = new Float64Array( valueSize * 6 );
  37280. this._workIndex = 5;
  37281. break;
  37282. case 'string':
  37283. case 'bool':
  37284. mixFunction = this._select;
  37285. // Use the regular mix function and for additive on these types,
  37286. // additive is not relevant for non-numeric types
  37287. mixFunctionAdditive = this._select;
  37288. setIdentity = this._setAdditiveIdentityOther;
  37289. this.buffer = new Array( valueSize * 5 );
  37290. break;
  37291. default:
  37292. mixFunction = this._lerp;
  37293. mixFunctionAdditive = this._lerpAdditive;
  37294. setIdentity = this._setAdditiveIdentityNumeric;
  37295. this.buffer = new Float64Array( valueSize * 5 );
  37296. }
  37297. this._mixBufferRegion = mixFunction;
  37298. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37299. this._setIdentity = setIdentity;
  37300. this._origIndex = 3;
  37301. this._addIndex = 4;
  37302. /**
  37303. * TODO
  37304. *
  37305. * @type {number}
  37306. * @default 0
  37307. */
  37308. this.cumulativeWeight = 0;
  37309. /**
  37310. * TODO
  37311. *
  37312. * @type {number}
  37313. * @default 0
  37314. */
  37315. this.cumulativeWeightAdditive = 0;
  37316. /**
  37317. * TODO
  37318. *
  37319. * @type {number}
  37320. * @default 0
  37321. */
  37322. this.useCount = 0;
  37323. /**
  37324. * TODO
  37325. *
  37326. * @type {number}
  37327. * @default 0
  37328. */
  37329. this.referenceCount = 0;
  37330. }
  37331. /**
  37332. * Accumulates data in the `incoming` region into `accu<i>`.
  37333. *
  37334. * @param {number} accuIndex - The accumulation index.
  37335. * @param {number} weight - The weight.
  37336. */
  37337. accumulate( accuIndex, weight ) {
  37338. // note: happily accumulating nothing when weight = 0, the caller knows
  37339. // the weight and shouldn't have made the call in the first place
  37340. const buffer = this.buffer,
  37341. stride = this.valueSize,
  37342. offset = accuIndex * stride + stride;
  37343. let currentWeight = this.cumulativeWeight;
  37344. if ( currentWeight === 0 ) {
  37345. // accuN := incoming * weight
  37346. for ( let i = 0; i !== stride; ++ i ) {
  37347. buffer[ offset + i ] = buffer[ i ];
  37348. }
  37349. currentWeight = weight;
  37350. } else {
  37351. // accuN := accuN + incoming * weight
  37352. currentWeight += weight;
  37353. const mix = weight / currentWeight;
  37354. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37355. }
  37356. this.cumulativeWeight = currentWeight;
  37357. }
  37358. /**
  37359. * Accumulates data in the `incoming` region into `add`.
  37360. *
  37361. * @param {number} weight - The weight.
  37362. */
  37363. accumulateAdditive( weight ) {
  37364. const buffer = this.buffer,
  37365. stride = this.valueSize,
  37366. offset = stride * this._addIndex;
  37367. if ( this.cumulativeWeightAdditive === 0 ) {
  37368. // add = identity
  37369. this._setIdentity();
  37370. }
  37371. // add := add + incoming * weight
  37372. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37373. this.cumulativeWeightAdditive += weight;
  37374. }
  37375. /**
  37376. * Applies the state of `accu<i>` to the binding when accus differ.
  37377. *
  37378. * @param {number} accuIndex - The accumulation index.
  37379. */
  37380. apply( accuIndex ) {
  37381. const stride = this.valueSize,
  37382. buffer = this.buffer,
  37383. offset = accuIndex * stride + stride,
  37384. weight = this.cumulativeWeight,
  37385. weightAdditive = this.cumulativeWeightAdditive,
  37386. binding = this.binding;
  37387. this.cumulativeWeight = 0;
  37388. this.cumulativeWeightAdditive = 0;
  37389. if ( weight < 1 ) {
  37390. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37391. const originalValueOffset = stride * this._origIndex;
  37392. this._mixBufferRegion(
  37393. buffer, offset, originalValueOffset, 1 - weight, stride );
  37394. }
  37395. if ( weightAdditive > 0 ) {
  37396. // accuN := accuN + additive accuN
  37397. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37398. }
  37399. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37400. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37401. // value has changed -> update scene graph
  37402. binding.setValue( buffer, offset );
  37403. break;
  37404. }
  37405. }
  37406. }
  37407. /**
  37408. * Remembers the state of the bound property and copy it to both accus.
  37409. */
  37410. saveOriginalState() {
  37411. const binding = this.binding;
  37412. const buffer = this.buffer,
  37413. stride = this.valueSize,
  37414. originalValueOffset = stride * this._origIndex;
  37415. binding.getValue( buffer, originalValueOffset );
  37416. // accu[0..1] := orig -- initially detect changes against the original
  37417. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37418. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37419. }
  37420. // Add to identity for additive
  37421. this._setIdentity();
  37422. this.cumulativeWeight = 0;
  37423. this.cumulativeWeightAdditive = 0;
  37424. }
  37425. /**
  37426. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37427. */
  37428. restoreOriginalState() {
  37429. const originalValueOffset = this.valueSize * 3;
  37430. this.binding.setValue( this.buffer, originalValueOffset );
  37431. }
  37432. // internals
  37433. _setAdditiveIdentityNumeric() {
  37434. const startIndex = this._addIndex * this.valueSize;
  37435. const endIndex = startIndex + this.valueSize;
  37436. for ( let i = startIndex; i < endIndex; i ++ ) {
  37437. this.buffer[ i ] = 0;
  37438. }
  37439. }
  37440. _setAdditiveIdentityQuaternion() {
  37441. this._setAdditiveIdentityNumeric();
  37442. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37443. }
  37444. _setAdditiveIdentityOther() {
  37445. const startIndex = this._origIndex * this.valueSize;
  37446. const targetIndex = this._addIndex * this.valueSize;
  37447. for ( let i = 0; i < this.valueSize; i ++ ) {
  37448. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37449. }
  37450. }
  37451. // mix functions
  37452. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37453. if ( t >= 0.5 ) {
  37454. for ( let i = 0; i !== stride; ++ i ) {
  37455. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37456. }
  37457. }
  37458. }
  37459. _slerp( buffer, dstOffset, srcOffset, t ) {
  37460. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37461. }
  37462. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37463. const workOffset = this._workIndex * stride;
  37464. // Store result in intermediate buffer offset
  37465. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37466. // Slerp to the intermediate result
  37467. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37468. }
  37469. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37470. const s = 1 - t;
  37471. for ( let i = 0; i !== stride; ++ i ) {
  37472. const j = dstOffset + i;
  37473. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37474. }
  37475. }
  37476. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37477. for ( let i = 0; i !== stride; ++ i ) {
  37478. const j = dstOffset + i;
  37479. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37480. }
  37481. }
  37482. }
  37483. // Characters [].:/ are reserved for track binding syntax.
  37484. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37485. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37486. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37487. // only latin characters, and the unicode \p{L} is not yet supported. So
  37488. // instead, we exclude reserved characters and match everything else.
  37489. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37490. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37491. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37492. // be matched to parse the rest of the track name.
  37493. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37494. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37495. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37496. // Object on target node, and accessor. May not contain reserved
  37497. // characters. Accessor may contain any character except closing bracket.
  37498. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37499. // Property and accessor. May not contain reserved characters. Accessor may
  37500. // contain any non-bracket characters.
  37501. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37502. const _trackRe = new RegExp( ''
  37503. + '^'
  37504. + _directoryRe
  37505. + _nodeRe
  37506. + _objectRe
  37507. + _propertyRe
  37508. + '$'
  37509. );
  37510. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37511. class Composite {
  37512. constructor( targetGroup, path, optionalParsedPath ) {
  37513. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37514. this._targetGroup = targetGroup;
  37515. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37516. }
  37517. getValue( array, offset ) {
  37518. this.bind(); // bind all binding
  37519. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37520. binding = this._bindings[ firstValidIndex ];
  37521. // and only call .getValue on the first
  37522. if ( binding !== undefined ) binding.getValue( array, offset );
  37523. }
  37524. setValue( array, offset ) {
  37525. const bindings = this._bindings;
  37526. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37527. bindings[ i ].setValue( array, offset );
  37528. }
  37529. }
  37530. bind() {
  37531. const bindings = this._bindings;
  37532. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37533. bindings[ i ].bind();
  37534. }
  37535. }
  37536. unbind() {
  37537. const bindings = this._bindings;
  37538. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37539. bindings[ i ].unbind();
  37540. }
  37541. }
  37542. }
  37543. // Note: This class uses a State pattern on a per-method basis:
  37544. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37545. // prototype version of these methods with one that represents
  37546. // the bound state. When the property is not found, the methods
  37547. // become no-ops.
  37548. /**
  37549. * This holds a reference to a real property in the scene graph; used internally.
  37550. */
  37551. class PropertyBinding {
  37552. /**
  37553. * Constructs a new property binding.
  37554. *
  37555. * @param {Object} rootNode - The root node.
  37556. * @param {string} path - The path.
  37557. * @param {?Object} [parsedPath] - The parsed path.
  37558. */
  37559. constructor( rootNode, path, parsedPath ) {
  37560. /**
  37561. * The object path to the animated property.
  37562. *
  37563. * @type {string}
  37564. */
  37565. this.path = path;
  37566. /**
  37567. * An object holding information about the path.
  37568. *
  37569. * @type {Object}
  37570. */
  37571. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37572. /**
  37573. * The object owns the animated property.
  37574. *
  37575. * @type {?Object}
  37576. */
  37577. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37578. /**
  37579. * The root node.
  37580. *
  37581. * @type {Object3D|Skeleton}
  37582. */
  37583. this.rootNode = rootNode;
  37584. // initial state of these methods that calls 'bind'
  37585. this.getValue = this._getValue_unbound;
  37586. this.setValue = this._setValue_unbound;
  37587. }
  37588. /**
  37589. * Factory method for creating a property binding from the given parameters.
  37590. *
  37591. * @static
  37592. * @param {Object} root - The root node.
  37593. * @param {string} path - The path.
  37594. * @param {?Object} [parsedPath] - The parsed path.
  37595. * @return {PropertyBinding|Composite} The created property binding or composite.
  37596. */
  37597. static create( root, path, parsedPath ) {
  37598. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37599. return new PropertyBinding( root, path, parsedPath );
  37600. } else {
  37601. return new PropertyBinding.Composite( root, path, parsedPath );
  37602. }
  37603. }
  37604. /**
  37605. * Replaces spaces with underscores and removes unsupported characters from
  37606. * node names, to ensure compatibility with parseTrackName().
  37607. *
  37608. * @param {string} name - Node name to be sanitized.
  37609. * @return {string} The sanitized node name.
  37610. */
  37611. static sanitizeNodeName( name ) {
  37612. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37613. }
  37614. /**
  37615. * Parses the given track name (an object path to an animated property) and
  37616. * returns an object with information about the path. Matches strings in the following forms:
  37617. *
  37618. * - nodeName.property
  37619. * - nodeName.property[accessor]
  37620. * - nodeName.material.property[accessor]
  37621. * - uuid.property[accessor]
  37622. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37623. * - parentName/nodeName.property
  37624. * - parentName/parentName/nodeName.property[index]
  37625. * - .bone[Armature.DEF_cog].position
  37626. * - scene:helium_balloon_model:helium_balloon_model.position
  37627. *
  37628. * @static
  37629. * @param {string} trackName - The track name to parse.
  37630. * @return {Object} The parsed track name as an object.
  37631. */
  37632. static parseTrackName( trackName ) {
  37633. const matches = _trackRe.exec( trackName );
  37634. if ( matches === null ) {
  37635. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37636. }
  37637. const results = {
  37638. // directoryName: matches[ 1 ], // (tschw) currently unused
  37639. nodeName: matches[ 2 ],
  37640. objectName: matches[ 3 ],
  37641. objectIndex: matches[ 4 ],
  37642. propertyName: matches[ 5 ], // required
  37643. propertyIndex: matches[ 6 ]
  37644. };
  37645. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37646. if ( lastDot !== undefined && lastDot !== -1 ) {
  37647. const objectName = results.nodeName.substring( lastDot + 1 );
  37648. // Object names must be checked against an allowlist. Otherwise, there
  37649. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37650. // 'bar' could be the objectName, or part of a nodeName (which can
  37651. // include '.' characters).
  37652. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37653. results.nodeName = results.nodeName.substring( 0, lastDot );
  37654. results.objectName = objectName;
  37655. }
  37656. }
  37657. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37658. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37659. }
  37660. return results;
  37661. }
  37662. /**
  37663. * Searches for a node in the hierarchy of the given root object by the given
  37664. * node name.
  37665. *
  37666. * @static
  37667. * @param {Object} root - The root object.
  37668. * @param {string|number} nodeName - The name of the node.
  37669. * @return {?Object} The found node. Returns `null` if no object was found.
  37670. */
  37671. static findNode( root, nodeName ) {
  37672. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37673. return root;
  37674. }
  37675. // search into skeleton bones.
  37676. if ( root.skeleton ) {
  37677. const bone = root.skeleton.getBoneByName( nodeName );
  37678. if ( bone !== undefined ) {
  37679. return bone;
  37680. }
  37681. }
  37682. // search into node subtree.
  37683. if ( root.children ) {
  37684. const searchNodeSubtree = function ( children ) {
  37685. for ( let i = 0; i < children.length; i ++ ) {
  37686. const childNode = children[ i ];
  37687. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37688. return childNode;
  37689. }
  37690. const result = searchNodeSubtree( childNode.children );
  37691. if ( result ) return result;
  37692. }
  37693. return null;
  37694. };
  37695. const subTreeNode = searchNodeSubtree( root.children );
  37696. if ( subTreeNode ) {
  37697. return subTreeNode;
  37698. }
  37699. }
  37700. return null;
  37701. }
  37702. // these are used to "bind" a nonexistent property
  37703. _getValue_unavailable() {}
  37704. _setValue_unavailable() {}
  37705. // Getters
  37706. _getValue_direct( buffer, offset ) {
  37707. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37708. }
  37709. _getValue_array( buffer, offset ) {
  37710. const source = this.resolvedProperty;
  37711. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37712. buffer[ offset ++ ] = source[ i ];
  37713. }
  37714. }
  37715. _getValue_arrayElement( buffer, offset ) {
  37716. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37717. }
  37718. _getValue_toArray( buffer, offset ) {
  37719. this.resolvedProperty.toArray( buffer, offset );
  37720. }
  37721. // Direct
  37722. _setValue_direct( buffer, offset ) {
  37723. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37724. }
  37725. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37726. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37727. this.targetObject.needsUpdate = true;
  37728. }
  37729. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37730. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37731. this.targetObject.matrixWorldNeedsUpdate = true;
  37732. }
  37733. // EntireArray
  37734. _setValue_array( buffer, offset ) {
  37735. const dest = this.resolvedProperty;
  37736. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37737. dest[ i ] = buffer[ offset ++ ];
  37738. }
  37739. }
  37740. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37741. const dest = this.resolvedProperty;
  37742. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37743. dest[ i ] = buffer[ offset ++ ];
  37744. }
  37745. this.targetObject.needsUpdate = true;
  37746. }
  37747. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37748. const dest = this.resolvedProperty;
  37749. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37750. dest[ i ] = buffer[ offset ++ ];
  37751. }
  37752. this.targetObject.matrixWorldNeedsUpdate = true;
  37753. }
  37754. // ArrayElement
  37755. _setValue_arrayElement( buffer, offset ) {
  37756. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37757. }
  37758. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37759. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37760. this.targetObject.needsUpdate = true;
  37761. }
  37762. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37763. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37764. this.targetObject.matrixWorldNeedsUpdate = true;
  37765. }
  37766. // HasToFromArray
  37767. _setValue_fromArray( buffer, offset ) {
  37768. this.resolvedProperty.fromArray( buffer, offset );
  37769. }
  37770. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37771. this.resolvedProperty.fromArray( buffer, offset );
  37772. this.targetObject.needsUpdate = true;
  37773. }
  37774. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37775. this.resolvedProperty.fromArray( buffer, offset );
  37776. this.targetObject.matrixWorldNeedsUpdate = true;
  37777. }
  37778. _getValue_unbound( targetArray, offset ) {
  37779. this.bind();
  37780. this.getValue( targetArray, offset );
  37781. }
  37782. _setValue_unbound( sourceArray, offset ) {
  37783. this.bind();
  37784. this.setValue( sourceArray, offset );
  37785. }
  37786. /**
  37787. * Creates a getter / setter pair for the property tracked by this binding.
  37788. */
  37789. bind() {
  37790. let targetObject = this.node;
  37791. const parsedPath = this.parsedPath;
  37792. const objectName = parsedPath.objectName;
  37793. const propertyName = parsedPath.propertyName;
  37794. let propertyIndex = parsedPath.propertyIndex;
  37795. if ( ! targetObject ) {
  37796. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37797. this.node = targetObject;
  37798. }
  37799. // set fail state so we can just 'return' on error
  37800. this.getValue = this._getValue_unavailable;
  37801. this.setValue = this._setValue_unavailable;
  37802. // ensure there is a value node
  37803. if ( ! targetObject ) {
  37804. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37805. return;
  37806. }
  37807. if ( objectName ) {
  37808. let objectIndex = parsedPath.objectIndex;
  37809. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37810. switch ( objectName ) {
  37811. case 'materials':
  37812. if ( ! targetObject.material ) {
  37813. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37814. return;
  37815. }
  37816. if ( ! targetObject.material.materials ) {
  37817. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37818. return;
  37819. }
  37820. targetObject = targetObject.material.materials;
  37821. break;
  37822. case 'bones':
  37823. if ( ! targetObject.skeleton ) {
  37824. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37825. return;
  37826. }
  37827. // potential future optimization: skip this if propertyIndex is already an integer
  37828. // and convert the integer string to a true integer.
  37829. targetObject = targetObject.skeleton.bones;
  37830. // support resolving morphTarget names into indices.
  37831. for ( let i = 0; i < targetObject.length; i ++ ) {
  37832. if ( targetObject[ i ].name === objectIndex ) {
  37833. objectIndex = i;
  37834. break;
  37835. }
  37836. }
  37837. break;
  37838. case 'map':
  37839. if ( 'map' in targetObject ) {
  37840. targetObject = targetObject.map;
  37841. break;
  37842. }
  37843. if ( ! targetObject.material ) {
  37844. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37845. return;
  37846. }
  37847. if ( ! targetObject.material.map ) {
  37848. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37849. return;
  37850. }
  37851. targetObject = targetObject.material.map;
  37852. break;
  37853. default:
  37854. if ( targetObject[ objectName ] === undefined ) {
  37855. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  37856. return;
  37857. }
  37858. targetObject = targetObject[ objectName ];
  37859. }
  37860. if ( objectIndex !== undefined ) {
  37861. if ( targetObject[ objectIndex ] === undefined ) {
  37862. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37863. return;
  37864. }
  37865. targetObject = targetObject[ objectIndex ];
  37866. }
  37867. }
  37868. // resolve property
  37869. const nodeProperty = targetObject[ propertyName ];
  37870. if ( nodeProperty === undefined ) {
  37871. const nodeName = parsedPath.nodeName;
  37872. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  37873. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37874. return;
  37875. }
  37876. // determine versioning scheme
  37877. let versioning = this.Versioning.None;
  37878. this.targetObject = targetObject;
  37879. if ( targetObject.isMaterial === true ) {
  37880. versioning = this.Versioning.NeedsUpdate;
  37881. } else if ( targetObject.isObject3D === true ) {
  37882. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37883. }
  37884. // determine how the property gets bound
  37885. let bindingType = this.BindingType.Direct;
  37886. if ( propertyIndex !== undefined ) {
  37887. // access a sub element of the property array (only primitives are supported right now)
  37888. if ( propertyName === 'morphTargetInfluences' ) {
  37889. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37890. // support resolving morphTarget names into indices.
  37891. if ( ! targetObject.geometry ) {
  37892. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37893. return;
  37894. }
  37895. if ( ! targetObject.geometry.morphAttributes ) {
  37896. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37897. return;
  37898. }
  37899. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37900. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37901. }
  37902. }
  37903. bindingType = this.BindingType.ArrayElement;
  37904. this.resolvedProperty = nodeProperty;
  37905. this.propertyIndex = propertyIndex;
  37906. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37907. // must use copy for Object3D.Euler/Quaternion
  37908. bindingType = this.BindingType.HasFromToArray;
  37909. this.resolvedProperty = nodeProperty;
  37910. } else if ( Array.isArray( nodeProperty ) ) {
  37911. bindingType = this.BindingType.EntireArray;
  37912. this.resolvedProperty = nodeProperty;
  37913. } else {
  37914. this.propertyName = propertyName;
  37915. }
  37916. // select getter / setter
  37917. this.getValue = this.GetterByBindingType[ bindingType ];
  37918. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37919. }
  37920. /**
  37921. * Unbinds the property.
  37922. */
  37923. unbind() {
  37924. this.node = null;
  37925. // back to the prototype version of getValue / setValue
  37926. // note: avoiding to mutate the shape of 'this' via 'delete'
  37927. this.getValue = this._getValue_unbound;
  37928. this.setValue = this._setValue_unbound;
  37929. }
  37930. }
  37931. PropertyBinding.Composite = Composite;
  37932. PropertyBinding.prototype.BindingType = {
  37933. Direct: 0,
  37934. EntireArray: 1,
  37935. ArrayElement: 2,
  37936. HasFromToArray: 3
  37937. };
  37938. PropertyBinding.prototype.Versioning = {
  37939. None: 0,
  37940. NeedsUpdate: 1,
  37941. MatrixWorldNeedsUpdate: 2
  37942. };
  37943. PropertyBinding.prototype.GetterByBindingType = [
  37944. PropertyBinding.prototype._getValue_direct,
  37945. PropertyBinding.prototype._getValue_array,
  37946. PropertyBinding.prototype._getValue_arrayElement,
  37947. PropertyBinding.prototype._getValue_toArray,
  37948. ];
  37949. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37950. [
  37951. // Direct
  37952. PropertyBinding.prototype._setValue_direct,
  37953. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37954. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37955. ], [
  37956. // EntireArray
  37957. PropertyBinding.prototype._setValue_array,
  37958. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37959. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37960. ], [
  37961. // ArrayElement
  37962. PropertyBinding.prototype._setValue_arrayElement,
  37963. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37964. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37965. ], [
  37966. // HasToFromArray
  37967. PropertyBinding.prototype._setValue_fromArray,
  37968. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37969. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37970. ]
  37971. ];
  37972. /**
  37973. * A group of objects that receives a shared animation state.
  37974. *
  37975. * Usage:
  37976. *
  37977. * - Add objects you would otherwise pass as 'root' to the
  37978. * constructor or the .clipAction method of AnimationMixer.
  37979. * - Instead pass this object as 'root'.
  37980. * - You can also add and remove objects later when the mixer is running.
  37981. *
  37982. * Note:
  37983. *
  37984. * - Objects of this class appear as one object to the mixer,
  37985. * so cache control of the individual objects must be done on the group.
  37986. *
  37987. * Limitation:
  37988. *
  37989. * - The animated properties must be compatible among the all objects in the group.
  37990. * - A single property can either be controlled through a target group or directly, but not both.
  37991. */
  37992. class AnimationObjectGroup {
  37993. /**
  37994. * Constructs a new animation group.
  37995. *
  37996. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37997. */
  37998. constructor() {
  37999. /**
  38000. * This flag can be used for type testing.
  38001. *
  38002. * @type {boolean}
  38003. * @readonly
  38004. * @default true
  38005. */
  38006. this.isAnimationObjectGroup = true;
  38007. /**
  38008. * The UUID of the 3D object.
  38009. *
  38010. * @type {string}
  38011. * @readonly
  38012. */
  38013. this.uuid = generateUUID();
  38014. // cached objects followed by the active ones
  38015. this._objects = Array.prototype.slice.call( arguments );
  38016. this.nCachedObjects_ = 0; // threshold
  38017. // note: read by PropertyBinding.Composite
  38018. const indices = {};
  38019. this._indicesByUUID = indices; // for bookkeeping
  38020. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38021. indices[ arguments[ i ].uuid ] = i;
  38022. }
  38023. this._paths = []; // inside: string
  38024. this._parsedPaths = []; // inside: { we don't care, here }
  38025. this._bindings = []; // inside: Array< PropertyBinding >
  38026. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38027. const scope = this;
  38028. this.stats = {
  38029. objects: {
  38030. get total() {
  38031. return scope._objects.length;
  38032. },
  38033. get inUse() {
  38034. return this.total - scope.nCachedObjects_;
  38035. }
  38036. },
  38037. get bindingsPerObject() {
  38038. return scope._bindings.length;
  38039. }
  38040. };
  38041. }
  38042. /**
  38043. * Adds an arbitrary number of objects to this animation group.
  38044. *
  38045. * @param {...Object3D} arguments - The 3D objects to add.
  38046. */
  38047. add() {
  38048. const objects = this._objects,
  38049. indicesByUUID = this._indicesByUUID,
  38050. paths = this._paths,
  38051. parsedPaths = this._parsedPaths,
  38052. bindings = this._bindings,
  38053. nBindings = bindings.length;
  38054. let knownObject = undefined,
  38055. nObjects = objects.length,
  38056. nCachedObjects = this.nCachedObjects_;
  38057. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38058. const object = arguments[ i ],
  38059. uuid = object.uuid;
  38060. let index = indicesByUUID[ uuid ];
  38061. if ( index === undefined ) {
  38062. // unknown object -> add it to the ACTIVE region
  38063. index = nObjects ++;
  38064. indicesByUUID[ uuid ] = index;
  38065. objects.push( object );
  38066. // accounting is done, now do the same for all bindings
  38067. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38068. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38069. }
  38070. } else if ( index < nCachedObjects ) {
  38071. knownObject = objects[ index ];
  38072. // move existing object to the ACTIVE region
  38073. const firstActiveIndex = -- nCachedObjects,
  38074. lastCachedObject = objects[ firstActiveIndex ];
  38075. indicesByUUID[ lastCachedObject.uuid ] = index;
  38076. objects[ index ] = lastCachedObject;
  38077. indicesByUUID[ uuid ] = firstActiveIndex;
  38078. objects[ firstActiveIndex ] = object;
  38079. // accounting is done, now do the same for all bindings
  38080. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38081. const bindingsForPath = bindings[ j ],
  38082. lastCached = bindingsForPath[ firstActiveIndex ];
  38083. let binding = bindingsForPath[ index ];
  38084. bindingsForPath[ index ] = lastCached;
  38085. if ( binding === undefined ) {
  38086. // since we do not bother to create new bindings
  38087. // for objects that are cached, the binding may
  38088. // or may not exist
  38089. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38090. }
  38091. bindingsForPath[ firstActiveIndex ] = binding;
  38092. }
  38093. } else if ( objects[ index ] !== knownObject ) {
  38094. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38095. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38096. } // else the object is already where we want it to be
  38097. } // for arguments
  38098. this.nCachedObjects_ = nCachedObjects;
  38099. }
  38100. /**
  38101. * Removes an arbitrary number of objects to this animation group
  38102. *
  38103. * @param {...Object3D} arguments - The 3D objects to remove.
  38104. */
  38105. remove() {
  38106. const objects = this._objects,
  38107. indicesByUUID = this._indicesByUUID,
  38108. bindings = this._bindings,
  38109. nBindings = bindings.length;
  38110. let nCachedObjects = this.nCachedObjects_;
  38111. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38112. const object = arguments[ i ],
  38113. uuid = object.uuid,
  38114. index = indicesByUUID[ uuid ];
  38115. if ( index !== undefined && index >= nCachedObjects ) {
  38116. // move existing object into the CACHED region
  38117. const lastCachedIndex = nCachedObjects ++,
  38118. firstActiveObject = objects[ lastCachedIndex ];
  38119. indicesByUUID[ firstActiveObject.uuid ] = index;
  38120. objects[ index ] = firstActiveObject;
  38121. indicesByUUID[ uuid ] = lastCachedIndex;
  38122. objects[ lastCachedIndex ] = object;
  38123. // accounting is done, now do the same for all bindings
  38124. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38125. const bindingsForPath = bindings[ j ],
  38126. firstActive = bindingsForPath[ lastCachedIndex ],
  38127. binding = bindingsForPath[ index ];
  38128. bindingsForPath[ index ] = firstActive;
  38129. bindingsForPath[ lastCachedIndex ] = binding;
  38130. }
  38131. }
  38132. } // for arguments
  38133. this.nCachedObjects_ = nCachedObjects;
  38134. }
  38135. /**
  38136. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38137. *
  38138. * @param {...Object3D} arguments - The 3D objects to uncache.
  38139. */
  38140. uncache() {
  38141. const objects = this._objects,
  38142. indicesByUUID = this._indicesByUUID,
  38143. bindings = this._bindings,
  38144. nBindings = bindings.length;
  38145. let nCachedObjects = this.nCachedObjects_,
  38146. nObjects = objects.length;
  38147. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38148. const object = arguments[ i ],
  38149. uuid = object.uuid,
  38150. index = indicesByUUID[ uuid ];
  38151. if ( index !== undefined ) {
  38152. delete indicesByUUID[ uuid ];
  38153. if ( index < nCachedObjects ) {
  38154. // object is cached, shrink the CACHED region
  38155. const firstActiveIndex = -- nCachedObjects,
  38156. lastCachedObject = objects[ firstActiveIndex ],
  38157. lastIndex = -- nObjects,
  38158. lastObject = objects[ lastIndex ];
  38159. // last cached object takes this object's place
  38160. indicesByUUID[ lastCachedObject.uuid ] = index;
  38161. objects[ index ] = lastCachedObject;
  38162. // last object goes to the activated slot and pop
  38163. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38164. objects[ firstActiveIndex ] = lastObject;
  38165. objects.pop();
  38166. // accounting is done, now do the same for all bindings
  38167. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38168. const bindingsForPath = bindings[ j ],
  38169. lastCached = bindingsForPath[ firstActiveIndex ],
  38170. last = bindingsForPath[ lastIndex ];
  38171. bindingsForPath[ index ] = lastCached;
  38172. bindingsForPath[ firstActiveIndex ] = last;
  38173. bindingsForPath.pop();
  38174. }
  38175. } else {
  38176. // object is active, just swap with the last and pop
  38177. const lastIndex = -- nObjects,
  38178. lastObject = objects[ lastIndex ];
  38179. if ( lastIndex > 0 ) {
  38180. indicesByUUID[ lastObject.uuid ] = index;
  38181. }
  38182. objects[ index ] = lastObject;
  38183. objects.pop();
  38184. // accounting is done, now do the same for all bindings
  38185. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38186. const bindingsForPath = bindings[ j ];
  38187. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38188. bindingsForPath.pop();
  38189. }
  38190. } // cached or active
  38191. } // if object is known
  38192. } // for arguments
  38193. this.nCachedObjects_ = nCachedObjects;
  38194. }
  38195. // Internal interface used by befriended PropertyBinding.Composite:
  38196. subscribe_( path, parsedPath ) {
  38197. // returns an array of bindings for the given path that is changed
  38198. // according to the contained objects in the group
  38199. const indicesByPath = this._bindingsIndicesByPath;
  38200. let index = indicesByPath[ path ];
  38201. const bindings = this._bindings;
  38202. if ( index !== undefined ) return bindings[ index ];
  38203. const paths = this._paths,
  38204. parsedPaths = this._parsedPaths,
  38205. objects = this._objects,
  38206. nObjects = objects.length,
  38207. nCachedObjects = this.nCachedObjects_,
  38208. bindingsForPath = new Array( nObjects );
  38209. index = bindings.length;
  38210. indicesByPath[ path ] = index;
  38211. paths.push( path );
  38212. parsedPaths.push( parsedPath );
  38213. bindings.push( bindingsForPath );
  38214. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38215. const object = objects[ i ];
  38216. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38217. }
  38218. return bindingsForPath;
  38219. }
  38220. unsubscribe_( path ) {
  38221. // tells the group to forget about a property path and no longer
  38222. // update the array previously obtained with 'subscribe_'
  38223. const indicesByPath = this._bindingsIndicesByPath,
  38224. index = indicesByPath[ path ];
  38225. if ( index !== undefined ) {
  38226. const paths = this._paths,
  38227. parsedPaths = this._parsedPaths,
  38228. bindings = this._bindings,
  38229. lastBindingsIndex = bindings.length - 1,
  38230. lastBindings = bindings[ lastBindingsIndex ],
  38231. lastBindingsPath = path[ lastBindingsIndex ];
  38232. indicesByPath[ lastBindingsPath ] = index;
  38233. bindings[ index ] = lastBindings;
  38234. bindings.pop();
  38235. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38236. parsedPaths.pop();
  38237. paths[ index ] = paths[ lastBindingsIndex ];
  38238. paths.pop();
  38239. }
  38240. }
  38241. }
  38242. /**
  38243. * An instance of `AnimationAction` schedules the playback of an animation which is
  38244. * stored in {@link AnimationClip}.
  38245. */
  38246. class AnimationAction {
  38247. /**
  38248. * Constructs a new animation action.
  38249. *
  38250. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38251. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38252. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38253. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38254. */
  38255. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38256. this._mixer = mixer;
  38257. this._clip = clip;
  38258. this._localRoot = localRoot;
  38259. /**
  38260. * Defines how the animation is blended/combined when two or more animations
  38261. * are simultaneously played.
  38262. *
  38263. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38264. */
  38265. this.blendMode = blendMode;
  38266. const tracks = clip.tracks,
  38267. nTracks = tracks.length,
  38268. interpolants = new Array( nTracks );
  38269. const interpolantSettings = {
  38270. endingStart: ZeroCurvatureEnding,
  38271. endingEnd: ZeroCurvatureEnding
  38272. };
  38273. for ( let i = 0; i !== nTracks; ++ i ) {
  38274. const interpolant = tracks[ i ].createInterpolant( null );
  38275. interpolants[ i ] = interpolant;
  38276. interpolant.settings = interpolantSettings;
  38277. }
  38278. this._interpolantSettings = interpolantSettings;
  38279. this._interpolants = interpolants; // bound by the mixer
  38280. // inside: PropertyMixer (managed by the mixer)
  38281. this._propertyBindings = new Array( nTracks );
  38282. this._cacheIndex = null; // for the memory manager
  38283. this._byClipCacheIndex = null; // for the memory manager
  38284. this._timeScaleInterpolant = null;
  38285. this._weightInterpolant = null;
  38286. /**
  38287. * The loop mode, set via {@link AnimationAction#setLoop}.
  38288. *
  38289. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38290. * @default LoopRepeat
  38291. */
  38292. this.loop = LoopRepeat;
  38293. this._loopCount = -1;
  38294. // global mixer time when the action is to be started
  38295. // it's set back to 'null' upon start of the action
  38296. this._startTime = null;
  38297. /**
  38298. * The local time of this action (in seconds, starting with `0`).
  38299. *
  38300. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38301. * loop state).
  38302. *
  38303. * @type {number}
  38304. * @default Infinity
  38305. */
  38306. this.time = 0;
  38307. /**
  38308. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38309. * animation to pause. Negative values cause the animation to play backwards.
  38310. *
  38311. * @type {number}
  38312. * @default 1
  38313. */
  38314. this.timeScale = 1;
  38315. this._effectiveTimeScale = 1;
  38316. /**
  38317. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38318. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38319. * several actions.
  38320. *
  38321. * @type {number}
  38322. * @default 1
  38323. */
  38324. this.weight = 1;
  38325. this._effectiveWeight = 1;
  38326. /**
  38327. * The number of repetitions of the performed clip over the course of this action.
  38328. * Can be set via {@link AnimationAction#setLoop}.
  38329. *
  38330. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38331. * `THREE:LoopOnce`.
  38332. *
  38333. * @type {number}
  38334. * @default Infinity
  38335. */
  38336. this.repetitions = Infinity;
  38337. /**
  38338. * If set to `true`, the playback of the action is paused.
  38339. *
  38340. * @type {boolean}
  38341. * @default false
  38342. */
  38343. this.paused = false;
  38344. /**
  38345. * If set to `false`, the action is disabled so it has no impact.
  38346. *
  38347. * When the action is re-enabled, the animation continues from its current
  38348. * time (setting `enabled` to `false` doesn't reset the action).
  38349. *
  38350. * @type {boolean}
  38351. * @default true
  38352. */
  38353. this.enabled = true;
  38354. /**
  38355. * If set to true the animation will automatically be paused on its last frame.
  38356. *
  38357. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38358. * to `false` when the last loop of the action has finished, so that this action has
  38359. * no further impact.
  38360. *
  38361. * Note: This member has no impact if the action is interrupted (it
  38362. * has only an effect if its last loop has really finished).
  38363. *
  38364. * @type {boolean}
  38365. * @default false
  38366. */
  38367. this.clampWhenFinished = false;
  38368. /**
  38369. * Enables smooth interpolation without separate clips for start, loop and end.
  38370. *
  38371. * @type {boolean}
  38372. * @default true
  38373. */
  38374. this.zeroSlopeAtStart = true;
  38375. /**
  38376. * Enables smooth interpolation without separate clips for start, loop and end.
  38377. *
  38378. * @type {boolean}
  38379. * @default true
  38380. */
  38381. this.zeroSlopeAtEnd = true;
  38382. }
  38383. /**
  38384. * Starts the playback of the animation.
  38385. *
  38386. * @return {AnimationAction} A reference to this animation action.
  38387. */
  38388. play() {
  38389. this._mixer._activateAction( this );
  38390. return this;
  38391. }
  38392. /**
  38393. * Stops the playback of the animation.
  38394. *
  38395. * @return {AnimationAction} A reference to this animation action.
  38396. */
  38397. stop() {
  38398. this._mixer._deactivateAction( this );
  38399. return this.reset();
  38400. }
  38401. /**
  38402. * Resets the playback of the animation.
  38403. *
  38404. * @return {AnimationAction} A reference to this animation action.
  38405. */
  38406. reset() {
  38407. this.paused = false;
  38408. this.enabled = true;
  38409. this.time = 0; // restart clip
  38410. this._loopCount = -1;// forget previous loops
  38411. this._startTime = null;// forget scheduling
  38412. return this.stopFading().stopWarping();
  38413. }
  38414. /**
  38415. * Returns `true` if the animation is running.
  38416. *
  38417. * @return {boolean} Whether the animation is running or not.
  38418. */
  38419. isRunning() {
  38420. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38421. this._startTime === null && this._mixer._isActiveAction( this );
  38422. }
  38423. /**
  38424. * Returns `true` when {@link AnimationAction#play} has been called.
  38425. *
  38426. * @return {boolean} Whether the animation is scheduled or not.
  38427. */
  38428. isScheduled() {
  38429. return this._mixer._isActiveAction( this );
  38430. }
  38431. /**
  38432. * Defines the time when the animation should start.
  38433. *
  38434. * @param {number} time - The start time in seconds.
  38435. * @return {AnimationAction} A reference to this animation action.
  38436. */
  38437. startAt( time ) {
  38438. this._startTime = time;
  38439. return this;
  38440. }
  38441. /**
  38442. * Configures the loop settings for this action.
  38443. *
  38444. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38445. * @param {number} repetitions - The number of repetitions.
  38446. * @return {AnimationAction} A reference to this animation action.
  38447. */
  38448. setLoop( mode, repetitions ) {
  38449. this.loop = mode;
  38450. this.repetitions = repetitions;
  38451. return this;
  38452. }
  38453. /**
  38454. * Sets the effective weight of this action.
  38455. *
  38456. * An action has no effect and thus an effective weight of zero when the
  38457. * action is disabled.
  38458. *
  38459. * @param {number} weight - The weight to set.
  38460. * @return {AnimationAction} A reference to this animation action.
  38461. */
  38462. setEffectiveWeight( weight ) {
  38463. this.weight = weight;
  38464. // note: same logic as when updated at runtime
  38465. this._effectiveWeight = this.enabled ? weight : 0;
  38466. return this.stopFading();
  38467. }
  38468. /**
  38469. * Returns the effective weight of this action.
  38470. *
  38471. * @return {number} The effective weight.
  38472. */
  38473. getEffectiveWeight() {
  38474. return this._effectiveWeight;
  38475. }
  38476. /**
  38477. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38478. * within the passed time interval.
  38479. *
  38480. * @param {number} duration - The duration of the fade.
  38481. * @return {AnimationAction} A reference to this animation action.
  38482. */
  38483. fadeIn( duration ) {
  38484. return this._scheduleFading( duration, 0, 1 );
  38485. }
  38486. /**
  38487. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38488. * within the passed time interval.
  38489. *
  38490. * @param {number} duration - The duration of the fade.
  38491. * @return {AnimationAction} A reference to this animation action.
  38492. */
  38493. fadeOut( duration ) {
  38494. return this._scheduleFading( duration, 1, 0 );
  38495. }
  38496. /**
  38497. * Causes this action to fade in and the given action to fade out,
  38498. * within the passed time interval.
  38499. *
  38500. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38501. * @param {number} duration - The duration of the fade.
  38502. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38503. * @return {AnimationAction} A reference to this animation action.
  38504. */
  38505. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38506. fadeOutAction.fadeOut( duration );
  38507. this.fadeIn( duration );
  38508. if ( warp === true ) {
  38509. const fadeInDuration = this._clip.duration,
  38510. fadeOutDuration = fadeOutAction._clip.duration,
  38511. startEndRatio = fadeOutDuration / fadeInDuration,
  38512. endStartRatio = fadeInDuration / fadeOutDuration;
  38513. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38514. this.warp( endStartRatio, 1.0, duration );
  38515. }
  38516. return this;
  38517. }
  38518. /**
  38519. * Causes this action to fade out and the given action to fade in,
  38520. * within the passed time interval.
  38521. *
  38522. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38523. * @param {number} duration - The duration of the fade.
  38524. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38525. * @return {AnimationAction} A reference to this animation action.
  38526. */
  38527. crossFadeTo( fadeInAction, duration, warp = false ) {
  38528. return fadeInAction.crossFadeFrom( this, duration, warp );
  38529. }
  38530. /**
  38531. * Stops any fading which is applied to this action.
  38532. *
  38533. * @return {AnimationAction} A reference to this animation action.
  38534. */
  38535. stopFading() {
  38536. const weightInterpolant = this._weightInterpolant;
  38537. if ( weightInterpolant !== null ) {
  38538. this._weightInterpolant = null;
  38539. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38540. }
  38541. return this;
  38542. }
  38543. /**
  38544. * Sets the effective time scale of this action.
  38545. *
  38546. * An action has no effect and thus an effective time scale of zero when the
  38547. * action is paused.
  38548. *
  38549. * @param {number} timeScale - The time scale to set.
  38550. * @return {AnimationAction} A reference to this animation action.
  38551. */
  38552. setEffectiveTimeScale( timeScale ) {
  38553. this.timeScale = timeScale;
  38554. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38555. return this.stopWarping();
  38556. }
  38557. /**
  38558. * Returns the effective time scale of this action.
  38559. *
  38560. * @return {number} The effective time scale.
  38561. */
  38562. getEffectiveTimeScale() {
  38563. return this._effectiveTimeScale;
  38564. }
  38565. /**
  38566. * Sets the duration for a single loop of this action.
  38567. *
  38568. * @param {number} duration - The duration to set.
  38569. * @return {AnimationAction} A reference to this animation action.
  38570. */
  38571. setDuration( duration ) {
  38572. this.timeScale = this._clip.duration / duration;
  38573. return this.stopWarping();
  38574. }
  38575. /**
  38576. * Synchronizes this action with the passed other action.
  38577. *
  38578. * @param {AnimationAction} action - The action to sync with.
  38579. * @return {AnimationAction} A reference to this animation action.
  38580. */
  38581. syncWith( action ) {
  38582. this.time = action.time;
  38583. this.timeScale = action.timeScale;
  38584. return this.stopWarping();
  38585. }
  38586. /**
  38587. * Decelerates this animation's speed to `0` within the passed time interval.
  38588. *
  38589. * @param {number} duration - The duration.
  38590. * @return {AnimationAction} A reference to this animation action.
  38591. */
  38592. halt( duration ) {
  38593. return this.warp( this._effectiveTimeScale, 0, duration );
  38594. }
  38595. /**
  38596. * Changes the playback speed, within the passed time interval, by modifying
  38597. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38598. * `endTimeScale`.
  38599. *
  38600. * @param {number} startTimeScale - The start time scale.
  38601. * @param {number} endTimeScale - The end time scale.
  38602. * @param {number} duration - The duration.
  38603. * @return {AnimationAction} A reference to this animation action.
  38604. */
  38605. warp( startTimeScale, endTimeScale, duration ) {
  38606. const mixer = this._mixer,
  38607. now = mixer.time,
  38608. timeScale = this.timeScale;
  38609. let interpolant = this._timeScaleInterpolant;
  38610. if ( interpolant === null ) {
  38611. interpolant = mixer._lendControlInterpolant();
  38612. this._timeScaleInterpolant = interpolant;
  38613. }
  38614. const times = interpolant.parameterPositions,
  38615. values = interpolant.sampleValues;
  38616. times[ 0 ] = now;
  38617. times[ 1 ] = now + duration;
  38618. values[ 0 ] = startTimeScale / timeScale;
  38619. values[ 1 ] = endTimeScale / timeScale;
  38620. return this;
  38621. }
  38622. /**
  38623. * Stops any scheduled warping which is applied to this action.
  38624. *
  38625. * @return {AnimationAction} A reference to this animation action.
  38626. */
  38627. stopWarping() {
  38628. const timeScaleInterpolant = this._timeScaleInterpolant;
  38629. if ( timeScaleInterpolant !== null ) {
  38630. this._timeScaleInterpolant = null;
  38631. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38632. }
  38633. return this;
  38634. }
  38635. /**
  38636. * Returns the animation mixer of this animation action.
  38637. *
  38638. * @return {AnimationMixer} The animation mixer.
  38639. */
  38640. getMixer() {
  38641. return this._mixer;
  38642. }
  38643. /**
  38644. * Returns the animation clip of this animation action.
  38645. *
  38646. * @return {AnimationClip} The animation clip.
  38647. */
  38648. getClip() {
  38649. return this._clip;
  38650. }
  38651. /**
  38652. * Returns the root object of this animation action.
  38653. *
  38654. * @return {Object3D} The root object.
  38655. */
  38656. getRoot() {
  38657. return this._localRoot || this._mixer._root;
  38658. }
  38659. // Interna
  38660. _update( time, deltaTime, timeDirection, accuIndex ) {
  38661. // called by the mixer
  38662. if ( ! this.enabled ) {
  38663. // call ._updateWeight() to update ._effectiveWeight
  38664. this._updateWeight( time );
  38665. return;
  38666. }
  38667. const startTime = this._startTime;
  38668. if ( startTime !== null ) {
  38669. // check for scheduled start of action
  38670. const timeRunning = ( time - startTime ) * timeDirection;
  38671. if ( timeRunning < 0 || timeDirection === 0 ) {
  38672. deltaTime = 0;
  38673. } else {
  38674. this._startTime = null; // unschedule
  38675. deltaTime = timeDirection * timeRunning;
  38676. }
  38677. }
  38678. // apply time scale and advance time
  38679. deltaTime *= this._updateTimeScale( time );
  38680. const clipTime = this._updateTime( deltaTime );
  38681. // note: _updateTime may disable the action resulting in
  38682. // an effective weight of 0
  38683. const weight = this._updateWeight( time );
  38684. if ( weight > 0 ) {
  38685. const interpolants = this._interpolants;
  38686. const propertyMixers = this._propertyBindings;
  38687. switch ( this.blendMode ) {
  38688. case AdditiveAnimationBlendMode:
  38689. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38690. interpolants[ j ].evaluate( clipTime );
  38691. propertyMixers[ j ].accumulateAdditive( weight );
  38692. }
  38693. break;
  38694. case NormalAnimationBlendMode:
  38695. default:
  38696. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38697. interpolants[ j ].evaluate( clipTime );
  38698. propertyMixers[ j ].accumulate( accuIndex, weight );
  38699. }
  38700. }
  38701. }
  38702. }
  38703. _updateWeight( time ) {
  38704. let weight = 0;
  38705. if ( this.enabled ) {
  38706. weight = this.weight;
  38707. const interpolant = this._weightInterpolant;
  38708. if ( interpolant !== null ) {
  38709. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38710. weight *= interpolantValue;
  38711. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38712. this.stopFading();
  38713. if ( interpolantValue === 0 ) {
  38714. // faded out, disable
  38715. this.enabled = false;
  38716. }
  38717. }
  38718. }
  38719. }
  38720. this._effectiveWeight = weight;
  38721. return weight;
  38722. }
  38723. _updateTimeScale( time ) {
  38724. let timeScale = 0;
  38725. if ( ! this.paused ) {
  38726. timeScale = this.timeScale;
  38727. const interpolant = this._timeScaleInterpolant;
  38728. if ( interpolant !== null ) {
  38729. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38730. timeScale *= interpolantValue;
  38731. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38732. this.stopWarping();
  38733. if ( timeScale === 0 ) {
  38734. // motion has halted, pause
  38735. this.paused = true;
  38736. } else {
  38737. // warp done - apply final time scale
  38738. this.timeScale = timeScale;
  38739. }
  38740. }
  38741. }
  38742. }
  38743. this._effectiveTimeScale = timeScale;
  38744. return timeScale;
  38745. }
  38746. _updateTime( deltaTime ) {
  38747. const duration = this._clip.duration;
  38748. const loop = this.loop;
  38749. let time = this.time + deltaTime;
  38750. let loopCount = this._loopCount;
  38751. const pingPong = ( loop === LoopPingPong );
  38752. if ( deltaTime === 0 ) {
  38753. if ( loopCount === -1 ) return time;
  38754. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38755. }
  38756. if ( loop === LoopOnce ) {
  38757. if ( loopCount === -1 ) {
  38758. // just started
  38759. this._loopCount = 0;
  38760. this._setEndings( true, true, false );
  38761. }
  38762. handle_stop: {
  38763. if ( time >= duration ) {
  38764. time = duration;
  38765. } else if ( time < 0 ) {
  38766. time = 0;
  38767. } else {
  38768. this.time = time;
  38769. break handle_stop;
  38770. }
  38771. if ( this.clampWhenFinished ) this.paused = true;
  38772. else this.enabled = false;
  38773. this.time = time;
  38774. this._mixer.dispatchEvent( {
  38775. type: 'finished', action: this,
  38776. direction: deltaTime < 0 ? -1 : 1
  38777. } );
  38778. }
  38779. } else { // repetitive Repeat or PingPong
  38780. if ( loopCount === -1 ) {
  38781. // just started
  38782. if ( deltaTime >= 0 ) {
  38783. loopCount = 0;
  38784. this._setEndings( true, this.repetitions === 0, pingPong );
  38785. } else {
  38786. // when looping in reverse direction, the initial
  38787. // transition through zero counts as a repetition,
  38788. // so leave loopCount at -1
  38789. this._setEndings( this.repetitions === 0, true, pingPong );
  38790. }
  38791. }
  38792. if ( time >= duration || time < 0 ) {
  38793. // wrap around
  38794. const loopDelta = Math.floor( time / duration ); // signed
  38795. time -= duration * loopDelta;
  38796. loopCount += Math.abs( loopDelta );
  38797. const pending = this.repetitions - loopCount;
  38798. if ( pending <= 0 ) {
  38799. // have to stop (switch state, clamp time, fire event)
  38800. if ( this.clampWhenFinished ) this.paused = true;
  38801. else this.enabled = false;
  38802. time = deltaTime > 0 ? duration : 0;
  38803. this.time = time;
  38804. this._mixer.dispatchEvent( {
  38805. type: 'finished', action: this,
  38806. direction: deltaTime > 0 ? 1 : -1
  38807. } );
  38808. } else {
  38809. // keep running
  38810. if ( pending === 1 ) {
  38811. // entering the last round
  38812. const atStart = deltaTime < 0;
  38813. this._setEndings( atStart, ! atStart, pingPong );
  38814. } else {
  38815. this._setEndings( false, false, pingPong );
  38816. }
  38817. this._loopCount = loopCount;
  38818. this.time = time;
  38819. this._mixer.dispatchEvent( {
  38820. type: 'loop', action: this, loopDelta: loopDelta
  38821. } );
  38822. }
  38823. } else {
  38824. this.time = time;
  38825. }
  38826. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38827. // invert time for the "pong round"
  38828. return duration - time;
  38829. }
  38830. }
  38831. return time;
  38832. }
  38833. _setEndings( atStart, atEnd, pingPong ) {
  38834. const settings = this._interpolantSettings;
  38835. if ( pingPong ) {
  38836. settings.endingStart = ZeroSlopeEnding;
  38837. settings.endingEnd = ZeroSlopeEnding;
  38838. } else {
  38839. // assuming for LoopOnce atStart == atEnd == true
  38840. if ( atStart ) {
  38841. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38842. } else {
  38843. settings.endingStart = WrapAroundEnding;
  38844. }
  38845. if ( atEnd ) {
  38846. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38847. } else {
  38848. settings.endingEnd = WrapAroundEnding;
  38849. }
  38850. }
  38851. }
  38852. _scheduleFading( duration, weightNow, weightThen ) {
  38853. const mixer = this._mixer, now = mixer.time;
  38854. let interpolant = this._weightInterpolant;
  38855. if ( interpolant === null ) {
  38856. interpolant = mixer._lendControlInterpolant();
  38857. this._weightInterpolant = interpolant;
  38858. }
  38859. const times = interpolant.parameterPositions,
  38860. values = interpolant.sampleValues;
  38861. times[ 0 ] = now;
  38862. values[ 0 ] = weightNow;
  38863. times[ 1 ] = now + duration;
  38864. values[ 1 ] = weightThen;
  38865. return this;
  38866. }
  38867. }
  38868. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38869. /**
  38870. * `AnimationMixer` is a player for animations on a particular object in
  38871. * the scene. When multiple objects in the scene are animated independently,
  38872. * one `AnimationMixer` may be used for each object.
  38873. */
  38874. class AnimationMixer extends EventDispatcher {
  38875. /**
  38876. * Constructs a new animation mixer.
  38877. *
  38878. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38879. */
  38880. constructor( root ) {
  38881. super();
  38882. this._root = root;
  38883. this._initMemoryManager();
  38884. this._accuIndex = 0;
  38885. /**
  38886. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38887. *
  38888. * @type {number}
  38889. * @default 0
  38890. */
  38891. this.time = 0;
  38892. /**
  38893. * A scaling factor for the global time.
  38894. *
  38895. * Note: Setting this member to `0` and later back to `1` is a
  38896. * possibility to pause/unpause all actions that are controlled by this
  38897. * mixer.
  38898. *
  38899. * @type {number}
  38900. * @default 1
  38901. */
  38902. this.timeScale = 1.0;
  38903. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  38904. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  38905. }
  38906. }
  38907. _bindAction( action, prototypeAction ) {
  38908. const root = action._localRoot || this._root,
  38909. tracks = action._clip.tracks,
  38910. nTracks = tracks.length,
  38911. bindings = action._propertyBindings,
  38912. interpolants = action._interpolants,
  38913. rootUuid = root.uuid,
  38914. bindingsByRoot = this._bindingsByRootAndName;
  38915. let bindingsByName = bindingsByRoot[ rootUuid ];
  38916. if ( bindingsByName === undefined ) {
  38917. bindingsByName = {};
  38918. bindingsByRoot[ rootUuid ] = bindingsByName;
  38919. }
  38920. for ( let i = 0; i !== nTracks; ++ i ) {
  38921. const track = tracks[ i ],
  38922. trackName = track.name;
  38923. let binding = bindingsByName[ trackName ];
  38924. if ( binding !== undefined ) {
  38925. ++ binding.referenceCount;
  38926. bindings[ i ] = binding;
  38927. } else {
  38928. binding = bindings[ i ];
  38929. if ( binding !== undefined ) {
  38930. // existing binding, make sure the cache knows
  38931. if ( binding._cacheIndex === null ) {
  38932. ++ binding.referenceCount;
  38933. this._addInactiveBinding( binding, rootUuid, trackName );
  38934. }
  38935. continue;
  38936. }
  38937. const path = prototypeAction && prototypeAction.
  38938. _propertyBindings[ i ].binding.parsedPath;
  38939. binding = new PropertyMixer(
  38940. PropertyBinding.create( root, trackName, path ),
  38941. track.ValueTypeName, track.getValueSize() );
  38942. ++ binding.referenceCount;
  38943. this._addInactiveBinding( binding, rootUuid, trackName );
  38944. bindings[ i ] = binding;
  38945. }
  38946. interpolants[ i ].resultBuffer = binding.buffer;
  38947. }
  38948. }
  38949. _activateAction( action ) {
  38950. if ( ! this._isActiveAction( action ) ) {
  38951. if ( action._cacheIndex === null ) {
  38952. // this action has been forgotten by the cache, but the user
  38953. // appears to be still using it -> rebind
  38954. const rootUuid = ( action._localRoot || this._root ).uuid,
  38955. clipUuid = action._clip.uuid,
  38956. actionsForClip = this._actionsByClip[ clipUuid ];
  38957. this._bindAction( action,
  38958. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38959. this._addInactiveAction( action, clipUuid, rootUuid );
  38960. }
  38961. const bindings = action._propertyBindings;
  38962. // increment reference counts / sort out state
  38963. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38964. const binding = bindings[ i ];
  38965. if ( binding.useCount ++ === 0 ) {
  38966. this._lendBinding( binding );
  38967. binding.saveOriginalState();
  38968. }
  38969. }
  38970. this._lendAction( action );
  38971. }
  38972. }
  38973. _deactivateAction( action ) {
  38974. if ( this._isActiveAction( action ) ) {
  38975. const bindings = action._propertyBindings;
  38976. // decrement reference counts / sort out state
  38977. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38978. const binding = bindings[ i ];
  38979. if ( -- binding.useCount === 0 ) {
  38980. binding.restoreOriginalState();
  38981. this._takeBackBinding( binding );
  38982. }
  38983. }
  38984. this._takeBackAction( action );
  38985. }
  38986. }
  38987. // Memory manager
  38988. _initMemoryManager() {
  38989. this._actions = []; // 'nActiveActions' followed by inactive ones
  38990. this._nActiveActions = 0;
  38991. this._actionsByClip = {};
  38992. // inside:
  38993. // {
  38994. // knownActions: Array< AnimationAction > - used as prototypes
  38995. // actionByRoot: AnimationAction - lookup
  38996. // }
  38997. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38998. this._nActiveBindings = 0;
  38999. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39000. this._controlInterpolants = []; // same game as above
  39001. this._nActiveControlInterpolants = 0;
  39002. const scope = this;
  39003. this.stats = {
  39004. actions: {
  39005. get total() {
  39006. return scope._actions.length;
  39007. },
  39008. get inUse() {
  39009. return scope._nActiveActions;
  39010. }
  39011. },
  39012. bindings: {
  39013. get total() {
  39014. return scope._bindings.length;
  39015. },
  39016. get inUse() {
  39017. return scope._nActiveBindings;
  39018. }
  39019. },
  39020. controlInterpolants: {
  39021. get total() {
  39022. return scope._controlInterpolants.length;
  39023. },
  39024. get inUse() {
  39025. return scope._nActiveControlInterpolants;
  39026. }
  39027. }
  39028. };
  39029. }
  39030. // Memory management for AnimationAction objects
  39031. _isActiveAction( action ) {
  39032. const index = action._cacheIndex;
  39033. return index !== null && index < this._nActiveActions;
  39034. }
  39035. _addInactiveAction( action, clipUuid, rootUuid ) {
  39036. const actions = this._actions,
  39037. actionsByClip = this._actionsByClip;
  39038. let actionsForClip = actionsByClip[ clipUuid ];
  39039. if ( actionsForClip === undefined ) {
  39040. actionsForClip = {
  39041. knownActions: [ action ],
  39042. actionByRoot: {}
  39043. };
  39044. action._byClipCacheIndex = 0;
  39045. actionsByClip[ clipUuid ] = actionsForClip;
  39046. } else {
  39047. const knownActions = actionsForClip.knownActions;
  39048. action._byClipCacheIndex = knownActions.length;
  39049. knownActions.push( action );
  39050. }
  39051. action._cacheIndex = actions.length;
  39052. actions.push( action );
  39053. actionsForClip.actionByRoot[ rootUuid ] = action;
  39054. }
  39055. _removeInactiveAction( action ) {
  39056. const actions = this._actions,
  39057. lastInactiveAction = actions[ actions.length - 1 ],
  39058. cacheIndex = action._cacheIndex;
  39059. lastInactiveAction._cacheIndex = cacheIndex;
  39060. actions[ cacheIndex ] = lastInactiveAction;
  39061. actions.pop();
  39062. action._cacheIndex = null;
  39063. const clipUuid = action._clip.uuid,
  39064. actionsByClip = this._actionsByClip,
  39065. actionsForClip = actionsByClip[ clipUuid ],
  39066. knownActionsForClip = actionsForClip.knownActions,
  39067. lastKnownAction =
  39068. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39069. byClipCacheIndex = action._byClipCacheIndex;
  39070. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39071. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39072. knownActionsForClip.pop();
  39073. action._byClipCacheIndex = null;
  39074. const actionByRoot = actionsForClip.actionByRoot,
  39075. rootUuid = ( action._localRoot || this._root ).uuid;
  39076. delete actionByRoot[ rootUuid ];
  39077. if ( knownActionsForClip.length === 0 ) {
  39078. delete actionsByClip[ clipUuid ];
  39079. }
  39080. this._removeInactiveBindingsForAction( action );
  39081. }
  39082. _removeInactiveBindingsForAction( action ) {
  39083. const bindings = action._propertyBindings;
  39084. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39085. const binding = bindings[ i ];
  39086. if ( -- binding.referenceCount === 0 ) {
  39087. this._removeInactiveBinding( binding );
  39088. }
  39089. }
  39090. }
  39091. _lendAction( action ) {
  39092. // [ active actions | inactive actions ]
  39093. // [ active actions >| inactive actions ]
  39094. // s a
  39095. // <-swap->
  39096. // a s
  39097. const actions = this._actions,
  39098. prevIndex = action._cacheIndex,
  39099. lastActiveIndex = this._nActiveActions ++,
  39100. firstInactiveAction = actions[ lastActiveIndex ];
  39101. action._cacheIndex = lastActiveIndex;
  39102. actions[ lastActiveIndex ] = action;
  39103. firstInactiveAction._cacheIndex = prevIndex;
  39104. actions[ prevIndex ] = firstInactiveAction;
  39105. }
  39106. _takeBackAction( action ) {
  39107. // [ active actions | inactive actions ]
  39108. // [ active actions |< inactive actions ]
  39109. // a s
  39110. // <-swap->
  39111. // s a
  39112. const actions = this._actions,
  39113. prevIndex = action._cacheIndex,
  39114. firstInactiveIndex = -- this._nActiveActions,
  39115. lastActiveAction = actions[ firstInactiveIndex ];
  39116. action._cacheIndex = firstInactiveIndex;
  39117. actions[ firstInactiveIndex ] = action;
  39118. lastActiveAction._cacheIndex = prevIndex;
  39119. actions[ prevIndex ] = lastActiveAction;
  39120. }
  39121. // Memory management for PropertyMixer objects
  39122. _addInactiveBinding( binding, rootUuid, trackName ) {
  39123. const bindingsByRoot = this._bindingsByRootAndName,
  39124. bindings = this._bindings;
  39125. let bindingByName = bindingsByRoot[ rootUuid ];
  39126. if ( bindingByName === undefined ) {
  39127. bindingByName = {};
  39128. bindingsByRoot[ rootUuid ] = bindingByName;
  39129. }
  39130. bindingByName[ trackName ] = binding;
  39131. binding._cacheIndex = bindings.length;
  39132. bindings.push( binding );
  39133. }
  39134. _removeInactiveBinding( binding ) {
  39135. const bindings = this._bindings,
  39136. propBinding = binding.binding,
  39137. rootUuid = propBinding.rootNode.uuid,
  39138. trackName = propBinding.path,
  39139. bindingsByRoot = this._bindingsByRootAndName,
  39140. bindingByName = bindingsByRoot[ rootUuid ],
  39141. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39142. cacheIndex = binding._cacheIndex;
  39143. lastInactiveBinding._cacheIndex = cacheIndex;
  39144. bindings[ cacheIndex ] = lastInactiveBinding;
  39145. bindings.pop();
  39146. delete bindingByName[ trackName ];
  39147. if ( Object.keys( bindingByName ).length === 0 ) {
  39148. delete bindingsByRoot[ rootUuid ];
  39149. }
  39150. }
  39151. _lendBinding( binding ) {
  39152. const bindings = this._bindings,
  39153. prevIndex = binding._cacheIndex,
  39154. lastActiveIndex = this._nActiveBindings ++,
  39155. firstInactiveBinding = bindings[ lastActiveIndex ];
  39156. binding._cacheIndex = lastActiveIndex;
  39157. bindings[ lastActiveIndex ] = binding;
  39158. firstInactiveBinding._cacheIndex = prevIndex;
  39159. bindings[ prevIndex ] = firstInactiveBinding;
  39160. }
  39161. _takeBackBinding( binding ) {
  39162. const bindings = this._bindings,
  39163. prevIndex = binding._cacheIndex,
  39164. firstInactiveIndex = -- this._nActiveBindings,
  39165. lastActiveBinding = bindings[ firstInactiveIndex ];
  39166. binding._cacheIndex = firstInactiveIndex;
  39167. bindings[ firstInactiveIndex ] = binding;
  39168. lastActiveBinding._cacheIndex = prevIndex;
  39169. bindings[ prevIndex ] = lastActiveBinding;
  39170. }
  39171. // Memory management of Interpolants for weight and time scale
  39172. _lendControlInterpolant() {
  39173. const interpolants = this._controlInterpolants,
  39174. lastActiveIndex = this._nActiveControlInterpolants ++;
  39175. let interpolant = interpolants[ lastActiveIndex ];
  39176. if ( interpolant === undefined ) {
  39177. interpolant = new LinearInterpolant(
  39178. new Float32Array( 2 ), new Float32Array( 2 ),
  39179. 1, _controlInterpolantsResultBuffer );
  39180. interpolant.__cacheIndex = lastActiveIndex;
  39181. interpolants[ lastActiveIndex ] = interpolant;
  39182. }
  39183. return interpolant;
  39184. }
  39185. _takeBackControlInterpolant( interpolant ) {
  39186. const interpolants = this._controlInterpolants,
  39187. prevIndex = interpolant.__cacheIndex,
  39188. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39189. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39190. interpolant.__cacheIndex = firstInactiveIndex;
  39191. interpolants[ firstInactiveIndex ] = interpolant;
  39192. lastActiveInterpolant.__cacheIndex = prevIndex;
  39193. interpolants[ prevIndex ] = lastActiveInterpolant;
  39194. }
  39195. /**
  39196. * Returns an instance of {@link AnimationAction} for the passed clip.
  39197. *
  39198. * If an action fitting the clip and root parameters doesn't yet exist, it
  39199. * will be created by this method. Calling this method several times with the
  39200. * same clip and root parameters always returns the same action.
  39201. *
  39202. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39203. * @param {Object3D} [optionalRoot] - An alternative root object.
  39204. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39205. * @return {?AnimationAction} The animation action.
  39206. */
  39207. clipAction( clip, optionalRoot, blendMode ) {
  39208. const root = optionalRoot || this._root,
  39209. rootUuid = root.uuid;
  39210. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39211. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39212. const actionsForClip = this._actionsByClip[ clipUuid ];
  39213. let prototypeAction = null;
  39214. if ( blendMode === undefined ) {
  39215. if ( clipObject !== null ) {
  39216. blendMode = clipObject.blendMode;
  39217. } else {
  39218. blendMode = NormalAnimationBlendMode;
  39219. }
  39220. }
  39221. if ( actionsForClip !== undefined ) {
  39222. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39223. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39224. return existingAction;
  39225. }
  39226. // we know the clip, so we don't have to parse all
  39227. // the bindings again but can just copy
  39228. prototypeAction = actionsForClip.knownActions[ 0 ];
  39229. // also, take the clip from the prototype action
  39230. if ( clipObject === null )
  39231. clipObject = prototypeAction._clip;
  39232. }
  39233. // clip must be known when specified via string
  39234. if ( clipObject === null ) return null;
  39235. // allocate all resources required to run it
  39236. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39237. this._bindAction( newAction, prototypeAction );
  39238. // and make the action known to the memory manager
  39239. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39240. return newAction;
  39241. }
  39242. /**
  39243. * Returns an existing animation action for the passed clip.
  39244. *
  39245. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39246. * @param {Object3D} [optionalRoot] - An alternative root object.
  39247. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39248. */
  39249. existingAction( clip, optionalRoot ) {
  39250. const root = optionalRoot || this._root,
  39251. rootUuid = root.uuid,
  39252. clipObject = typeof clip === 'string' ?
  39253. AnimationClip.findByName( root, clip ) : clip,
  39254. clipUuid = clipObject ? clipObject.uuid : clip,
  39255. actionsForClip = this._actionsByClip[ clipUuid ];
  39256. if ( actionsForClip !== undefined ) {
  39257. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39258. }
  39259. return null;
  39260. }
  39261. /**
  39262. * Deactivates all previously scheduled actions on this mixer.
  39263. *
  39264. * @return {AnimationMixer} A reference to this animation mixer.
  39265. */
  39266. stopAllAction() {
  39267. const actions = this._actions,
  39268. nActions = this._nActiveActions;
  39269. for ( let i = nActions - 1; i >= 0; -- i ) {
  39270. actions[ i ].stop();
  39271. }
  39272. return this;
  39273. }
  39274. /**
  39275. * Advances the global mixer time and updates the animation.
  39276. *
  39277. * This is usually done in the render loop by passing the delta
  39278. * time from {@link Clock} or {@link Timer}.
  39279. *
  39280. * @param {number} deltaTime - The delta time in seconds.
  39281. * @return {AnimationMixer} A reference to this animation mixer.
  39282. */
  39283. update( deltaTime ) {
  39284. deltaTime *= this.timeScale;
  39285. const actions = this._actions,
  39286. nActions = this._nActiveActions,
  39287. time = this.time += deltaTime,
  39288. timeDirection = Math.sign( deltaTime ),
  39289. accuIndex = this._accuIndex ^= 1;
  39290. // run active actions
  39291. for ( let i = 0; i !== nActions; ++ i ) {
  39292. const action = actions[ i ];
  39293. action._update( time, deltaTime, timeDirection, accuIndex );
  39294. }
  39295. // update scene graph
  39296. const bindings = this._bindings,
  39297. nBindings = this._nActiveBindings;
  39298. for ( let i = 0; i !== nBindings; ++ i ) {
  39299. bindings[ i ].apply( accuIndex );
  39300. }
  39301. return this;
  39302. }
  39303. /**
  39304. * Sets the global mixer to a specific time and updates the animation accordingly.
  39305. *
  39306. * This is useful when you need to jump to an exact time in an animation. The
  39307. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39308. *
  39309. * @param {number} time - The time to set in seconds.
  39310. * @return {AnimationMixer} A reference to this animation mixer.
  39311. */
  39312. setTime( time ) {
  39313. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39314. for ( let i = 0; i < this._actions.length; i ++ ) {
  39315. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39316. }
  39317. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39318. }
  39319. /**
  39320. * Returns this mixer's root object.
  39321. *
  39322. * @return {Object3D} The mixer's root object.
  39323. */
  39324. getRoot() {
  39325. return this._root;
  39326. }
  39327. /**
  39328. * Deallocates all memory resources for a clip. Before using this method make
  39329. * sure to call {@link AnimationAction#stop} for all related actions.
  39330. *
  39331. * @param {AnimationClip} clip - The clip to uncache.
  39332. */
  39333. uncacheClip( clip ) {
  39334. const actions = this._actions,
  39335. clipUuid = clip.uuid,
  39336. actionsByClip = this._actionsByClip,
  39337. actionsForClip = actionsByClip[ clipUuid ];
  39338. if ( actionsForClip !== undefined ) {
  39339. // note: just calling _removeInactiveAction would mess up the
  39340. // iteration state and also require updating the state we can
  39341. // just throw away
  39342. const actionsToRemove = actionsForClip.knownActions;
  39343. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39344. const action = actionsToRemove[ i ];
  39345. this._deactivateAction( action );
  39346. const cacheIndex = action._cacheIndex,
  39347. lastInactiveAction = actions[ actions.length - 1 ];
  39348. action._cacheIndex = null;
  39349. action._byClipCacheIndex = null;
  39350. lastInactiveAction._cacheIndex = cacheIndex;
  39351. actions[ cacheIndex ] = lastInactiveAction;
  39352. actions.pop();
  39353. this._removeInactiveBindingsForAction( action );
  39354. }
  39355. delete actionsByClip[ clipUuid ];
  39356. }
  39357. }
  39358. /**
  39359. * Deallocates all memory resources for a root object. Before using this
  39360. * method make sure to call {@link AnimationAction#stop} for all related
  39361. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39362. * mixer operates on a single root.
  39363. *
  39364. * @param {Object3D} root - The root object to uncache.
  39365. */
  39366. uncacheRoot( root ) {
  39367. const rootUuid = root.uuid,
  39368. actionsByClip = this._actionsByClip;
  39369. for ( const clipUuid in actionsByClip ) {
  39370. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39371. action = actionByRoot[ rootUuid ];
  39372. if ( action !== undefined ) {
  39373. this._deactivateAction( action );
  39374. this._removeInactiveAction( action );
  39375. }
  39376. }
  39377. const bindingsByRoot = this._bindingsByRootAndName,
  39378. bindingByName = bindingsByRoot[ rootUuid ];
  39379. if ( bindingByName !== undefined ) {
  39380. for ( const trackName in bindingByName ) {
  39381. const binding = bindingByName[ trackName ];
  39382. binding.restoreOriginalState();
  39383. this._removeInactiveBinding( binding );
  39384. }
  39385. }
  39386. }
  39387. /**
  39388. * Deallocates all memory resources for an action. The action is identified by the
  39389. * given clip and an optional root object. Before using this method make
  39390. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39391. *
  39392. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39393. * @param {Object3D} [optionalRoot] - An alternative root object.
  39394. */
  39395. uncacheAction( clip, optionalRoot ) {
  39396. const action = this.existingAction( clip, optionalRoot );
  39397. if ( action !== null ) {
  39398. this._deactivateAction( action );
  39399. this._removeInactiveAction( action );
  39400. }
  39401. }
  39402. }
  39403. /**
  39404. * Represents a 3D render target.
  39405. *
  39406. * @augments RenderTarget
  39407. */
  39408. class RenderTarget3D extends RenderTarget {
  39409. /**
  39410. * Constructs a new 3D render target.
  39411. *
  39412. * @param {number} [width=1] - The width of the render target.
  39413. * @param {number} [height=1] - The height of the render target.
  39414. * @param {number} [depth=1] - The height of the render target.
  39415. * @param {RenderTarget~Options} [options] - The configuration object.
  39416. */
  39417. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39418. super( width, height, options );
  39419. /**
  39420. * This flag can be used for type testing.
  39421. *
  39422. * @type {boolean}
  39423. * @readonly
  39424. * @default true
  39425. */
  39426. this.isRenderTarget3D = true;
  39427. this.depth = depth;
  39428. /**
  39429. * Overwritten with a different texture type.
  39430. *
  39431. * @type {Data3DTexture}
  39432. */
  39433. this.texture = new Data3DTexture( null, width, height, depth );
  39434. this._setTextureOptions( options );
  39435. this.texture.isRenderTargetTexture = true;
  39436. }
  39437. }
  39438. /**
  39439. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39440. *
  39441. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39442. * ```js
  39443. * uniforms: {
  39444. * time: { value: 1.0 },
  39445. * resolution: new Uniform( new Vector2() )
  39446. * };
  39447. * ```
  39448. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39449. * in {@link WebGLRenderer}.
  39450. */
  39451. class Uniform {
  39452. /**
  39453. * Constructs a new uniform.
  39454. *
  39455. * @param {any} value - The uniform value.
  39456. */
  39457. constructor( value ) {
  39458. /**
  39459. * The uniform value.
  39460. *
  39461. * @type {any}
  39462. */
  39463. this.value = value;
  39464. }
  39465. /**
  39466. * Returns a new uniform with copied values from this instance.
  39467. * If the value has a `clone()` method, the value is cloned as well.
  39468. *
  39469. * @return {Uniform} A clone of this instance.
  39470. */
  39471. clone() {
  39472. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39473. }
  39474. }
  39475. let _id$1 = 0;
  39476. /**
  39477. * A class for managing multiple uniforms in a single group. The renderer will process
  39478. * such a definition as a single UBO.
  39479. *
  39480. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39481. * in {@link WebGLRenderer}.
  39482. *
  39483. * @augments EventDispatcher
  39484. */
  39485. class UniformsGroup extends EventDispatcher {
  39486. /**
  39487. * Constructs a new uniforms group.
  39488. */
  39489. constructor() {
  39490. super();
  39491. /**
  39492. * This flag can be used for type testing.
  39493. *
  39494. * @type {boolean}
  39495. * @readonly
  39496. * @default true
  39497. */
  39498. this.isUniformsGroup = true;
  39499. /**
  39500. * The ID of the 3D object.
  39501. *
  39502. * @name UniformsGroup#id
  39503. * @type {number}
  39504. * @readonly
  39505. */
  39506. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39507. /**
  39508. * The name of the uniforms group.
  39509. *
  39510. * @type {string}
  39511. */
  39512. this.name = '';
  39513. /**
  39514. * The buffer usage.
  39515. *
  39516. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39517. * @default StaticDrawUsage
  39518. */
  39519. this.usage = StaticDrawUsage;
  39520. /**
  39521. * An array holding the uniforms.
  39522. *
  39523. * @type {Array<Uniform>}
  39524. */
  39525. this.uniforms = [];
  39526. }
  39527. /**
  39528. * Adds the given uniform to this uniforms group.
  39529. *
  39530. * @param {Uniform} uniform - The uniform to add.
  39531. * @return {UniformsGroup} A reference to this uniforms group.
  39532. */
  39533. add( uniform ) {
  39534. this.uniforms.push( uniform );
  39535. return this;
  39536. }
  39537. /**
  39538. * Removes the given uniform from this uniforms group.
  39539. *
  39540. * @param {Uniform} uniform - The uniform to remove.
  39541. * @return {UniformsGroup} A reference to this uniforms group.
  39542. */
  39543. remove( uniform ) {
  39544. const index = this.uniforms.indexOf( uniform );
  39545. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39546. return this;
  39547. }
  39548. /**
  39549. * Sets the name of this uniforms group.
  39550. *
  39551. * @param {string} name - The name to set.
  39552. * @return {UniformsGroup} A reference to this uniforms group.
  39553. */
  39554. setName( name ) {
  39555. this.name = name;
  39556. return this;
  39557. }
  39558. /**
  39559. * Sets the usage of this uniforms group.
  39560. *
  39561. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39562. * @return {UniformsGroup} A reference to this uniforms group.
  39563. */
  39564. setUsage( value ) {
  39565. this.usage = value;
  39566. return this;
  39567. }
  39568. /**
  39569. * Frees the GPU-related resources allocated by this instance. Call this
  39570. * method whenever this instance is no longer used in your app.
  39571. *
  39572. * @fires Texture#dispose
  39573. */
  39574. dispose() {
  39575. this.dispatchEvent( { type: 'dispose' } );
  39576. }
  39577. /**
  39578. * Copies the values of the given uniforms group to this instance.
  39579. *
  39580. * @param {UniformsGroup} source - The uniforms group to copy.
  39581. * @return {UniformsGroup} A reference to this uniforms group.
  39582. */
  39583. copy( source ) {
  39584. this.name = source.name;
  39585. this.usage = source.usage;
  39586. const uniformsSource = source.uniforms;
  39587. this.uniforms.length = 0;
  39588. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39589. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39590. for ( let j = 0; j < uniforms.length; j ++ ) {
  39591. this.uniforms.push( uniforms[ j ].clone() );
  39592. }
  39593. }
  39594. return this;
  39595. }
  39596. /**
  39597. * Returns a new uniforms group with copied values from this instance.
  39598. *
  39599. * @return {UniformsGroup} A clone of this instance.
  39600. */
  39601. clone() {
  39602. return new this.constructor().copy( this );
  39603. }
  39604. }
  39605. /**
  39606. * An instanced version of an interleaved buffer.
  39607. *
  39608. * @augments InterleavedBuffer
  39609. */
  39610. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39611. /**
  39612. * Constructs a new instanced interleaved buffer.
  39613. *
  39614. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39615. * @param {number} stride - The number of typed-array elements per vertex.
  39616. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39617. */
  39618. constructor( array, stride, meshPerAttribute = 1 ) {
  39619. super( array, stride );
  39620. /**
  39621. * This flag can be used for type testing.
  39622. *
  39623. * @type {boolean}
  39624. * @readonly
  39625. * @default true
  39626. */
  39627. this.isInstancedInterleavedBuffer = true;
  39628. /**
  39629. * Defines how often a value of this buffer attribute should be repeated,
  39630. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39631. *
  39632. * @type {number}
  39633. * @default 1
  39634. */
  39635. this.meshPerAttribute = meshPerAttribute;
  39636. }
  39637. copy( source ) {
  39638. super.copy( source );
  39639. this.meshPerAttribute = source.meshPerAttribute;
  39640. return this;
  39641. }
  39642. clone( data ) {
  39643. const ib = super.clone( data );
  39644. ib.meshPerAttribute = this.meshPerAttribute;
  39645. return ib;
  39646. }
  39647. toJSON( data ) {
  39648. const json = super.toJSON( data );
  39649. json.isInstancedInterleavedBuffer = true;
  39650. json.meshPerAttribute = this.meshPerAttribute;
  39651. return json;
  39652. }
  39653. }
  39654. /**
  39655. * An alternative version of a buffer attribute with more control over the VBO.
  39656. *
  39657. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39658. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39659. *
  39660. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39661. * or even produces the VBOs in question.
  39662. *
  39663. * Notice that this class can only be used with {@link WebGLRenderer}.
  39664. */
  39665. class GLBufferAttribute {
  39666. /**
  39667. * Constructs a new GL buffer attribute.
  39668. *
  39669. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39670. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39671. * @param {number} itemSize - The item size.
  39672. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39673. * @param {number} count - The expected number of vertices in VBO.
  39674. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39675. */
  39676. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39677. /**
  39678. * This flag can be used for type testing.
  39679. *
  39680. * @type {boolean}
  39681. * @readonly
  39682. * @default true
  39683. */
  39684. this.isGLBufferAttribute = true;
  39685. /**
  39686. * The name of the buffer attribute.
  39687. *
  39688. * @type {string}
  39689. */
  39690. this.name = '';
  39691. /**
  39692. * The native WebGL buffer.
  39693. *
  39694. * @type {WebGLBuffer}
  39695. */
  39696. this.buffer = buffer;
  39697. /**
  39698. * The native data type.
  39699. *
  39700. * @type {number}
  39701. */
  39702. this.type = type;
  39703. /**
  39704. * The item size, see {@link BufferAttribute#itemSize}.
  39705. *
  39706. * @type {number}
  39707. */
  39708. this.itemSize = itemSize;
  39709. /**
  39710. * The corresponding size (in bytes) for the given `type` parameter.
  39711. *
  39712. * @type {number}
  39713. */
  39714. this.elementSize = elementSize;
  39715. /**
  39716. * The expected number of vertices in VBO.
  39717. *
  39718. * @type {number}
  39719. */
  39720. this.count = count;
  39721. /**
  39722. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39723. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39724. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39725. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39726. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39727. *
  39728. * @type {boolean}
  39729. */
  39730. this.normalized = normalized;
  39731. /**
  39732. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39733. *
  39734. * @type {number}
  39735. */
  39736. this.version = 0;
  39737. }
  39738. /**
  39739. * Flag to indicate that this attribute has changed and should be re-sent to
  39740. * the GPU. Set this to `true` when you modify the value of the array.
  39741. *
  39742. * @type {number}
  39743. * @default false
  39744. * @param {boolean} value
  39745. */
  39746. set needsUpdate( value ) {
  39747. if ( value === true ) this.version ++;
  39748. }
  39749. /**
  39750. * Sets the given native WebGL buffer.
  39751. *
  39752. * @param {WebGLBuffer} buffer - The buffer to set.
  39753. * @return {BufferAttribute} A reference to this instance.
  39754. */
  39755. setBuffer( buffer ) {
  39756. this.buffer = buffer;
  39757. return this;
  39758. }
  39759. /**
  39760. * Sets the given native data type and element size.
  39761. *
  39762. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39763. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39764. * @return {BufferAttribute} A reference to this instance.
  39765. */
  39766. setType( type, elementSize ) {
  39767. this.type = type;
  39768. this.elementSize = elementSize;
  39769. return this;
  39770. }
  39771. /**
  39772. * Sets the item size.
  39773. *
  39774. * @param {number} itemSize - The item size.
  39775. * @return {BufferAttribute} A reference to this instance.
  39776. */
  39777. setItemSize( itemSize ) {
  39778. this.itemSize = itemSize;
  39779. return this;
  39780. }
  39781. /**
  39782. * Sets the count (the expected number of vertices in VBO).
  39783. *
  39784. * @param {number} count - The count.
  39785. * @return {BufferAttribute} A reference to this instance.
  39786. */
  39787. setCount( count ) {
  39788. this.count = count;
  39789. return this;
  39790. }
  39791. }
  39792. const _matrix = /*@__PURE__*/ new Matrix4();
  39793. /**
  39794. * This class is designed to assist with raycasting. Raycasting is used for
  39795. * mouse picking (working out what objects in the 3d space the mouse is over)
  39796. * amongst other things.
  39797. */
  39798. class Raycaster {
  39799. /**
  39800. * Constructs a new raycaster.
  39801. *
  39802. * @param {Vector3} origin - The origin vector where the ray casts from.
  39803. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39804. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39805. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39806. */
  39807. constructor( origin, direction, near = 0, far = Infinity ) {
  39808. /**
  39809. * The ray used for raycasting.
  39810. *
  39811. * @type {Ray}
  39812. */
  39813. this.ray = new Ray( origin, direction );
  39814. /**
  39815. * All results returned are further away than near. Near can't be negative.
  39816. *
  39817. * @type {number}
  39818. * @default 0
  39819. */
  39820. this.near = near;
  39821. /**
  39822. * All results returned are closer than far. Far can't be lower than near.
  39823. *
  39824. * @type {number}
  39825. * @default Infinity
  39826. */
  39827. this.far = far;
  39828. /**
  39829. * The camera to use when raycasting against view-dependent objects such as
  39830. * billboarded objects like sprites. This field can be set manually or
  39831. * is set when calling `setFromCamera()`.
  39832. *
  39833. * @type {?Camera}
  39834. * @default null
  39835. */
  39836. this.camera = null;
  39837. /**
  39838. * Allows to selectively ignore 3D objects when performing intersection tests.
  39839. * The following code example ensures that only 3D objects on layer `1` will be
  39840. * honored by raycaster.
  39841. * ```js
  39842. * raycaster.layers.set( 1 );
  39843. * object.layers.enable( 1 );
  39844. * ```
  39845. *
  39846. * @type {Layers}
  39847. */
  39848. this.layers = new Layers();
  39849. /**
  39850. * A parameter object that configures the raycasting. It has the structure:
  39851. *
  39852. * ```
  39853. * {
  39854. * Mesh: {},
  39855. * Line: { threshold: 1 },
  39856. * LOD: {},
  39857. * Points: { threshold: 1 },
  39858. * Sprite: {}
  39859. * }
  39860. * ```
  39861. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39862. *
  39863. * @type {Object}
  39864. */
  39865. this.params = {
  39866. Mesh: {},
  39867. Line: { threshold: 1 },
  39868. LOD: {},
  39869. Points: { threshold: 1 },
  39870. Sprite: {}
  39871. };
  39872. }
  39873. /**
  39874. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39875. *
  39876. * @param {Vector3} origin - The origin vector where the ray casts from.
  39877. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39878. */
  39879. set( origin, direction ) {
  39880. // direction is assumed to be normalized (for accurate distance calculations)
  39881. this.ray.set( origin, direction );
  39882. }
  39883. /**
  39884. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39885. *
  39886. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39887. * X and Y components should be between `-1` and `1`.
  39888. * @param {Camera} camera - The camera from which the ray should originate.
  39889. */
  39890. setFromCamera( coords, camera ) {
  39891. if ( camera.isPerspectiveCamera ) {
  39892. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39893. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39894. this.camera = camera;
  39895. } else if ( camera.isOrthographicCamera ) {
  39896. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39897. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39898. this.camera = camera;
  39899. } else {
  39900. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  39901. }
  39902. }
  39903. /**
  39904. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39905. *
  39906. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39907. * @return {Raycaster} A reference to this raycaster.
  39908. */
  39909. setFromXRController( controller ) {
  39910. _matrix.identity().extractRotation( controller.matrixWorld );
  39911. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39912. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39913. return this;
  39914. }
  39915. /**
  39916. * The intersection point of a raycaster intersection test.
  39917. * @typedef {Object} Raycaster~Intersection
  39918. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39919. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39920. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39921. * @property {Vector3} point - The intersection point, in world coordinates.
  39922. * @property {Object} face - The face that has been intersected.
  39923. * @property {number} faceIndex - The face index.
  39924. * @property {Object3D} object - The 3D object that has been intersected.
  39925. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39926. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39927. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  39928. * @property {number} instanceId - The index number of the instance where the ray
  39929. * intersects the {@link InstancedMesh}.
  39930. */
  39931. /**
  39932. * Checks all intersection between the ray and the object with or without the
  39933. * descendants. Intersections are returned sorted by distance, closest first.
  39934. *
  39935. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39936. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39937. * differently to ray casting than lines or points.
  39938. *
  39939. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39940. * to be detected; intersections of the ray passing through the back of a face will not
  39941. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39942. * to `THREE.DoubleSide`.
  39943. *
  39944. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39945. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39946. * Otherwise it only checks intersection with the object.
  39947. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39948. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39949. */
  39950. intersectObject( object, recursive = true, intersects = [] ) {
  39951. intersect( object, this, intersects, recursive );
  39952. intersects.sort( ascSort );
  39953. return intersects;
  39954. }
  39955. /**
  39956. * Checks all intersection between the ray and the objects with or without
  39957. * the descendants. Intersections are returned sorted by distance, closest first.
  39958. *
  39959. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39960. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39961. * Otherwise it only checks intersection with the object.
  39962. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39963. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39964. */
  39965. intersectObjects( objects, recursive = true, intersects = [] ) {
  39966. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39967. intersect( objects[ i ], this, intersects, recursive );
  39968. }
  39969. intersects.sort( ascSort );
  39970. return intersects;
  39971. }
  39972. }
  39973. function ascSort( a, b ) {
  39974. return a.distance - b.distance;
  39975. }
  39976. function intersect( object, raycaster, intersects, recursive ) {
  39977. let propagate = true;
  39978. if ( object.layers.test( raycaster.layers ) ) {
  39979. const result = object.raycast( raycaster, intersects );
  39980. if ( result === false ) propagate = false;
  39981. }
  39982. if ( propagate === true && recursive === true ) {
  39983. const children = object.children;
  39984. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39985. intersect( children[ i ], raycaster, intersects, true );
  39986. }
  39987. }
  39988. }
  39989. /**
  39990. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39991. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39992. *
  39993. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39994. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39995. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39996. * is inactive (e.g. tab switched or browser hidden).
  39997. *
  39998. * ```js
  39999. * const timer = new Timer();
  40000. * timer.connect( document ); // use Page Visibility API
  40001. * ```
  40002. */
  40003. class Timer {
  40004. /**
  40005. * Constructs a new timer.
  40006. */
  40007. constructor() {
  40008. this._previousTime = 0;
  40009. this._currentTime = 0;
  40010. this._startTime = performance.now();
  40011. this._delta = 0;
  40012. this._elapsed = 0;
  40013. this._timescale = 1;
  40014. this._document = null;
  40015. this._pageVisibilityHandler = null;
  40016. }
  40017. /**
  40018. * Connect the timer to the given document.Calling this method is not mandatory to
  40019. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40020. * delta values.
  40021. *
  40022. * @param {Document} document - The document.
  40023. */
  40024. connect( document ) {
  40025. this._document = document;
  40026. // use Page Visibility API to avoid large time delta values
  40027. if ( document.hidden !== undefined ) {
  40028. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40029. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40030. }
  40031. }
  40032. /**
  40033. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40034. */
  40035. disconnect() {
  40036. if ( this._pageVisibilityHandler !== null ) {
  40037. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40038. this._pageVisibilityHandler = null;
  40039. }
  40040. this._document = null;
  40041. }
  40042. /**
  40043. * Returns the time delta in seconds.
  40044. *
  40045. * @return {number} The time delta in second.
  40046. */
  40047. getDelta() {
  40048. return this._delta / 1000;
  40049. }
  40050. /**
  40051. * Returns the elapsed time in seconds.
  40052. *
  40053. * @return {number} The elapsed time in second.
  40054. */
  40055. getElapsed() {
  40056. return this._elapsed / 1000;
  40057. }
  40058. /**
  40059. * Returns the timescale.
  40060. *
  40061. * @return {number} The timescale.
  40062. */
  40063. getTimescale() {
  40064. return this._timescale;
  40065. }
  40066. /**
  40067. * Sets the given timescale which scale the time delta computation
  40068. * in `update()`.
  40069. *
  40070. * @param {number} timescale - The timescale to set.
  40071. * @return {Timer} A reference to this timer.
  40072. */
  40073. setTimescale( timescale ) {
  40074. this._timescale = timescale;
  40075. return this;
  40076. }
  40077. /**
  40078. * Resets the time computation for the current simulation step.
  40079. *
  40080. * @return {Timer} A reference to this timer.
  40081. */
  40082. reset() {
  40083. this._currentTime = performance.now() - this._startTime;
  40084. return this;
  40085. }
  40086. /**
  40087. * Can be used to free all internal resources. Usually called when
  40088. * the timer instance isn't required anymore.
  40089. */
  40090. dispose() {
  40091. this.disconnect();
  40092. }
  40093. /**
  40094. * Updates the internal state of the timer. This method should be called
  40095. * once per simulation step and before you perform queries against the timer
  40096. * (e.g. via `getDelta()`).
  40097. *
  40098. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40099. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40100. * time will be determined with `performance.now`.
  40101. * @return {Timer} A reference to this timer.
  40102. */
  40103. update( timestamp ) {
  40104. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40105. this._delta = 0;
  40106. } else {
  40107. this._previousTime = this._currentTime;
  40108. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40109. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40110. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40111. }
  40112. return this;
  40113. }
  40114. }
  40115. function handleVisibilityChange() {
  40116. if ( this._document.hidden === false ) this.reset();
  40117. }
  40118. /**
  40119. * This class can be used to represent points in 3D space as
  40120. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40121. */
  40122. class Spherical {
  40123. /**
  40124. * Constructs a new spherical.
  40125. *
  40126. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40127. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40128. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40129. */
  40130. constructor( radius = 1, phi = 0, theta = 0 ) {
  40131. /**
  40132. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40133. *
  40134. * @type {number}
  40135. * @default 1
  40136. */
  40137. this.radius = radius;
  40138. /**
  40139. * The polar angle in radians from the y (up) axis.
  40140. *
  40141. * @type {number}
  40142. * @default 0
  40143. */
  40144. this.phi = phi;
  40145. /**
  40146. * The equator/azimuthal angle in radians around the y (up) axis.
  40147. *
  40148. * @type {number}
  40149. * @default 0
  40150. */
  40151. this.theta = theta;
  40152. }
  40153. /**
  40154. * Sets the spherical components by copying the given values.
  40155. *
  40156. * @param {number} radius - The radius.
  40157. * @param {number} phi - The polar angle.
  40158. * @param {number} theta - The azimuthal angle.
  40159. * @return {Spherical} A reference to this spherical.
  40160. */
  40161. set( radius, phi, theta ) {
  40162. this.radius = radius;
  40163. this.phi = phi;
  40164. this.theta = theta;
  40165. return this;
  40166. }
  40167. /**
  40168. * Copies the values of the given spherical to this instance.
  40169. *
  40170. * @param {Spherical} other - The spherical to copy.
  40171. * @return {Spherical} A reference to this spherical.
  40172. */
  40173. copy( other ) {
  40174. this.radius = other.radius;
  40175. this.phi = other.phi;
  40176. this.theta = other.theta;
  40177. return this;
  40178. }
  40179. /**
  40180. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40181. * `0.000001`.
  40182. *
  40183. * @return {Spherical} A reference to this spherical.
  40184. */
  40185. makeSafe() {
  40186. const EPS = 0.000001;
  40187. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40188. return this;
  40189. }
  40190. /**
  40191. * Sets the spherical components from the given vector which is assumed to hold
  40192. * Cartesian coordinates.
  40193. *
  40194. * @param {Vector3} v - The vector to set.
  40195. * @return {Spherical} A reference to this spherical.
  40196. */
  40197. setFromVector3( v ) {
  40198. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40199. }
  40200. /**
  40201. * Sets the spherical components from the given Cartesian coordinates.
  40202. *
  40203. * @param {number} x - The x value.
  40204. * @param {number} y - The y value.
  40205. * @param {number} z - The z value.
  40206. * @return {Spherical} A reference to this spherical.
  40207. */
  40208. setFromCartesianCoords( x, y, z ) {
  40209. this.radius = Math.sqrt( x * x + y * y + z * z );
  40210. if ( this.radius === 0 ) {
  40211. this.theta = 0;
  40212. this.phi = 0;
  40213. } else {
  40214. this.theta = Math.atan2( x, z );
  40215. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40216. }
  40217. return this;
  40218. }
  40219. /**
  40220. * Returns a new spherical with copied values from this instance.
  40221. *
  40222. * @return {Spherical} A clone of this instance.
  40223. */
  40224. clone() {
  40225. return new this.constructor().copy( this );
  40226. }
  40227. }
  40228. /**
  40229. * This class can be used to represent points in 3D space as
  40230. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40231. */
  40232. class Cylindrical {
  40233. /**
  40234. * Constructs a new cylindrical.
  40235. *
  40236. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40237. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40238. * @param {number} [y=0] - The height above the x-z plane.
  40239. */
  40240. constructor( radius = 1, theta = 0, y = 0 ) {
  40241. /**
  40242. * The distance from the origin to a point in the x-z plane.
  40243. *
  40244. * @type {number}
  40245. * @default 1
  40246. */
  40247. this.radius = radius;
  40248. /**
  40249. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40250. *
  40251. * @type {number}
  40252. * @default 0
  40253. */
  40254. this.theta = theta;
  40255. /**
  40256. * The height above the x-z plane.
  40257. *
  40258. * @type {number}
  40259. * @default 0
  40260. */
  40261. this.y = y;
  40262. }
  40263. /**
  40264. * Sets the cylindrical components by copying the given values.
  40265. *
  40266. * @param {number} radius - The radius.
  40267. * @param {number} theta - The theta angle.
  40268. * @param {number} y - The height value.
  40269. * @return {Cylindrical} A reference to this cylindrical.
  40270. */
  40271. set( radius, theta, y ) {
  40272. this.radius = radius;
  40273. this.theta = theta;
  40274. this.y = y;
  40275. return this;
  40276. }
  40277. /**
  40278. * Copies the values of the given cylindrical to this instance.
  40279. *
  40280. * @param {Cylindrical} other - The cylindrical to copy.
  40281. * @return {Cylindrical} A reference to this cylindrical.
  40282. */
  40283. copy( other ) {
  40284. this.radius = other.radius;
  40285. this.theta = other.theta;
  40286. this.y = other.y;
  40287. return this;
  40288. }
  40289. /**
  40290. * Sets the cylindrical components from the given vector which is assumed to hold
  40291. * Cartesian coordinates.
  40292. *
  40293. * @param {Vector3} v - The vector to set.
  40294. * @return {Cylindrical} A reference to this cylindrical.
  40295. */
  40296. setFromVector3( v ) {
  40297. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40298. }
  40299. /**
  40300. * Sets the cylindrical components from the given Cartesian coordinates.
  40301. *
  40302. * @param {number} x - The x value.
  40303. * @param {number} y - The x value.
  40304. * @param {number} z - The x value.
  40305. * @return {Cylindrical} A reference to this cylindrical.
  40306. */
  40307. setFromCartesianCoords( x, y, z ) {
  40308. this.radius = Math.sqrt( x * x + z * z );
  40309. this.theta = Math.atan2( x, z );
  40310. this.y = y;
  40311. return this;
  40312. }
  40313. /**
  40314. * Returns a new cylindrical with copied values from this instance.
  40315. *
  40316. * @return {Cylindrical} A clone of this instance.
  40317. */
  40318. clone() {
  40319. return new this.constructor().copy( this );
  40320. }
  40321. }
  40322. /**
  40323. * Represents a 2x2 matrix.
  40324. *
  40325. * A Note on Row-Major and Column-Major Ordering:
  40326. *
  40327. * The constructor and {@link Matrix2#set} method take arguments in
  40328. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40329. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40330. * This means that calling:
  40331. * ```js
  40332. * const m = new THREE.Matrix2();
  40333. * m.set( 11, 12,
  40334. * 21, 22 );
  40335. * ```
  40336. * will result in the elements array containing:
  40337. * ```js
  40338. * m.elements = [ 11, 21,
  40339. * 12, 22 ];
  40340. * ```
  40341. * and internally all calculations are performed using column-major ordering.
  40342. * However, as the actual ordering makes no difference mathematically and
  40343. * most people are used to thinking about matrices in row-major order, the
  40344. * three.js documentation shows matrices in row-major order. Just bear in
  40345. * mind that if you are reading the source code, you'll have to take the
  40346. * transpose of any matrices outlined here to make sense of the calculations.
  40347. */
  40348. class Matrix2 {
  40349. /**
  40350. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40351. * in row-major order. If no arguments are provided, the constructor
  40352. * initializes the matrix as an identity matrix.
  40353. *
  40354. * @param {number} [n11] - 1-1 matrix element.
  40355. * @param {number} [n12] - 1-2 matrix element.
  40356. * @param {number} [n21] - 2-1 matrix element.
  40357. * @param {number} [n22] - 2-2 matrix element.
  40358. */
  40359. constructor( n11, n12, n21, n22 ) {
  40360. /**
  40361. * This flag can be used for type testing.
  40362. *
  40363. * @type {boolean}
  40364. * @readonly
  40365. * @default true
  40366. */
  40367. Matrix2.prototype.isMatrix2 = true;
  40368. /**
  40369. * A column-major list of matrix values.
  40370. *
  40371. * @type {Array<number>}
  40372. */
  40373. this.elements = [
  40374. 1, 0,
  40375. 0, 1,
  40376. ];
  40377. if ( n11 !== undefined ) {
  40378. this.set( n11, n12, n21, n22 );
  40379. }
  40380. }
  40381. /**
  40382. * Sets this matrix to the 2x2 identity matrix.
  40383. *
  40384. * @return {Matrix2} A reference to this matrix.
  40385. */
  40386. identity() {
  40387. this.set(
  40388. 1, 0,
  40389. 0, 1,
  40390. );
  40391. return this;
  40392. }
  40393. /**
  40394. * Sets the elements of the matrix from the given array.
  40395. *
  40396. * @param {Array<number>} array - The matrix elements in column-major order.
  40397. * @param {number} [offset=0] - Index of the first element in the array.
  40398. * @return {Matrix2} A reference to this matrix.
  40399. */
  40400. fromArray( array, offset = 0 ) {
  40401. for ( let i = 0; i < 4; i ++ ) {
  40402. this.elements[ i ] = array[ i + offset ];
  40403. }
  40404. return this;
  40405. }
  40406. /**
  40407. * Sets the elements of the matrix.The arguments are supposed to be
  40408. * in row-major order.
  40409. *
  40410. * @param {number} n11 - 1-1 matrix element.
  40411. * @param {number} n12 - 1-2 matrix element.
  40412. * @param {number} n21 - 2-1 matrix element.
  40413. * @param {number} n22 - 2-2 matrix element.
  40414. * @return {Matrix2} A reference to this matrix.
  40415. */
  40416. set( n11, n12, n21, n22 ) {
  40417. const te = this.elements;
  40418. te[ 0 ] = n11; te[ 2 ] = n12;
  40419. te[ 1 ] = n21; te[ 3 ] = n22;
  40420. return this;
  40421. }
  40422. }
  40423. const _vector$4 = /*@__PURE__*/ new Vector2();
  40424. /**
  40425. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40426. */
  40427. class Box2 {
  40428. /**
  40429. * Constructs a new bounding box.
  40430. *
  40431. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40432. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40433. */
  40434. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40435. /**
  40436. * This flag can be used for type testing.
  40437. *
  40438. * @type {boolean}
  40439. * @readonly
  40440. * @default true
  40441. */
  40442. this.isBox2 = true;
  40443. /**
  40444. * The lower boundary of the box.
  40445. *
  40446. * @type {Vector2}
  40447. */
  40448. this.min = min;
  40449. /**
  40450. * The upper boundary of the box.
  40451. *
  40452. * @type {Vector2}
  40453. */
  40454. this.max = max;
  40455. }
  40456. /**
  40457. * Sets the lower and upper boundaries of this box.
  40458. * Please note that this method only copies the values from the given objects.
  40459. *
  40460. * @param {Vector2} min - The lower boundary of the box.
  40461. * @param {Vector2} max - The upper boundary of the box.
  40462. * @return {Box2} A reference to this bounding box.
  40463. */
  40464. set( min, max ) {
  40465. this.min.copy( min );
  40466. this.max.copy( max );
  40467. return this;
  40468. }
  40469. /**
  40470. * Sets the upper and lower bounds of this box so it encloses the position data
  40471. * in the given array.
  40472. *
  40473. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40474. * @return {Box2} A reference to this bounding box.
  40475. */
  40476. setFromPoints( points ) {
  40477. this.makeEmpty();
  40478. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40479. this.expandByPoint( points[ i ] );
  40480. }
  40481. return this;
  40482. }
  40483. /**
  40484. * Centers this box on the given center vector and sets this box's width, height and
  40485. * depth to the given size values.
  40486. *
  40487. * @param {Vector2} center - The center of the box.
  40488. * @param {Vector2} size - The x and y dimensions of the box.
  40489. * @return {Box2} A reference to this bounding box.
  40490. */
  40491. setFromCenterAndSize( center, size ) {
  40492. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40493. this.min.copy( center ).sub( halfSize );
  40494. this.max.copy( center ).add( halfSize );
  40495. return this;
  40496. }
  40497. /**
  40498. * Returns a new box with copied values from this instance.
  40499. *
  40500. * @return {Box2} A clone of this instance.
  40501. */
  40502. clone() {
  40503. return new this.constructor().copy( this );
  40504. }
  40505. /**
  40506. * Copies the values of the given box to this instance.
  40507. *
  40508. * @param {Box2} box - The box to copy.
  40509. * @return {Box2} A reference to this bounding box.
  40510. */
  40511. copy( box ) {
  40512. this.min.copy( box.min );
  40513. this.max.copy( box.max );
  40514. return this;
  40515. }
  40516. /**
  40517. * Makes this box empty which means in encloses a zero space in 2D.
  40518. *
  40519. * @return {Box2} A reference to this bounding box.
  40520. */
  40521. makeEmpty() {
  40522. this.min.x = this.min.y = + Infinity;
  40523. this.max.x = this.max.y = - Infinity;
  40524. return this;
  40525. }
  40526. /**
  40527. * Returns true if this box includes zero points within its bounds.
  40528. * Note that a box with equal lower and upper bounds still includes one
  40529. * point, the one both bounds share.
  40530. *
  40531. * @return {boolean} Whether this box is empty or not.
  40532. */
  40533. isEmpty() {
  40534. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40535. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40536. }
  40537. /**
  40538. * Returns the center point of this box.
  40539. *
  40540. * @param {Vector2} target - The target vector that is used to store the method's result.
  40541. * @return {Vector2} The center point.
  40542. */
  40543. getCenter( target ) {
  40544. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40545. }
  40546. /**
  40547. * Returns the dimensions of this box.
  40548. *
  40549. * @param {Vector2} target - The target vector that is used to store the method's result.
  40550. * @return {Vector2} The size.
  40551. */
  40552. getSize( target ) {
  40553. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40554. }
  40555. /**
  40556. * Expands the boundaries of this box to include the given point.
  40557. *
  40558. * @param {Vector2} point - The point that should be included by the bounding box.
  40559. * @return {Box2} A reference to this bounding box.
  40560. */
  40561. expandByPoint( point ) {
  40562. this.min.min( point );
  40563. this.max.max( point );
  40564. return this;
  40565. }
  40566. /**
  40567. * Expands this box equilaterally by the given vector. The width of this
  40568. * box will be expanded by the x component of the vector in both
  40569. * directions. The height of this box will be expanded by the y component of
  40570. * the vector in both directions.
  40571. *
  40572. * @param {Vector2} vector - The vector that should expand the bounding box.
  40573. * @return {Box2} A reference to this bounding box.
  40574. */
  40575. expandByVector( vector ) {
  40576. this.min.sub( vector );
  40577. this.max.add( vector );
  40578. return this;
  40579. }
  40580. /**
  40581. * Expands each dimension of the box by the given scalar. If negative, the
  40582. * dimensions of the box will be contracted.
  40583. *
  40584. * @param {number} scalar - The scalar value that should expand the bounding box.
  40585. * @return {Box2} A reference to this bounding box.
  40586. */
  40587. expandByScalar( scalar ) {
  40588. this.min.addScalar( - scalar );
  40589. this.max.addScalar( scalar );
  40590. return this;
  40591. }
  40592. /**
  40593. * Returns `true` if the given point lies within or on the boundaries of this box.
  40594. *
  40595. * @param {Vector2} point - The point to test.
  40596. * @return {boolean} Whether the bounding box contains the given point or not.
  40597. */
  40598. containsPoint( point ) {
  40599. return point.x >= this.min.x && point.x <= this.max.x &&
  40600. point.y >= this.min.y && point.y <= this.max.y;
  40601. }
  40602. /**
  40603. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40604. * If this box and the given one are identical, this function also returns `true`.
  40605. *
  40606. * @param {Box2} box - The bounding box to test.
  40607. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40608. */
  40609. containsBox( box ) {
  40610. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40611. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40612. }
  40613. /**
  40614. * Returns a point as a proportion of this box's width and height.
  40615. *
  40616. * @param {Vector2} point - A point in 2D space.
  40617. * @param {Vector2} target - The target vector that is used to store the method's result.
  40618. * @return {Vector2} A point as a proportion of this box's width and height.
  40619. */
  40620. getParameter( point, target ) {
  40621. // This can potentially have a divide by zero if the box
  40622. // has a size dimension of 0.
  40623. return target.set(
  40624. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40625. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40626. );
  40627. }
  40628. /**
  40629. * Returns `true` if the given bounding box intersects with this bounding box.
  40630. *
  40631. * @param {Box2} box - The bounding box to test.
  40632. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40633. */
  40634. intersectsBox( box ) {
  40635. // using 4 splitting planes to rule out intersections
  40636. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40637. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40638. }
  40639. /**
  40640. * Clamps the given point within the bounds of this box.
  40641. *
  40642. * @param {Vector2} point - The point to clamp.
  40643. * @param {Vector2} target - The target vector that is used to store the method's result.
  40644. * @return {Vector2} The clamped point.
  40645. */
  40646. clampPoint( point, target ) {
  40647. return target.copy( point ).clamp( this.min, this.max );
  40648. }
  40649. /**
  40650. * Returns the euclidean distance from any edge of this box to the specified point. If
  40651. * the given point lies inside of this box, the distance will be `0`.
  40652. *
  40653. * @param {Vector2} point - The point to compute the distance to.
  40654. * @return {number} The euclidean distance.
  40655. */
  40656. distanceToPoint( point ) {
  40657. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40658. }
  40659. /**
  40660. * Computes the intersection of this bounding box and the given one, setting the upper
  40661. * bound of this box to the lesser of the two boxes' upper bounds and the
  40662. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40663. * there's no overlap, makes this box empty.
  40664. *
  40665. * @param {Box2} box - The bounding box to intersect with.
  40666. * @return {Box2} A reference to this bounding box.
  40667. */
  40668. intersect( box ) {
  40669. this.min.max( box.min );
  40670. this.max.min( box.max );
  40671. if ( this.isEmpty() ) this.makeEmpty();
  40672. return this;
  40673. }
  40674. /**
  40675. * Computes the union of this box and another and the given one, setting the upper
  40676. * bound of this box to the greater of the two boxes' upper bounds and the
  40677. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40678. *
  40679. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40680. * @return {Box2} A reference to this bounding box.
  40681. */
  40682. union( box ) {
  40683. this.min.min( box.min );
  40684. this.max.max( box.max );
  40685. return this;
  40686. }
  40687. /**
  40688. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40689. * effectively moving it in 2D space.
  40690. *
  40691. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40692. * @return {Box2} A reference to this bounding box.
  40693. */
  40694. translate( offset ) {
  40695. this.min.add( offset );
  40696. this.max.add( offset );
  40697. return this;
  40698. }
  40699. /**
  40700. * Returns `true` if this bounding box is equal with the given one.
  40701. *
  40702. * @param {Box2} box - The box to test for equality.
  40703. * @return {boolean} Whether this bounding box is equal with the given one.
  40704. */
  40705. equals( box ) {
  40706. return box.min.equals( this.min ) && box.max.equals( this.max );
  40707. }
  40708. }
  40709. const _startP = /*@__PURE__*/ new Vector3();
  40710. const _startEnd = /*@__PURE__*/ new Vector3();
  40711. const _d1 = /*@__PURE__*/ new Vector3();
  40712. const _d2 = /*@__PURE__*/ new Vector3();
  40713. const _r = /*@__PURE__*/ new Vector3();
  40714. const _c1 = /*@__PURE__*/ new Vector3();
  40715. const _c2 = /*@__PURE__*/ new Vector3();
  40716. /**
  40717. * An analytical line segment in 3D space represented by a start and end point.
  40718. */
  40719. class Line3 {
  40720. /**
  40721. * Constructs a new line segment.
  40722. *
  40723. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40724. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40725. */
  40726. constructor( start = new Vector3(), end = new Vector3() ) {
  40727. /**
  40728. * Start of the line segment.
  40729. *
  40730. * @type {Vector3}
  40731. */
  40732. this.start = start;
  40733. /**
  40734. * End of the line segment.
  40735. *
  40736. * @type {Vector3}
  40737. */
  40738. this.end = end;
  40739. }
  40740. /**
  40741. * Sets the start and end values by copying the given vectors.
  40742. *
  40743. * @param {Vector3} start - The start point.
  40744. * @param {Vector3} end - The end point.
  40745. * @return {Line3} A reference to this line segment.
  40746. */
  40747. set( start, end ) {
  40748. this.start.copy( start );
  40749. this.end.copy( end );
  40750. return this;
  40751. }
  40752. /**
  40753. * Copies the values of the given line segment to this instance.
  40754. *
  40755. * @param {Line3} line - The line segment to copy.
  40756. * @return {Line3} A reference to this line segment.
  40757. */
  40758. copy( line ) {
  40759. this.start.copy( line.start );
  40760. this.end.copy( line.end );
  40761. return this;
  40762. }
  40763. /**
  40764. * Returns the center of the line segment.
  40765. *
  40766. * @param {Vector3} target - The target vector that is used to store the method's result.
  40767. * @return {Vector3} The center point.
  40768. */
  40769. getCenter( target ) {
  40770. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40771. }
  40772. /**
  40773. * Returns the delta vector of the line segment's start and end point.
  40774. *
  40775. * @param {Vector3} target - The target vector that is used to store the method's result.
  40776. * @return {Vector3} The delta vector.
  40777. */
  40778. delta( target ) {
  40779. return target.subVectors( this.end, this.start );
  40780. }
  40781. /**
  40782. * Returns the squared Euclidean distance between the line' start and end point.
  40783. *
  40784. * @return {number} The squared Euclidean distance.
  40785. */
  40786. distanceSq() {
  40787. return this.start.distanceToSquared( this.end );
  40788. }
  40789. /**
  40790. * Returns the Euclidean distance between the line' start and end point.
  40791. *
  40792. * @return {number} The Euclidean distance.
  40793. */
  40794. distance() {
  40795. return this.start.distanceTo( this.end );
  40796. }
  40797. /**
  40798. * Returns a vector at a certain position along the line segment.
  40799. *
  40800. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40801. * @param {Vector3} target - The target vector that is used to store the method's result.
  40802. * @return {Vector3} The delta vector.
  40803. */
  40804. at( t, target ) {
  40805. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40806. }
  40807. /**
  40808. * Returns a point parameter based on the closest point as projected on the line segment.
  40809. *
  40810. * @param {Vector3} point - The point for which to return a point parameter.
  40811. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40812. * @return {number} The point parameter.
  40813. */
  40814. closestPointToPointParameter( point, clampToLine ) {
  40815. _startP.subVectors( point, this.start );
  40816. _startEnd.subVectors( this.end, this.start );
  40817. const startEnd2 = _startEnd.dot( _startEnd );
  40818. const startEnd_startP = _startEnd.dot( _startP );
  40819. let t = startEnd_startP / startEnd2;
  40820. if ( clampToLine ) {
  40821. t = clamp( t, 0, 1 );
  40822. }
  40823. return t;
  40824. }
  40825. /**
  40826. * Returns the closest point on the line for a given point.
  40827. *
  40828. * @param {Vector3} point - The point to compute the closest point on the line for.
  40829. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40830. * @param {Vector3} target - The target vector that is used to store the method's result.
  40831. * @return {Vector3} The closest point on the line.
  40832. */
  40833. closestPointToPoint( point, clampToLine, target ) {
  40834. const t = this.closestPointToPointParameter( point, clampToLine );
  40835. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40836. }
  40837. /**
  40838. * Returns the closest squared distance between this line segment and the given one.
  40839. *
  40840. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40841. * @param {Vector3} [c1] - The closest point on this line segment.
  40842. * @param {Vector3} [c2] - The closest point on the given line segment.
  40843. * @return {number} The squared distance between this line segment and the given one.
  40844. */
  40845. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40846. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40847. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40848. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40849. // distance between between S1(s) and S2(t)
  40850. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40851. let s, t;
  40852. const p1 = this.start;
  40853. const p2 = line.start;
  40854. const q1 = this.end;
  40855. const q2 = line.end;
  40856. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40857. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40858. _r.subVectors( p1, p2 );
  40859. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40860. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40861. const f = _d2.dot( _r );
  40862. // Check if either or both segments degenerate into points
  40863. if ( a <= EPSILON && e <= EPSILON ) {
  40864. // Both segments degenerate into points
  40865. c1.copy( p1 );
  40866. c2.copy( p2 );
  40867. c1.sub( c2 );
  40868. return c1.dot( c1 );
  40869. }
  40870. if ( a <= EPSILON ) {
  40871. // First segment degenerates into a point
  40872. s = 0;
  40873. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40874. t = clamp( t, 0, 1 );
  40875. } else {
  40876. const c = _d1.dot( _r );
  40877. if ( e <= EPSILON ) {
  40878. // Second segment degenerates into a point
  40879. t = 0;
  40880. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40881. } else {
  40882. // The general nondegenerate case starts here
  40883. const b = _d1.dot( _d2 );
  40884. const denom = a * e - b * b; // Always nonnegative
  40885. // If segments not parallel, compute closest point on L1 to L2 and
  40886. // clamp to segment S1. Else pick arbitrary s (here 0)
  40887. if ( denom !== 0 ) {
  40888. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40889. } else {
  40890. s = 0;
  40891. }
  40892. // Compute point on L2 closest to S1(s) using
  40893. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40894. t = ( b * s + f ) / e;
  40895. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40896. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40897. // and clamp s to [0, 1]
  40898. if ( t < 0 ) {
  40899. t = 0.;
  40900. s = clamp( - c / a, 0, 1 );
  40901. } else if ( t > 1 ) {
  40902. t = 1;
  40903. s = clamp( ( b - c ) / a, 0, 1 );
  40904. }
  40905. }
  40906. }
  40907. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40908. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40909. c1.sub( c2 );
  40910. return c1.dot( c1 );
  40911. }
  40912. /**
  40913. * Applies a 4x4 transformation matrix to this line segment.
  40914. *
  40915. * @param {Matrix4} matrix - The transformation matrix.
  40916. * @return {Line3} A reference to this line segment.
  40917. */
  40918. applyMatrix4( matrix ) {
  40919. this.start.applyMatrix4( matrix );
  40920. this.end.applyMatrix4( matrix );
  40921. return this;
  40922. }
  40923. /**
  40924. * Returns `true` if this line segment is equal with the given one.
  40925. *
  40926. * @param {Line3} line - The line segment to test for equality.
  40927. * @return {boolean} Whether this line segment is equal with the given one.
  40928. */
  40929. equals( line ) {
  40930. return line.start.equals( this.start ) && line.end.equals( this.end );
  40931. }
  40932. /**
  40933. * Returns a new line segment with copied values from this instance.
  40934. *
  40935. * @return {Line3} A clone of this instance.
  40936. */
  40937. clone() {
  40938. return new this.constructor().copy( this );
  40939. }
  40940. }
  40941. const _vector$3 = /*@__PURE__*/ new Vector3();
  40942. /**
  40943. * This displays a cone shaped helper object for a {@link SpotLight}.
  40944. *
  40945. * ```js
  40946. * const spotLight = new THREE.SpotLight( 0xffffff );
  40947. * spotLight.position.set( 10, 10, 10 );
  40948. * scene.add( spotLight );
  40949. *
  40950. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40951. * scene.add( spotLightHelper );
  40952. * ```
  40953. *
  40954. * @augments Object3D
  40955. */
  40956. class SpotLightHelper extends Object3D {
  40957. /**
  40958. * Constructs a new spot light helper.
  40959. *
  40960. * @param {HemisphereLight} light - The light to be visualized.
  40961. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40962. * the color of the light.
  40963. */
  40964. constructor( light, color ) {
  40965. super();
  40966. /**
  40967. * The light being visualized.
  40968. *
  40969. * @type {SpotLight}
  40970. */
  40971. this.light = light;
  40972. this.matrixAutoUpdate = false;
  40973. /**
  40974. * The color parameter passed in the constructor.
  40975. * If not set, the helper will take the color of the light.
  40976. *
  40977. * @type {number|Color|string}
  40978. */
  40979. this.color = color;
  40980. this.type = 'SpotLightHelper';
  40981. const geometry = new BufferGeometry();
  40982. const positions = [
  40983. 0, 0, 0, 0, 0, 1,
  40984. 0, 0, 0, 1, 0, 1,
  40985. 0, 0, 0, -1, 0, 1,
  40986. 0, 0, 0, 0, 1, 1,
  40987. 0, 0, 0, 0, -1, 1
  40988. ];
  40989. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40990. const p1 = ( i / l ) * Math.PI * 2;
  40991. const p2 = ( j / l ) * Math.PI * 2;
  40992. positions.push(
  40993. Math.cos( p1 ), Math.sin( p1 ), 1,
  40994. Math.cos( p2 ), Math.sin( p2 ), 1
  40995. );
  40996. }
  40997. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40998. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40999. this.cone = new LineSegments( geometry, material );
  41000. this.add( this.cone );
  41001. this.update();
  41002. }
  41003. /**
  41004. * Frees the GPU-related resources allocated by this instance. Call this
  41005. * method whenever this instance is no longer used in your app.
  41006. */
  41007. dispose() {
  41008. this.cone.geometry.dispose();
  41009. this.cone.material.dispose();
  41010. }
  41011. /**
  41012. * Updates the helper to match the position and direction of the
  41013. * light being visualized.
  41014. */
  41015. update() {
  41016. this.light.updateWorldMatrix( true, false );
  41017. this.light.target.updateWorldMatrix( true, false );
  41018. // update the local matrix based on the parent and light target transforms
  41019. if ( this.parent ) {
  41020. this.parent.updateWorldMatrix( true );
  41021. this.matrix
  41022. .copy( this.parent.matrixWorld )
  41023. .invert()
  41024. .multiply( this.light.matrixWorld );
  41025. } else {
  41026. this.matrix.copy( this.light.matrixWorld );
  41027. }
  41028. this.matrixWorld.copy( this.light.matrixWorld );
  41029. const coneLength = this.light.distance ? this.light.distance : 1000;
  41030. const coneWidth = coneLength * Math.tan( this.light.angle );
  41031. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41032. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41033. this.cone.lookAt( _vector$3 );
  41034. if ( this.color !== undefined ) {
  41035. this.cone.material.color.set( this.color );
  41036. } else {
  41037. this.cone.material.color.copy( this.light.color );
  41038. }
  41039. }
  41040. }
  41041. const _vector$2 = /*@__PURE__*/ new Vector3();
  41042. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41043. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41044. /**
  41045. * A helper object to assist with visualizing a {@link Skeleton}.
  41046. *
  41047. * ```js
  41048. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41049. * scene.add( helper );
  41050. * ```
  41051. *
  41052. * @augments LineSegments
  41053. */
  41054. class SkeletonHelper extends LineSegments {
  41055. /**
  41056. * Constructs a new skeleton helper.
  41057. *
  41058. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41059. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41060. */
  41061. constructor( object ) {
  41062. const bones = getBoneList( object );
  41063. const geometry = new BufferGeometry();
  41064. const vertices = [];
  41065. const colors = [];
  41066. for ( let i = 0; i < bones.length; i ++ ) {
  41067. const bone = bones[ i ];
  41068. if ( bone.parent && bone.parent.isBone ) {
  41069. vertices.push( 0, 0, 0 );
  41070. vertices.push( 0, 0, 0 );
  41071. colors.push( 0, 0, 0 );
  41072. colors.push( 0, 0, 0 );
  41073. }
  41074. }
  41075. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41076. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41077. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41078. super( geometry, material );
  41079. /**
  41080. * This flag can be used for type testing.
  41081. *
  41082. * @type {boolean}
  41083. * @readonly
  41084. * @default true
  41085. */
  41086. this.isSkeletonHelper = true;
  41087. this.type = 'SkeletonHelper';
  41088. /**
  41089. * The object being visualized.
  41090. *
  41091. * @type {Object3D}
  41092. */
  41093. this.root = object;
  41094. /**
  41095. * The list of bones that the helper visualizes.
  41096. *
  41097. * @type {Array<Bone>}
  41098. */
  41099. this.bones = bones;
  41100. this.matrix = object.matrixWorld;
  41101. this.matrixAutoUpdate = false;
  41102. // colors
  41103. const color1 = new Color( 0x0000ff );
  41104. const color2 = new Color( 0x00ff00 );
  41105. this.setColors( color1, color2 );
  41106. }
  41107. updateMatrixWorld( force ) {
  41108. const bones = this.bones;
  41109. const geometry = this.geometry;
  41110. const position = geometry.getAttribute( 'position' );
  41111. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41112. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41113. const bone = bones[ i ];
  41114. if ( bone.parent && bone.parent.isBone ) {
  41115. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41116. _vector$2.setFromMatrixPosition( _boneMatrix );
  41117. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41118. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41119. _vector$2.setFromMatrixPosition( _boneMatrix );
  41120. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41121. j += 2;
  41122. }
  41123. }
  41124. geometry.getAttribute( 'position' ).needsUpdate = true;
  41125. super.updateMatrixWorld( force );
  41126. }
  41127. /**
  41128. * Defines the colors of the helper.
  41129. *
  41130. * @param {Color} color1 - The first line color for each bone.
  41131. * @param {Color} color2 - The second line color for each bone.
  41132. * @return {SkeletonHelper} A reference to this helper.
  41133. */
  41134. setColors( color1, color2 ) {
  41135. const geometry = this.geometry;
  41136. const colorAttribute = geometry.getAttribute( 'color' );
  41137. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41138. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41139. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41140. }
  41141. colorAttribute.needsUpdate = true;
  41142. return this;
  41143. }
  41144. /**
  41145. * Frees the GPU-related resources allocated by this instance. Call this
  41146. * method whenever this instance is no longer used in your app.
  41147. */
  41148. dispose() {
  41149. this.geometry.dispose();
  41150. this.material.dispose();
  41151. }
  41152. }
  41153. function getBoneList( object ) {
  41154. const boneList = [];
  41155. if ( object.isBone === true ) {
  41156. boneList.push( object );
  41157. }
  41158. for ( let i = 0; i < object.children.length; i ++ ) {
  41159. boneList.push( ...getBoneList( object.children[ i ] ) );
  41160. }
  41161. return boneList;
  41162. }
  41163. /**
  41164. * This displays a helper object consisting of a spherical mesh for
  41165. * visualizing an instance of {@link PointLight}.
  41166. *
  41167. * ```js
  41168. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41169. * pointLight.position.set( 10, 10, 10 );
  41170. * scene.add( pointLight );
  41171. *
  41172. * const sphereSize = 1;
  41173. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41174. * scene.add( pointLightHelper );
  41175. * ```
  41176. *
  41177. * @augments Mesh
  41178. */
  41179. class PointLightHelper extends Mesh {
  41180. /**
  41181. * Constructs a new point light helper.
  41182. *
  41183. * @param {PointLight} light - The light to be visualized.
  41184. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41185. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41186. * the color of the light.
  41187. */
  41188. constructor( light, sphereSize, color ) {
  41189. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41190. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41191. super( geometry, material );
  41192. /**
  41193. * The light being visualized.
  41194. *
  41195. * @type {PointLight}
  41196. */
  41197. this.light = light;
  41198. /**
  41199. * The color parameter passed in the constructor.
  41200. * If not set, the helper will take the color of the light.
  41201. *
  41202. * @type {number|Color|string}
  41203. */
  41204. this.color = color;
  41205. this.type = 'PointLightHelper';
  41206. this.matrix = this.light.matrixWorld;
  41207. this.matrixAutoUpdate = false;
  41208. this.update();
  41209. /*
  41210. // TODO: delete this comment?
  41211. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41212. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41213. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41214. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41215. const d = light.distance;
  41216. if ( d === 0.0 ) {
  41217. this.lightDistance.visible = false;
  41218. } else {
  41219. this.lightDistance.scale.set( d, d, d );
  41220. }
  41221. this.add( this.lightDistance );
  41222. */
  41223. }
  41224. /**
  41225. * Frees the GPU-related resources allocated by this instance. Call this
  41226. * method whenever this instance is no longer used in your app.
  41227. */
  41228. dispose() {
  41229. this.geometry.dispose();
  41230. this.material.dispose();
  41231. }
  41232. /**
  41233. * Updates the helper to match the position of the
  41234. * light being visualized.
  41235. */
  41236. update() {
  41237. this.light.updateWorldMatrix( true, false );
  41238. if ( this.color !== undefined ) {
  41239. this.material.color.set( this.color );
  41240. } else {
  41241. this.material.color.copy( this.light.color );
  41242. }
  41243. /*
  41244. const d = this.light.distance;
  41245. if ( d === 0.0 ) {
  41246. this.lightDistance.visible = false;
  41247. } else {
  41248. this.lightDistance.visible = true;
  41249. this.lightDistance.scale.set( d, d, d );
  41250. }
  41251. */
  41252. }
  41253. }
  41254. const _vector$1 = /*@__PURE__*/ new Vector3();
  41255. const _color1 = /*@__PURE__*/ new Color();
  41256. const _color2 = /*@__PURE__*/ new Color();
  41257. /**
  41258. * Creates a visual aid consisting of a spherical mesh for a
  41259. * given {@link HemisphereLight}.
  41260. *
  41261. * ```js
  41262. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41263. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41264. * scene.add( helper );
  41265. * ```
  41266. *
  41267. * @augments Object3D
  41268. */
  41269. class HemisphereLightHelper extends Object3D {
  41270. /**
  41271. * Constructs a new hemisphere light helper.
  41272. *
  41273. * @param {HemisphereLight} light - The light to be visualized.
  41274. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41275. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41276. * the color of the light.
  41277. */
  41278. constructor( light, size, color ) {
  41279. super();
  41280. /**
  41281. * The light being visualized.
  41282. *
  41283. * @type {HemisphereLight}
  41284. */
  41285. this.light = light;
  41286. this.matrix = light.matrixWorld;
  41287. this.matrixAutoUpdate = false;
  41288. /**
  41289. * The color parameter passed in the constructor.
  41290. * If not set, the helper will take the color of the light.
  41291. *
  41292. * @type {number|Color|string}
  41293. */
  41294. this.color = color;
  41295. this.type = 'HemisphereLightHelper';
  41296. const geometry = new OctahedronGeometry( size );
  41297. geometry.rotateY( Math.PI * 0.5 );
  41298. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41299. if ( this.color === undefined ) this.material.vertexColors = true;
  41300. const position = geometry.getAttribute( 'position' );
  41301. const colors = new Float32Array( position.count * 3 );
  41302. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41303. this.add( new Mesh( geometry, this.material ) );
  41304. this.update();
  41305. }
  41306. /**
  41307. * Frees the GPU-related resources allocated by this instance. Call this
  41308. * method whenever this instance is no longer used in your app.
  41309. */
  41310. dispose() {
  41311. this.children[ 0 ].geometry.dispose();
  41312. this.children[ 0 ].material.dispose();
  41313. }
  41314. /**
  41315. * Updates the helper to match the position and direction of the
  41316. * light being visualized.
  41317. */
  41318. update() {
  41319. const mesh = this.children[ 0 ];
  41320. if ( this.color !== undefined ) {
  41321. this.material.color.set( this.color );
  41322. } else {
  41323. const colors = mesh.geometry.getAttribute( 'color' );
  41324. _color1.copy( this.light.color );
  41325. _color2.copy( this.light.groundColor );
  41326. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41327. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41328. colors.setXYZ( i, color.r, color.g, color.b );
  41329. }
  41330. colors.needsUpdate = true;
  41331. }
  41332. this.light.updateWorldMatrix( true, false );
  41333. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41334. }
  41335. }
  41336. /**
  41337. * The helper is an object to define grids. Grids are two-dimensional
  41338. * arrays of lines.
  41339. *
  41340. * ```js
  41341. * const size = 10;
  41342. * const divisions = 10;
  41343. *
  41344. * const gridHelper = new THREE.GridHelper( size, divisions );
  41345. * scene.add( gridHelper );
  41346. * ```
  41347. *
  41348. * @augments LineSegments
  41349. */
  41350. class GridHelper extends LineSegments {
  41351. /**
  41352. * Constructs a new grid helper.
  41353. *
  41354. * @param {number} [size=10] - The size of the grid.
  41355. * @param {number} [divisions=10] - The number of divisions across the grid.
  41356. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41357. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41358. */
  41359. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41360. color1 = new Color( color1 );
  41361. color2 = new Color( color2 );
  41362. const center = divisions / 2;
  41363. const step = size / divisions;
  41364. const halfSize = size / 2;
  41365. const vertices = [], colors = [];
  41366. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41367. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41368. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41369. const color = i === center ? color1 : color2;
  41370. color.toArray( colors, j ); j += 3;
  41371. color.toArray( colors, j ); j += 3;
  41372. color.toArray( colors, j ); j += 3;
  41373. color.toArray( colors, j ); j += 3;
  41374. }
  41375. const geometry = new BufferGeometry();
  41376. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41377. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41378. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41379. super( geometry, material );
  41380. this.type = 'GridHelper';
  41381. }
  41382. /**
  41383. * Frees the GPU-related resources allocated by this instance. Call this
  41384. * method whenever this instance is no longer used in your app.
  41385. */
  41386. dispose() {
  41387. this.geometry.dispose();
  41388. this.material.dispose();
  41389. }
  41390. }
  41391. /**
  41392. * This helper is an object to define polar grids. Grids are
  41393. * two-dimensional arrays of lines.
  41394. *
  41395. * ```js
  41396. * const radius = 10;
  41397. * const sectors = 16;
  41398. * const rings = 8;
  41399. * const divisions = 64;
  41400. *
  41401. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41402. * scene.add( helper );
  41403. * ```
  41404. *
  41405. * @augments LineSegments
  41406. */
  41407. class PolarGridHelper extends LineSegments {
  41408. /**
  41409. * Constructs a new polar grid helper.
  41410. *
  41411. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41412. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41413. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41414. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41415. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41416. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41417. */
  41418. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41419. color1 = new Color( color1 );
  41420. color2 = new Color( color2 );
  41421. const vertices = [];
  41422. const colors = [];
  41423. // create the sectors
  41424. if ( sectors > 1 ) {
  41425. for ( let i = 0; i < sectors; i ++ ) {
  41426. const v = ( i / sectors ) * ( Math.PI * 2 );
  41427. const x = Math.sin( v ) * radius;
  41428. const z = Math.cos( v ) * radius;
  41429. vertices.push( 0, 0, 0 );
  41430. vertices.push( x, 0, z );
  41431. const color = ( i & 1 ) ? color1 : color2;
  41432. colors.push( color.r, color.g, color.b );
  41433. colors.push( color.r, color.g, color.b );
  41434. }
  41435. }
  41436. // create the rings
  41437. for ( let i = 0; i < rings; i ++ ) {
  41438. const color = ( i & 1 ) ? color1 : color2;
  41439. const r = radius - ( radius / rings * i );
  41440. for ( let j = 0; j < divisions; j ++ ) {
  41441. // first vertex
  41442. let v = ( j / divisions ) * ( Math.PI * 2 );
  41443. let x = Math.sin( v ) * r;
  41444. let z = Math.cos( v ) * r;
  41445. vertices.push( x, 0, z );
  41446. colors.push( color.r, color.g, color.b );
  41447. // second vertex
  41448. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41449. x = Math.sin( v ) * r;
  41450. z = Math.cos( v ) * r;
  41451. vertices.push( x, 0, z );
  41452. colors.push( color.r, color.g, color.b );
  41453. }
  41454. }
  41455. const geometry = new BufferGeometry();
  41456. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41457. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41458. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41459. super( geometry, material );
  41460. this.type = 'PolarGridHelper';
  41461. }
  41462. /**
  41463. * Frees the GPU-related resources allocated by this instance. Call this
  41464. * method whenever this instance is no longer used in your app.
  41465. */
  41466. dispose() {
  41467. this.geometry.dispose();
  41468. this.material.dispose();
  41469. }
  41470. }
  41471. const _v1 = /*@__PURE__*/ new Vector3();
  41472. const _v2 = /*@__PURE__*/ new Vector3();
  41473. const _v3 = /*@__PURE__*/ new Vector3();
  41474. /**
  41475. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41476. * effect on the scene. This consists of plane and a line representing the
  41477. * light's position and direction.
  41478. *
  41479. * ```js
  41480. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41481. * scene.add( light );
  41482. *
  41483. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41484. * scene.add( helper );
  41485. * ```
  41486. *
  41487. * @augments Object3D
  41488. */
  41489. class DirectionalLightHelper extends Object3D {
  41490. /**
  41491. * Constructs a new directional light helper.
  41492. *
  41493. * @param {DirectionalLight} light - The light to be visualized.
  41494. * @param {number} [size=1] - The dimensions of the plane.
  41495. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41496. * the color of the light.
  41497. */
  41498. constructor( light, size, color ) {
  41499. super();
  41500. /**
  41501. * The light being visualized.
  41502. *
  41503. * @type {DirectionalLight}
  41504. */
  41505. this.light = light;
  41506. this.matrix = light.matrixWorld;
  41507. this.matrixAutoUpdate = false;
  41508. /**
  41509. * The color parameter passed in the constructor.
  41510. * If not set, the helper will take the color of the light.
  41511. *
  41512. * @type {number|Color|string}
  41513. */
  41514. this.color = color;
  41515. this.type = 'DirectionalLightHelper';
  41516. if ( size === undefined ) size = 1;
  41517. let geometry = new BufferGeometry();
  41518. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41519. - size, size, 0,
  41520. size, size, 0,
  41521. size, - size, 0,
  41522. - size, - size, 0,
  41523. - size, size, 0
  41524. ], 3 ) );
  41525. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41526. /**
  41527. * Contains the line showing the location of the directional light.
  41528. *
  41529. * @type {Line}
  41530. */
  41531. this.lightPlane = new Line( geometry, material );
  41532. this.add( this.lightPlane );
  41533. geometry = new BufferGeometry();
  41534. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41535. /**
  41536. * Represents the target line of the directional light.
  41537. *
  41538. * @type {Line}
  41539. */
  41540. this.targetLine = new Line( geometry, material );
  41541. this.add( this.targetLine );
  41542. this.update();
  41543. }
  41544. /**
  41545. * Frees the GPU-related resources allocated by this instance. Call this
  41546. * method whenever this instance is no longer used in your app.
  41547. */
  41548. dispose() {
  41549. this.lightPlane.geometry.dispose();
  41550. this.lightPlane.material.dispose();
  41551. this.targetLine.geometry.dispose();
  41552. this.targetLine.material.dispose();
  41553. }
  41554. /**
  41555. * Updates the helper to match the position and direction of the
  41556. * light being visualized.
  41557. */
  41558. update() {
  41559. this.light.updateWorldMatrix( true, false );
  41560. this.light.target.updateWorldMatrix( true, false );
  41561. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41562. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41563. _v3.subVectors( _v2, _v1 );
  41564. this.lightPlane.lookAt( _v2 );
  41565. if ( this.color !== undefined ) {
  41566. this.lightPlane.material.color.set( this.color );
  41567. this.targetLine.material.color.set( this.color );
  41568. } else {
  41569. this.lightPlane.material.color.copy( this.light.color );
  41570. this.targetLine.material.color.copy( this.light.color );
  41571. }
  41572. this.targetLine.lookAt( _v2 );
  41573. this.targetLine.scale.z = _v3.length();
  41574. }
  41575. }
  41576. const _vector = /*@__PURE__*/ new Vector3();
  41577. const _camera = /*@__PURE__*/ new Camera();
  41578. /**
  41579. * This helps with visualizing what a camera contains in its frustum. It
  41580. * visualizes the frustum of a camera using a line segments.
  41581. *
  41582. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41583. *
  41584. * `CameraHelper` must be a child of the scene.
  41585. *
  41586. * ```js
  41587. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41588. * const helper = new THREE.CameraHelper( camera );
  41589. * scene.add( helper );
  41590. * ```
  41591. *
  41592. * @augments LineSegments
  41593. */
  41594. class CameraHelper extends LineSegments {
  41595. /**
  41596. * Constructs a new arrow helper.
  41597. *
  41598. * @param {Camera} camera - The camera to visualize.
  41599. */
  41600. constructor( camera ) {
  41601. const geometry = new BufferGeometry();
  41602. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41603. const vertices = [];
  41604. const colors = [];
  41605. const pointMap = {};
  41606. // near
  41607. addLine( 'n1', 'n2' );
  41608. addLine( 'n2', 'n4' );
  41609. addLine( 'n4', 'n3' );
  41610. addLine( 'n3', 'n1' );
  41611. // far
  41612. addLine( 'f1', 'f2' );
  41613. addLine( 'f2', 'f4' );
  41614. addLine( 'f4', 'f3' );
  41615. addLine( 'f3', 'f1' );
  41616. // sides
  41617. addLine( 'n1', 'f1' );
  41618. addLine( 'n2', 'f2' );
  41619. addLine( 'n3', 'f3' );
  41620. addLine( 'n4', 'f4' );
  41621. // cone
  41622. addLine( 'p', 'n1' );
  41623. addLine( 'p', 'n2' );
  41624. addLine( 'p', 'n3' );
  41625. addLine( 'p', 'n4' );
  41626. // up
  41627. addLine( 'u1', 'u2' );
  41628. addLine( 'u2', 'u3' );
  41629. addLine( 'u3', 'u1' );
  41630. // target
  41631. addLine( 'c', 't' );
  41632. addLine( 'p', 'c' );
  41633. // cross
  41634. addLine( 'cn1', 'cn2' );
  41635. addLine( 'cn3', 'cn4' );
  41636. addLine( 'cf1', 'cf2' );
  41637. addLine( 'cf3', 'cf4' );
  41638. function addLine( a, b ) {
  41639. addPoint( a );
  41640. addPoint( b );
  41641. }
  41642. function addPoint( id ) {
  41643. vertices.push( 0, 0, 0 );
  41644. colors.push( 0, 0, 0 );
  41645. if ( pointMap[ id ] === undefined ) {
  41646. pointMap[ id ] = [];
  41647. }
  41648. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41649. }
  41650. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41651. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41652. super( geometry, material );
  41653. this.type = 'CameraHelper';
  41654. /**
  41655. * The camera being visualized.
  41656. *
  41657. * @type {Camera}
  41658. */
  41659. this.camera = camera;
  41660. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41661. this.matrix = camera.matrixWorld;
  41662. this.matrixAutoUpdate = false;
  41663. /**
  41664. * This contains the points used to visualize the camera.
  41665. *
  41666. * @type {Object<string,Array<number>>}
  41667. */
  41668. this.pointMap = pointMap;
  41669. this.update();
  41670. // colors
  41671. const colorFrustum = new Color( 0xffaa00 );
  41672. const colorCone = new Color( 0xff0000 );
  41673. const colorUp = new Color( 0x00aaff );
  41674. const colorTarget = new Color( 0xffffff );
  41675. const colorCross = new Color( 0x333333 );
  41676. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41677. }
  41678. /**
  41679. * Defines the colors of the helper.
  41680. *
  41681. * @param {Color} frustum - The frustum line color.
  41682. * @param {Color} cone - The cone line color.
  41683. * @param {Color} up - The up line color.
  41684. * @param {Color} target - The target line color.
  41685. * @param {Color} cross - The cross line color.
  41686. * @return {CameraHelper} A reference to this helper.
  41687. */
  41688. setColors( frustum, cone, up, target, cross ) {
  41689. const geometry = this.geometry;
  41690. const colorAttribute = geometry.getAttribute( 'color' );
  41691. // near
  41692. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41693. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41694. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41695. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41696. // far
  41697. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41698. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41699. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41700. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41701. // sides
  41702. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41703. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41704. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41705. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41706. // cone
  41707. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41708. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41709. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41710. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41711. // up
  41712. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41713. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41714. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41715. // target
  41716. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41717. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41718. // cross
  41719. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41720. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41721. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41722. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41723. colorAttribute.needsUpdate = true;
  41724. return this;
  41725. }
  41726. /**
  41727. * Updates the helper based on the projection matrix of the camera.
  41728. */
  41729. update() {
  41730. const geometry = this.geometry;
  41731. const pointMap = this.pointMap;
  41732. const w = 1, h = 1;
  41733. let nearZ, farZ;
  41734. // we need just camera projection matrix inverse
  41735. // world matrix must be identity
  41736. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41737. // Adjust z values based on coordinate system
  41738. if ( this.camera.reversedDepth === true ) {
  41739. nearZ = 1;
  41740. farZ = 0;
  41741. } else {
  41742. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41743. nearZ = -1;
  41744. farZ = 1;
  41745. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41746. nearZ = 0;
  41747. farZ = 1;
  41748. } else {
  41749. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41750. }
  41751. }
  41752. // center / target
  41753. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41754. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41755. // near
  41756. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41757. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41758. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41759. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41760. // far
  41761. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41762. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41763. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41764. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41765. // up
  41766. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41767. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41768. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41769. // cross
  41770. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41771. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41772. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41773. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41774. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41775. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41776. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41777. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41778. geometry.getAttribute( 'position' ).needsUpdate = true;
  41779. }
  41780. /**
  41781. * Frees the GPU-related resources allocated by this instance. Call this
  41782. * method whenever this instance is no longer used in your app.
  41783. */
  41784. dispose() {
  41785. this.geometry.dispose();
  41786. this.material.dispose();
  41787. }
  41788. }
  41789. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41790. _vector.set( x, y, z ).unproject( camera );
  41791. const points = pointMap[ point ];
  41792. if ( points !== undefined ) {
  41793. const position = geometry.getAttribute( 'position' );
  41794. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41795. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41796. }
  41797. }
  41798. }
  41799. const _box = /*@__PURE__*/ new Box3();
  41800. /**
  41801. * Helper object to graphically show the world-axis-aligned bounding box
  41802. * around an object. The actual bounding box is handled with {@link Box3},
  41803. * this is just a visual helper for debugging. It can be automatically
  41804. * resized with {@link BoxHelper#update} when the object it's created from
  41805. * is transformed. Note that the object must have a geometry for this to work,
  41806. * so it won't work with sprites.
  41807. *
  41808. * ```js
  41809. * const sphere = new THREE.SphereGeometry();
  41810. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41811. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41812. * scene.add( box );
  41813. * ```
  41814. *
  41815. * @augments LineSegments
  41816. */
  41817. class BoxHelper extends LineSegments {
  41818. /**
  41819. * Constructs a new box helper.
  41820. *
  41821. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41822. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41823. */
  41824. constructor( object, color = 0xffff00 ) {
  41825. 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 ] );
  41826. const positions = new Float32Array( 8 * 3 );
  41827. const geometry = new BufferGeometry();
  41828. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41829. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41830. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41831. /**
  41832. * The 3D object being visualized.
  41833. *
  41834. * @type {Object3D}
  41835. */
  41836. this.object = object;
  41837. this.type = 'BoxHelper';
  41838. this.matrixAutoUpdate = false;
  41839. this.update();
  41840. }
  41841. /**
  41842. * Updates the helper's geometry to match the dimensions of the object,
  41843. * including any children.
  41844. */
  41845. update() {
  41846. if ( this.object !== undefined ) {
  41847. _box.setFromObject( this.object );
  41848. }
  41849. if ( _box.isEmpty() ) return;
  41850. const min = _box.min;
  41851. const max = _box.max;
  41852. /*
  41853. 5____4
  41854. 1/___0/|
  41855. | 6__|_7
  41856. 2/___3/
  41857. 0: max.x, max.y, max.z
  41858. 1: min.x, max.y, max.z
  41859. 2: min.x, min.y, max.z
  41860. 3: max.x, min.y, max.z
  41861. 4: max.x, max.y, min.z
  41862. 5: min.x, max.y, min.z
  41863. 6: min.x, min.y, min.z
  41864. 7: max.x, min.y, min.z
  41865. */
  41866. const position = this.geometry.attributes.position;
  41867. const array = position.array;
  41868. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41869. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41870. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41871. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41872. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41873. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41874. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41875. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41876. position.needsUpdate = true;
  41877. this.geometry.computeBoundingSphere();
  41878. }
  41879. /**
  41880. * Updates the wireframe box for the passed object.
  41881. *
  41882. * @param {Object3D} object - The 3D object to create the helper for.
  41883. * @return {BoxHelper} A reference to this instance.
  41884. */
  41885. setFromObject( object ) {
  41886. this.object = object;
  41887. this.update();
  41888. return this;
  41889. }
  41890. copy( source, recursive ) {
  41891. super.copy( source, recursive );
  41892. this.object = source.object;
  41893. return this;
  41894. }
  41895. /**
  41896. * Frees the GPU-related resources allocated by this instance. Call this
  41897. * method whenever this instance is no longer used in your app.
  41898. */
  41899. dispose() {
  41900. this.geometry.dispose();
  41901. this.material.dispose();
  41902. }
  41903. }
  41904. /**
  41905. * A helper object to visualize an instance of {@link Box3}.
  41906. *
  41907. * ```js
  41908. * const box = new THREE.Box3();
  41909. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41910. *
  41911. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41912. * scene.add( helper )
  41913. * ```
  41914. *
  41915. * @augments LineSegments
  41916. */
  41917. class Box3Helper extends LineSegments {
  41918. /**
  41919. * Constructs a new box3 helper.
  41920. *
  41921. * @param {Box3} box - The box to visualize.
  41922. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41923. */
  41924. constructor( box, color = 0xffff00 ) {
  41925. 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 ] );
  41926. 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 ];
  41927. const geometry = new BufferGeometry();
  41928. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41929. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41930. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41931. /**
  41932. * The box being visualized.
  41933. *
  41934. * @type {Box3}
  41935. */
  41936. this.box = box;
  41937. this.type = 'Box3Helper';
  41938. this.geometry.computeBoundingSphere();
  41939. }
  41940. updateMatrixWorld( force ) {
  41941. const box = this.box;
  41942. if ( box.isEmpty() ) return;
  41943. box.getCenter( this.position );
  41944. box.getSize( this.scale );
  41945. this.scale.multiplyScalar( 0.5 );
  41946. super.updateMatrixWorld( force );
  41947. }
  41948. /**
  41949. * Frees the GPU-related resources allocated by this instance. Call this
  41950. * method whenever this instance is no longer used in your app.
  41951. */
  41952. dispose() {
  41953. this.geometry.dispose();
  41954. this.material.dispose();
  41955. }
  41956. }
  41957. /**
  41958. * A helper object to visualize an instance of {@link Plane}.
  41959. *
  41960. * ```js
  41961. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41962. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41963. * scene.add( helper );
  41964. * ```
  41965. *
  41966. * @augments Line
  41967. */
  41968. class PlaneHelper extends Line {
  41969. /**
  41970. * Constructs a new plane helper.
  41971. *
  41972. * @param {Plane} plane - The plane to be visualized.
  41973. * @param {number} [size=1] - The side length of plane helper.
  41974. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41975. */
  41976. constructor( plane, size = 1, hex = 0xffff00 ) {
  41977. const color = hex;
  41978. 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 ];
  41979. const geometry = new BufferGeometry();
  41980. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41981. geometry.computeBoundingSphere();
  41982. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41983. this.type = 'PlaneHelper';
  41984. /**
  41985. * The plane being visualized.
  41986. *
  41987. * @type {Plane}
  41988. */
  41989. this.plane = plane;
  41990. /**
  41991. * The side length of plane helper.
  41992. *
  41993. * @type {number}
  41994. * @default 1
  41995. */
  41996. this.size = size;
  41997. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41998. const geometry2 = new BufferGeometry();
  41999. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42000. geometry2.computeBoundingSphere();
  42001. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42002. }
  42003. updateMatrixWorld( force ) {
  42004. this.position.set( 0, 0, 0 );
  42005. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42006. this.lookAt( this.plane.normal );
  42007. this.translateZ( - this.plane.constant );
  42008. super.updateMatrixWorld( force );
  42009. }
  42010. /**
  42011. * Updates the helper to match the position and direction of the
  42012. * light being visualized.
  42013. */
  42014. dispose() {
  42015. this.geometry.dispose();
  42016. this.material.dispose();
  42017. this.children[ 0 ].geometry.dispose();
  42018. this.children[ 0 ].material.dispose();
  42019. }
  42020. }
  42021. const _axis = /*@__PURE__*/ new Vector3();
  42022. let _lineGeometry, _coneGeometry;
  42023. /**
  42024. * An 3D arrow object for visualizing directions.
  42025. *
  42026. * ```js
  42027. * const dir = new THREE.Vector3( 1, 2, 0 );
  42028. *
  42029. * //normalize the direction vector (convert to vector of length 1)
  42030. * dir.normalize();
  42031. *
  42032. * const origin = new THREE.Vector3( 0, 0, 0 );
  42033. * const length = 1;
  42034. * const hex = 0xffff00;
  42035. *
  42036. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42037. * scene.add( arrowHelper );
  42038. * ```
  42039. *
  42040. * @augments Object3D
  42041. */
  42042. class ArrowHelper extends Object3D {
  42043. /**
  42044. * Constructs a new arrow helper.
  42045. *
  42046. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42047. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42048. * @param {number} [length=1] - Length of the arrow in world units.
  42049. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42050. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42051. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42052. */
  42053. 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 ) {
  42054. super();
  42055. this.type = 'ArrowHelper';
  42056. if ( _lineGeometry === undefined ) {
  42057. _lineGeometry = new BufferGeometry();
  42058. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42059. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42060. _coneGeometry.translate( 0, -0.5, 0 );
  42061. }
  42062. this.position.copy( origin );
  42063. /**
  42064. * The line part of the arrow helper.
  42065. *
  42066. * @type {Line}
  42067. */
  42068. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42069. this.line.matrixAutoUpdate = false;
  42070. this.add( this.line );
  42071. /**
  42072. * The cone part of the arrow helper.
  42073. *
  42074. * @type {Mesh}
  42075. */
  42076. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42077. this.cone.matrixAutoUpdate = false;
  42078. this.add( this.cone );
  42079. this.setDirection( dir );
  42080. this.setLength( length, headLength, headWidth );
  42081. }
  42082. /**
  42083. * Sets the direction of the helper.
  42084. *
  42085. * @param {Vector3} dir - The normalized direction vector.
  42086. */
  42087. setDirection( dir ) {
  42088. // dir is assumed to be normalized
  42089. if ( dir.y > 0.99999 ) {
  42090. this.quaternion.set( 0, 0, 0, 1 );
  42091. } else if ( dir.y < -0.99999 ) {
  42092. this.quaternion.set( 1, 0, 0, 0 );
  42093. } else {
  42094. _axis.set( dir.z, 0, - dir.x ).normalize();
  42095. const radians = Math.acos( dir.y );
  42096. this.quaternion.setFromAxisAngle( _axis, radians );
  42097. }
  42098. }
  42099. /**
  42100. * Sets the length of the helper.
  42101. *
  42102. * @param {number} length - Length of the arrow in world units.
  42103. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42104. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42105. */
  42106. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42107. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42108. this.line.updateMatrix();
  42109. this.cone.scale.set( headWidth, headLength, headWidth );
  42110. this.cone.position.y = length;
  42111. this.cone.updateMatrix();
  42112. }
  42113. /**
  42114. * Sets the color of the helper.
  42115. *
  42116. * @param {number|Color|string} color - The color to set.
  42117. */
  42118. setColor( color ) {
  42119. this.line.material.color.set( color );
  42120. this.cone.material.color.set( color );
  42121. }
  42122. copy( source ) {
  42123. super.copy( source, false );
  42124. this.line.copy( source.line );
  42125. this.cone.copy( source.cone );
  42126. return this;
  42127. }
  42128. /**
  42129. * Frees the GPU-related resources allocated by this instance. Call this
  42130. * method whenever this instance is no longer used in your app.
  42131. */
  42132. dispose() {
  42133. this.line.geometry.dispose();
  42134. this.line.material.dispose();
  42135. this.cone.geometry.dispose();
  42136. this.cone.material.dispose();
  42137. }
  42138. }
  42139. /**
  42140. * An axis object to visualize the 3 axes in a simple way.
  42141. * The X axis is red. The Y axis is green. The Z axis is blue.
  42142. *
  42143. * ```js
  42144. * const axesHelper = new THREE.AxesHelper( 5 );
  42145. * scene.add( axesHelper );
  42146. * ```
  42147. *
  42148. * @augments LineSegments
  42149. */
  42150. class AxesHelper extends LineSegments {
  42151. /**
  42152. * Constructs a new axes helper.
  42153. *
  42154. * @param {number} [size=1] - Size of the lines representing the axes.
  42155. */
  42156. constructor( size = 1 ) {
  42157. const vertices = [
  42158. 0, 0, 0, size, 0, 0,
  42159. 0, 0, 0, 0, size, 0,
  42160. 0, 0, 0, 0, 0, size
  42161. ];
  42162. const colors = [
  42163. 1, 0, 0, 1, 0.6, 0,
  42164. 0, 1, 0, 0.6, 1, 0,
  42165. 0, 0, 1, 0, 0.6, 1
  42166. ];
  42167. const geometry = new BufferGeometry();
  42168. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42169. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42170. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42171. super( geometry, material );
  42172. this.type = 'AxesHelper';
  42173. }
  42174. /**
  42175. * Defines the colors of the axes helper.
  42176. *
  42177. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42178. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42179. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42180. * @return {AxesHelper} A reference to this axes helper.
  42181. */
  42182. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42183. const color = new Color();
  42184. const array = this.geometry.attributes.color.array;
  42185. color.set( xAxisColor );
  42186. color.toArray( array, 0 );
  42187. color.toArray( array, 3 );
  42188. color.set( yAxisColor );
  42189. color.toArray( array, 6 );
  42190. color.toArray( array, 9 );
  42191. color.set( zAxisColor );
  42192. color.toArray( array, 12 );
  42193. color.toArray( array, 15 );
  42194. this.geometry.attributes.color.needsUpdate = true;
  42195. return this;
  42196. }
  42197. /**
  42198. * Frees the GPU-related resources allocated by this instance. Call this
  42199. * method whenever this instance is no longer used in your app.
  42200. */
  42201. dispose() {
  42202. this.geometry.dispose();
  42203. this.material.dispose();
  42204. }
  42205. }
  42206. /**
  42207. * This class is used to convert a series of paths to an array of
  42208. * shapes. It is specifically used in context of fonts and SVG.
  42209. */
  42210. class ShapePath {
  42211. /**
  42212. * Constructs a new shape path.
  42213. */
  42214. constructor() {
  42215. this.type = 'ShapePath';
  42216. /**
  42217. * The color of the shape.
  42218. *
  42219. * @type {Color}
  42220. */
  42221. this.color = new Color();
  42222. /**
  42223. * The paths that have been generated for this shape.
  42224. *
  42225. * @type {Array<Path>}
  42226. * @default null
  42227. */
  42228. this.subPaths = [];
  42229. /**
  42230. * The current path that is being generated.
  42231. *
  42232. * @type {?Path}
  42233. * @default null
  42234. */
  42235. this.currentPath = null;
  42236. }
  42237. /**
  42238. * Creates a new path and moves it current point to the given one.
  42239. *
  42240. * @param {number} x - The x coordinate.
  42241. * @param {number} y - The y coordinate.
  42242. * @return {ShapePath} A reference to this shape path.
  42243. */
  42244. moveTo( x, y ) {
  42245. this.currentPath = new Path();
  42246. this.subPaths.push( this.currentPath );
  42247. this.currentPath.moveTo( x, y );
  42248. return this;
  42249. }
  42250. /**
  42251. * Adds an instance of {@link LineCurve} to the path by connecting
  42252. * the current point with the given one.
  42253. *
  42254. * @param {number} x - The x coordinate of the end point.
  42255. * @param {number} y - The y coordinate of the end point.
  42256. * @return {ShapePath} A reference to this shape path.
  42257. */
  42258. lineTo( x, y ) {
  42259. this.currentPath.lineTo( x, y );
  42260. return this;
  42261. }
  42262. /**
  42263. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42264. * the current point with the given one.
  42265. *
  42266. * @param {number} aCPx - The x coordinate of the control point.
  42267. * @param {number} aCPy - The y coordinate of the control point.
  42268. * @param {number} aX - The x coordinate of the end point.
  42269. * @param {number} aY - The y coordinate of the end point.
  42270. * @return {ShapePath} A reference to this shape path.
  42271. */
  42272. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42273. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42274. return this;
  42275. }
  42276. /**
  42277. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42278. * the current point with the given one.
  42279. *
  42280. * @param {number} aCP1x - The x coordinate of the first control point.
  42281. * @param {number} aCP1y - The y coordinate of the first control point.
  42282. * @param {number} aCP2x - The x coordinate of the second control point.
  42283. * @param {number} aCP2y - The y coordinate of the second control point.
  42284. * @param {number} aX - The x coordinate of the end point.
  42285. * @param {number} aY - The y coordinate of the end point.
  42286. * @return {ShapePath} A reference to this shape path.
  42287. */
  42288. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42289. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42290. return this;
  42291. }
  42292. /**
  42293. * Adds an instance of {@link SplineCurve} to the path by connecting
  42294. * the current point with the given list of points.
  42295. *
  42296. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42297. * @return {ShapePath} A reference to this shape path.
  42298. */
  42299. splineThru( pts ) {
  42300. this.currentPath.splineThru( pts );
  42301. return this;
  42302. }
  42303. /**
  42304. * Converts the paths into an array of shapes.
  42305. *
  42306. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42307. * If this flag is set to `true`, then those are flipped.
  42308. * @return {Array<Shape>} An array of shapes.
  42309. */
  42310. toShapes( isCCW ) {
  42311. function toShapesNoHoles( inSubpaths ) {
  42312. const shapes = [];
  42313. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42314. const tmpPath = inSubpaths[ i ];
  42315. const tmpShape = new Shape();
  42316. tmpShape.curves = tmpPath.curves;
  42317. shapes.push( tmpShape );
  42318. }
  42319. return shapes;
  42320. }
  42321. function isPointInsidePolygon( inPt, inPolygon ) {
  42322. const polyLen = inPolygon.length;
  42323. // inPt on polygon contour => immediate success or
  42324. // toggling of inside/outside at every single! intersection point of an edge
  42325. // with the horizontal line through inPt, left of inPt
  42326. // not counting lowerY endpoints of edges and whole edges on that line
  42327. let inside = false;
  42328. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42329. let edgeLowPt = inPolygon[ p ];
  42330. let edgeHighPt = inPolygon[ q ];
  42331. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42332. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42333. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42334. // not parallel
  42335. if ( edgeDy < 0 ) {
  42336. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42337. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42338. }
  42339. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42340. if ( inPt.y === edgeLowPt.y ) {
  42341. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42342. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42343. } else {
  42344. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42345. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42346. if ( perpEdge < 0 ) continue;
  42347. inside = ! inside; // true intersection left of inPt
  42348. }
  42349. } else {
  42350. // parallel or collinear
  42351. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42352. // edge lies on the same horizontal line as inPt
  42353. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42354. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42355. // continue;
  42356. }
  42357. }
  42358. return inside;
  42359. }
  42360. const isClockWise = ShapeUtils.isClockWise;
  42361. const subPaths = this.subPaths;
  42362. if ( subPaths.length === 0 ) return [];
  42363. let solid, tmpPath, tmpShape;
  42364. const shapes = [];
  42365. if ( subPaths.length === 1 ) {
  42366. tmpPath = subPaths[ 0 ];
  42367. tmpShape = new Shape();
  42368. tmpShape.curves = tmpPath.curves;
  42369. shapes.push( tmpShape );
  42370. return shapes;
  42371. }
  42372. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42373. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42374. // log("Holes first", holesFirst);
  42375. const betterShapeHoles = [];
  42376. const newShapes = [];
  42377. let newShapeHoles = [];
  42378. let mainIdx = 0;
  42379. let tmpPoints;
  42380. newShapes[ mainIdx ] = undefined;
  42381. newShapeHoles[ mainIdx ] = [];
  42382. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42383. tmpPath = subPaths[ i ];
  42384. tmpPoints = tmpPath.getPoints();
  42385. solid = isClockWise( tmpPoints );
  42386. solid = isCCW ? ! solid : solid;
  42387. if ( solid ) {
  42388. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42389. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42390. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42391. if ( holesFirst ) mainIdx ++;
  42392. newShapeHoles[ mainIdx ] = [];
  42393. //log('cw', i);
  42394. } else {
  42395. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42396. //log('ccw', i);
  42397. }
  42398. }
  42399. // only Holes? -> probably all Shapes with wrong orientation
  42400. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42401. if ( newShapes.length > 1 ) {
  42402. let ambiguous = false;
  42403. let toChange = 0;
  42404. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42405. betterShapeHoles[ sIdx ] = [];
  42406. }
  42407. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42408. const sho = newShapeHoles[ sIdx ];
  42409. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42410. const ho = sho[ hIdx ];
  42411. let hole_unassigned = true;
  42412. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42413. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42414. if ( sIdx !== s2Idx ) toChange ++;
  42415. if ( hole_unassigned ) {
  42416. hole_unassigned = false;
  42417. betterShapeHoles[ s2Idx ].push( ho );
  42418. } else {
  42419. ambiguous = true;
  42420. }
  42421. }
  42422. }
  42423. if ( hole_unassigned ) {
  42424. betterShapeHoles[ sIdx ].push( ho );
  42425. }
  42426. }
  42427. }
  42428. if ( toChange > 0 && ambiguous === false ) {
  42429. newShapeHoles = betterShapeHoles;
  42430. }
  42431. }
  42432. let tmpHoles;
  42433. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42434. tmpShape = newShapes[ i ].s;
  42435. shapes.push( tmpShape );
  42436. tmpHoles = newShapeHoles[ i ];
  42437. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42438. tmpShape.holes.push( tmpHoles[ j ].h );
  42439. }
  42440. }
  42441. //log("shape", shapes);
  42442. return shapes;
  42443. }
  42444. }
  42445. /**
  42446. * Abstract base class for controls.
  42447. *
  42448. * @abstract
  42449. * @augments EventDispatcher
  42450. */
  42451. class Controls extends EventDispatcher {
  42452. /**
  42453. * Constructs a new controls instance.
  42454. *
  42455. * @param {Object3D} object - The object that is managed by the controls.
  42456. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42457. */
  42458. constructor( object, domElement = null ) {
  42459. super();
  42460. /**
  42461. * The object that is managed by the controls.
  42462. *
  42463. * @type {Object3D}
  42464. */
  42465. this.object = object;
  42466. /**
  42467. * The HTML element used for event listeners.
  42468. *
  42469. * @type {?HTMLElement}
  42470. * @default null
  42471. */
  42472. this.domElement = domElement;
  42473. /**
  42474. * Whether the controls responds to user input or not.
  42475. *
  42476. * @type {boolean}
  42477. * @default true
  42478. */
  42479. this.enabled = true;
  42480. /**
  42481. * The internal state of the controls.
  42482. *
  42483. * @type {number}
  42484. * @default -1
  42485. */
  42486. this.state = -1;
  42487. /**
  42488. * This object defines the keyboard input of the controls.
  42489. *
  42490. * @type {Object}
  42491. */
  42492. this.keys = {};
  42493. /**
  42494. * This object defines what type of actions are assigned to the available mouse buttons.
  42495. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42496. *
  42497. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42498. */
  42499. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42500. /**
  42501. * This object defines what type of actions are assigned to what kind of touch interaction.
  42502. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42503. *
  42504. * @type {{ONE: ?number, TWO: ?number}}
  42505. */
  42506. this.touches = { ONE: null, TWO: null };
  42507. }
  42508. /**
  42509. * Connects the controls to the DOM. This method has so called "side effects" since
  42510. * it adds the module's event listeners to the DOM.
  42511. *
  42512. * @param {HTMLElement} element - The DOM element to connect to.
  42513. */
  42514. connect( element ) {
  42515. if ( element === undefined ) {
  42516. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42517. return;
  42518. }
  42519. if ( this.domElement !== null ) this.disconnect();
  42520. this.domElement = element;
  42521. }
  42522. /**
  42523. * Disconnects the controls from the DOM.
  42524. */
  42525. disconnect() {}
  42526. /**
  42527. * Call this method if you no longer want use to the controls. It frees all internal
  42528. * resources and removes all event listeners.
  42529. */
  42530. dispose() {}
  42531. /**
  42532. * Controls should implement this method if they have to update their internal state
  42533. * per simulation step.
  42534. *
  42535. * @param {number} [delta] - The time delta in seconds.
  42536. */
  42537. update( /* delta */ ) {}
  42538. }
  42539. /**
  42540. * Scales the texture as large as possible within its surface without cropping
  42541. * or stretching the texture. The method preserves the original aspect ratio of
  42542. * the texture. Akin to CSS `object-fit: contain`
  42543. *
  42544. * @param {Texture} texture - The texture.
  42545. * @param {number} aspect - The texture's aspect ratio.
  42546. * @return {Texture} The updated texture.
  42547. */
  42548. function contain( texture, aspect ) {
  42549. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42550. if ( imageAspect > aspect ) {
  42551. texture.repeat.x = 1;
  42552. texture.repeat.y = imageAspect / aspect;
  42553. texture.offset.x = 0;
  42554. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42555. } else {
  42556. texture.repeat.x = aspect / imageAspect;
  42557. texture.repeat.y = 1;
  42558. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42559. texture.offset.y = 0;
  42560. }
  42561. return texture;
  42562. }
  42563. /**
  42564. * Scales the texture to the smallest possible size to fill the surface, leaving
  42565. * no empty space. The method preserves the original aspect ratio of the texture.
  42566. * Akin to CSS `object-fit: cover`.
  42567. *
  42568. * @param {Texture} texture - The texture.
  42569. * @param {number} aspect - The texture's aspect ratio.
  42570. * @return {Texture} The updated texture.
  42571. */
  42572. function cover( texture, aspect ) {
  42573. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42574. if ( imageAspect > aspect ) {
  42575. texture.repeat.x = aspect / imageAspect;
  42576. texture.repeat.y = 1;
  42577. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42578. texture.offset.y = 0;
  42579. } else {
  42580. texture.repeat.x = 1;
  42581. texture.repeat.y = imageAspect / aspect;
  42582. texture.offset.x = 0;
  42583. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42584. }
  42585. return texture;
  42586. }
  42587. /**
  42588. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42589. *
  42590. * @param {Texture} texture - The texture.
  42591. * @return {Texture} The updated texture.
  42592. */
  42593. function fill( texture ) {
  42594. texture.repeat.x = 1;
  42595. texture.repeat.y = 1;
  42596. texture.offset.x = 0;
  42597. texture.offset.y = 0;
  42598. return texture;
  42599. }
  42600. /**
  42601. * Determines how many bytes must be used to represent the texture.
  42602. *
  42603. * @param {number} width - The width of the texture.
  42604. * @param {number} height - The height of the texture.
  42605. * @param {number} format - The texture's format.
  42606. * @param {number} type - The texture's type.
  42607. * @return {number} The byte length.
  42608. */
  42609. function getByteLength( width, height, format, type ) {
  42610. const typeByteLength = getTextureTypeByteLength( type );
  42611. switch ( format ) {
  42612. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42613. case AlphaFormat:
  42614. return width * height;
  42615. case RedFormat:
  42616. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42617. case RedIntegerFormat:
  42618. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42619. case RGFormat:
  42620. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42621. case RGIntegerFormat:
  42622. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42623. case RGBFormat:
  42624. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42625. case RGBAFormat:
  42626. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42627. case RGBAIntegerFormat:
  42628. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42629. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42630. case RGB_S3TC_DXT1_Format:
  42631. case RGBA_S3TC_DXT1_Format:
  42632. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42633. case RGBA_S3TC_DXT3_Format:
  42634. case RGBA_S3TC_DXT5_Format:
  42635. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42636. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42637. case RGB_PVRTC_2BPPV1_Format:
  42638. case RGBA_PVRTC_2BPPV1_Format:
  42639. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42640. case RGB_PVRTC_4BPPV1_Format:
  42641. case RGBA_PVRTC_4BPPV1_Format:
  42642. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42643. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42644. case RGB_ETC1_Format:
  42645. case RGB_ETC2_Format:
  42646. case R11_EAC_Format:
  42647. case SIGNED_R11_EAC_Format:
  42648. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42649. case RGBA_ETC2_EAC_Format:
  42650. case RG11_EAC_Format:
  42651. case SIGNED_RG11_EAC_Format:
  42652. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42653. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42654. case RGBA_ASTC_4x4_Format:
  42655. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42656. case RGBA_ASTC_5x4_Format:
  42657. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42658. case RGBA_ASTC_5x5_Format:
  42659. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42660. case RGBA_ASTC_6x5_Format:
  42661. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42662. case RGBA_ASTC_6x6_Format:
  42663. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42664. case RGBA_ASTC_8x5_Format:
  42665. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42666. case RGBA_ASTC_8x6_Format:
  42667. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42668. case RGBA_ASTC_8x8_Format:
  42669. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42670. case RGBA_ASTC_10x5_Format:
  42671. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42672. case RGBA_ASTC_10x6_Format:
  42673. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42674. case RGBA_ASTC_10x8_Format:
  42675. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42676. case RGBA_ASTC_10x10_Format:
  42677. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42678. case RGBA_ASTC_12x10_Format:
  42679. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42680. case RGBA_ASTC_12x12_Format:
  42681. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42682. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42683. case RGBA_BPTC_Format:
  42684. case RGB_BPTC_SIGNED_Format:
  42685. case RGB_BPTC_UNSIGNED_Format:
  42686. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42687. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42688. case RED_RGTC1_Format:
  42689. case SIGNED_RED_RGTC1_Format:
  42690. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42691. case RED_GREEN_RGTC2_Format:
  42692. case SIGNED_RED_GREEN_RGTC2_Format:
  42693. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42694. }
  42695. throw new Error(
  42696. `Unable to determine texture byte length for ${format} format.`,
  42697. );
  42698. }
  42699. function getTextureTypeByteLength( type ) {
  42700. switch ( type ) {
  42701. case UnsignedByteType:
  42702. case ByteType:
  42703. return { byteLength: 1, components: 1 };
  42704. case UnsignedShortType:
  42705. case ShortType:
  42706. case HalfFloatType:
  42707. return { byteLength: 2, components: 1 };
  42708. case UnsignedShort4444Type:
  42709. case UnsignedShort5551Type:
  42710. return { byteLength: 2, components: 4 };
  42711. case UnsignedIntType:
  42712. case IntType:
  42713. case FloatType:
  42714. return { byteLength: 4, components: 1 };
  42715. case UnsignedInt5999Type:
  42716. case UnsignedInt101111Type:
  42717. return { byteLength: 4, components: 3 };
  42718. }
  42719. throw new Error( `Unknown texture type ${type}.` );
  42720. }
  42721. /**
  42722. * A class containing utility functions for textures.
  42723. *
  42724. * @hideconstructor
  42725. */
  42726. class TextureUtils {
  42727. /**
  42728. * Scales the texture as large as possible within its surface without cropping
  42729. * or stretching the texture. The method preserves the original aspect ratio of
  42730. * the texture. Akin to CSS `object-fit: contain`
  42731. *
  42732. * @param {Texture} texture - The texture.
  42733. * @param {number} aspect - The texture's aspect ratio.
  42734. * @return {Texture} The updated texture.
  42735. */
  42736. static contain( texture, aspect ) {
  42737. return contain( texture, aspect );
  42738. }
  42739. /**
  42740. * Scales the texture to the smallest possible size to fill the surface, leaving
  42741. * no empty space. The method preserves the original aspect ratio of the texture.
  42742. * Akin to CSS `object-fit: cover`.
  42743. *
  42744. * @param {Texture} texture - The texture.
  42745. * @param {number} aspect - The texture's aspect ratio.
  42746. * @return {Texture} The updated texture.
  42747. */
  42748. static cover( texture, aspect ) {
  42749. return cover( texture, aspect );
  42750. }
  42751. /**
  42752. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42753. *
  42754. * @param {Texture} texture - The texture.
  42755. * @return {Texture} The updated texture.
  42756. */
  42757. static fill( texture ) {
  42758. return fill( texture );
  42759. }
  42760. /**
  42761. * Determines how many bytes must be used to represent the texture.
  42762. *
  42763. * @param {number} width - The width of the texture.
  42764. * @param {number} height - The height of the texture.
  42765. * @param {number} format - The texture's format.
  42766. * @param {number} type - The texture's type.
  42767. * @return {number} The byte length.
  42768. */
  42769. static getByteLength( width, height, format, type ) {
  42770. return getByteLength( width, height, format, type );
  42771. }
  42772. }
  42773. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42774. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42775. revision: REVISION,
  42776. } } ) );
  42777. }
  42778. if ( typeof window !== 'undefined' ) {
  42779. if ( window.__THREE__ ) {
  42780. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42781. } else {
  42782. window.__THREE__ = REVISION;
  42783. }
  42784. }
  42785. function WebGLAnimation() {
  42786. let context = null;
  42787. let isAnimating = false;
  42788. let animationLoop = null;
  42789. let requestId = null;
  42790. function onAnimationFrame( time, frame ) {
  42791. animationLoop( time, frame );
  42792. requestId = context.requestAnimationFrame( onAnimationFrame );
  42793. }
  42794. return {
  42795. start: function () {
  42796. if ( isAnimating === true ) return;
  42797. if ( animationLoop === null ) return;
  42798. requestId = context.requestAnimationFrame( onAnimationFrame );
  42799. isAnimating = true;
  42800. },
  42801. stop: function () {
  42802. context.cancelAnimationFrame( requestId );
  42803. isAnimating = false;
  42804. },
  42805. setAnimationLoop: function ( callback ) {
  42806. animationLoop = callback;
  42807. },
  42808. setContext: function ( value ) {
  42809. context = value;
  42810. }
  42811. };
  42812. }
  42813. function WebGLAttributes( gl ) {
  42814. const buffers = new WeakMap();
  42815. function createBuffer( attribute, bufferType ) {
  42816. const array = attribute.array;
  42817. const usage = attribute.usage;
  42818. const size = array.byteLength;
  42819. const buffer = gl.createBuffer();
  42820. gl.bindBuffer( bufferType, buffer );
  42821. gl.bufferData( bufferType, array, usage );
  42822. attribute.onUploadCallback();
  42823. let type;
  42824. if ( array instanceof Float32Array ) {
  42825. type = gl.FLOAT;
  42826. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42827. type = gl.HALF_FLOAT;
  42828. } else if ( array instanceof Uint16Array ) {
  42829. if ( attribute.isFloat16BufferAttribute ) {
  42830. type = gl.HALF_FLOAT;
  42831. } else {
  42832. type = gl.UNSIGNED_SHORT;
  42833. }
  42834. } else if ( array instanceof Int16Array ) {
  42835. type = gl.SHORT;
  42836. } else if ( array instanceof Uint32Array ) {
  42837. type = gl.UNSIGNED_INT;
  42838. } else if ( array instanceof Int32Array ) {
  42839. type = gl.INT;
  42840. } else if ( array instanceof Int8Array ) {
  42841. type = gl.BYTE;
  42842. } else if ( array instanceof Uint8Array ) {
  42843. type = gl.UNSIGNED_BYTE;
  42844. } else if ( array instanceof Uint8ClampedArray ) {
  42845. type = gl.UNSIGNED_BYTE;
  42846. } else {
  42847. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42848. }
  42849. return {
  42850. buffer: buffer,
  42851. type: type,
  42852. bytesPerElement: array.BYTES_PER_ELEMENT,
  42853. version: attribute.version,
  42854. size: size
  42855. };
  42856. }
  42857. function updateBuffer( buffer, attribute, bufferType ) {
  42858. const array = attribute.array;
  42859. const updateRanges = attribute.updateRanges;
  42860. gl.bindBuffer( bufferType, buffer );
  42861. if ( updateRanges.length === 0 ) {
  42862. // Not using update ranges
  42863. gl.bufferSubData( bufferType, 0, array );
  42864. } else {
  42865. // Before applying update ranges, we merge any adjacent / overlapping
  42866. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42867. // to performance improvements for applications which make heavy use of
  42868. // update ranges. Likely due to GPU command overhead.
  42869. //
  42870. // Note that to reduce garbage collection between frames, we merge the
  42871. // update ranges in-place. This is safe because this method will clear the
  42872. // update ranges once updated.
  42873. updateRanges.sort( ( a, b ) => a.start - b.start );
  42874. // To merge the update ranges in-place, we work from left to right in the
  42875. // existing updateRanges array, merging ranges. This may result in a final
  42876. // array which is smaller than the original. This index tracks the last
  42877. // index representing a merged range, any data after this index can be
  42878. // trimmed once the merge algorithm is completed.
  42879. let mergeIndex = 0;
  42880. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42881. const previousRange = updateRanges[ mergeIndex ];
  42882. const range = updateRanges[ i ];
  42883. // We add one here to merge adjacent ranges. This is safe because ranges
  42884. // operate over positive integers.
  42885. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42886. previousRange.count = Math.max(
  42887. previousRange.count,
  42888. range.start + range.count - previousRange.start
  42889. );
  42890. } else {
  42891. ++ mergeIndex;
  42892. updateRanges[ mergeIndex ] = range;
  42893. }
  42894. }
  42895. // Trim the array to only contain the merged ranges.
  42896. updateRanges.length = mergeIndex + 1;
  42897. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42898. const range = updateRanges[ i ];
  42899. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42900. array, range.start, range.count );
  42901. }
  42902. attribute.clearUpdateRanges();
  42903. }
  42904. attribute.onUploadCallback();
  42905. }
  42906. //
  42907. function get( attribute ) {
  42908. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42909. return buffers.get( attribute );
  42910. }
  42911. function remove( attribute ) {
  42912. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42913. const data = buffers.get( attribute );
  42914. if ( data ) {
  42915. gl.deleteBuffer( data.buffer );
  42916. buffers.delete( attribute );
  42917. }
  42918. }
  42919. function update( attribute, bufferType ) {
  42920. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42921. if ( attribute.isGLBufferAttribute ) {
  42922. const cached = buffers.get( attribute );
  42923. if ( ! cached || cached.version < attribute.version ) {
  42924. buffers.set( attribute, {
  42925. buffer: attribute.buffer,
  42926. type: attribute.type,
  42927. bytesPerElement: attribute.elementSize,
  42928. version: attribute.version
  42929. } );
  42930. }
  42931. return;
  42932. }
  42933. const data = buffers.get( attribute );
  42934. if ( data === undefined ) {
  42935. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42936. } else if ( data.version < attribute.version ) {
  42937. if ( data.size !== attribute.array.byteLength ) {
  42938. 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.' );
  42939. }
  42940. updateBuffer( data.buffer, attribute, bufferType );
  42941. data.version = attribute.version;
  42942. }
  42943. }
  42944. return {
  42945. get: get,
  42946. remove: remove,
  42947. update: update
  42948. };
  42949. }
  42950. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42951. 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";
  42952. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42953. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42954. 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";
  42955. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42956. 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";
  42957. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42958. 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\tvec3 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 ).rgb;\n\t}\n#endif";
  42959. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42960. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42961. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42962. 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";
  42963. 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";
  42964. 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";
  42965. 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";
  42966. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42967. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42968. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42969. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42970. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42971. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42972. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  42973. 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";
  42974. 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";
  42975. 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";
  42976. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42977. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42978. 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";
  42979. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42980. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42981. 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}";
  42982. 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#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  42983. 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";
  42984. 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";
  42985. 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";
  42986. 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";
  42987. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42988. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42989. 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";
  42990. 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";
  42991. 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}";
  42992. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42993. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42994. 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";
  42995. 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";
  42996. 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";
  42997. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42998. 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";
  42999. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  43000. 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";
  43001. 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";
  43002. 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}";
  43003. 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";
  43004. 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( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\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";
  43005. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\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";
  43006. 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";
  43007. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43008. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43009. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  43010. 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";
  43011. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  43012. 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";
  43013. 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";
  43014. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  43015. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  43016. 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";
  43017. 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";
  43018. 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";
  43019. 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";
  43020. 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";
  43021. 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;";
  43022. 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";
  43023. 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";
  43024. 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";
  43025. 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";
  43026. 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";
  43027. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  43028. 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";
  43029. 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";
  43030. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43031. 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 );";
  43032. 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\treturn depth * ( near - far ) - near;\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\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  43033. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43034. 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;";
  43035. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43036. 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";
  43037. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43038. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43039. 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 ) * 6.28318530718;\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\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 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\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\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\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\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\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 ) * 6.28318530718;\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 0, 5, phi ).x + bitangent * vogelDiskSample( 0, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 1, 5, phi ).x + bitangent * vogelDiskSample( 1, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 2, 5, phi ).x + bitangent * vogelDiskSample( 2, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 3, 5, phi ).x + bitangent * vogelDiskSample( 3, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 4, 5, phi ).x + bitangent * vogelDiskSample( 4, 5, phi ).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 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\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadow = step( depth, dp );\n\t\t\t#else\n\t\t\t\tshadow = step( dp, depth );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  43040. 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";
  43041. 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";
  43042. 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}";
  43043. 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";
  43044. 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";
  43045. 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";
  43046. 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";
  43047. 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";
  43048. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43049. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43050. 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; }";
  43051. 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";
  43052. 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";
  43053. 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";
  43054. 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";
  43055. 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";
  43056. 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";
  43057. 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}";
  43058. 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}";
  43059. 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}";
  43060. 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}";
  43061. 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}";
  43062. 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}";
  43063. 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}";
  43064. 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}";
  43065. 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}";
  43066. 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}";
  43067. 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}";
  43068. 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}";
  43069. 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}";
  43070. 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}";
  43071. 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}";
  43072. 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}";
  43073. 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}";
  43074. 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 <envmap_common_pars_fragment>\n#include <envmap_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}";
  43075. 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}";
  43076. 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}";
  43077. 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}";
  43078. 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}";
  43079. 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}";
  43080. 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 <envmap_common_pars_fragment>\n#include <envmap_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}";
  43081. 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}";
  43082. 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}";
  43083. 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}";
  43084. 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}";
  43085. 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}";
  43086. 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}";
  43087. 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}";
  43088. 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}";
  43089. 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}";
  43090. 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}";
  43091. const ShaderChunk = {
  43092. alphahash_fragment: alphahash_fragment,
  43093. alphahash_pars_fragment: alphahash_pars_fragment,
  43094. alphamap_fragment: alphamap_fragment,
  43095. alphamap_pars_fragment: alphamap_pars_fragment,
  43096. alphatest_fragment: alphatest_fragment,
  43097. alphatest_pars_fragment: alphatest_pars_fragment,
  43098. aomap_fragment: aomap_fragment,
  43099. aomap_pars_fragment: aomap_pars_fragment,
  43100. batching_pars_vertex: batching_pars_vertex,
  43101. batching_vertex: batching_vertex,
  43102. begin_vertex: begin_vertex,
  43103. beginnormal_vertex: beginnormal_vertex,
  43104. bsdfs: bsdfs,
  43105. iridescence_fragment: iridescence_fragment,
  43106. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43107. clipping_planes_fragment: clipping_planes_fragment,
  43108. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43109. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43110. clipping_planes_vertex: clipping_planes_vertex,
  43111. color_fragment: color_fragment,
  43112. color_pars_fragment: color_pars_fragment,
  43113. color_pars_vertex: color_pars_vertex,
  43114. color_vertex: color_vertex,
  43115. common: common,
  43116. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43117. defaultnormal_vertex: defaultnormal_vertex,
  43118. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43119. displacementmap_vertex: displacementmap_vertex,
  43120. emissivemap_fragment: emissivemap_fragment,
  43121. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43122. colorspace_fragment: colorspace_fragment,
  43123. colorspace_pars_fragment: colorspace_pars_fragment,
  43124. envmap_fragment: envmap_fragment,
  43125. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43126. envmap_pars_fragment: envmap_pars_fragment,
  43127. envmap_pars_vertex: envmap_pars_vertex,
  43128. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43129. envmap_vertex: envmap_vertex,
  43130. fog_vertex: fog_vertex,
  43131. fog_pars_vertex: fog_pars_vertex,
  43132. fog_fragment: fog_fragment,
  43133. fog_pars_fragment: fog_pars_fragment,
  43134. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43135. lightmap_pars_fragment: lightmap_pars_fragment,
  43136. lights_lambert_fragment: lights_lambert_fragment,
  43137. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43138. lights_pars_begin: lights_pars_begin,
  43139. lights_toon_fragment: lights_toon_fragment,
  43140. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43141. lights_phong_fragment: lights_phong_fragment,
  43142. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43143. lights_physical_fragment: lights_physical_fragment,
  43144. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43145. lights_fragment_begin: lights_fragment_begin,
  43146. lights_fragment_maps: lights_fragment_maps,
  43147. lights_fragment_end: lights_fragment_end,
  43148. logdepthbuf_fragment: logdepthbuf_fragment,
  43149. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43150. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43151. logdepthbuf_vertex: logdepthbuf_vertex,
  43152. map_fragment: map_fragment,
  43153. map_pars_fragment: map_pars_fragment,
  43154. map_particle_fragment: map_particle_fragment,
  43155. map_particle_pars_fragment: map_particle_pars_fragment,
  43156. metalnessmap_fragment: metalnessmap_fragment,
  43157. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43158. morphinstance_vertex: morphinstance_vertex,
  43159. morphcolor_vertex: morphcolor_vertex,
  43160. morphnormal_vertex: morphnormal_vertex,
  43161. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43162. morphtarget_vertex: morphtarget_vertex,
  43163. normal_fragment_begin: normal_fragment_begin,
  43164. normal_fragment_maps: normal_fragment_maps,
  43165. normal_pars_fragment: normal_pars_fragment,
  43166. normal_pars_vertex: normal_pars_vertex,
  43167. normal_vertex: normal_vertex,
  43168. normalmap_pars_fragment: normalmap_pars_fragment,
  43169. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43170. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43171. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43172. iridescence_pars_fragment: iridescence_pars_fragment,
  43173. opaque_fragment: opaque_fragment,
  43174. packing: packing,
  43175. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43176. project_vertex: project_vertex,
  43177. dithering_fragment: dithering_fragment,
  43178. dithering_pars_fragment: dithering_pars_fragment,
  43179. roughnessmap_fragment: roughnessmap_fragment,
  43180. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43181. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43182. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43183. shadowmap_vertex: shadowmap_vertex,
  43184. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43185. skinbase_vertex: skinbase_vertex,
  43186. skinning_pars_vertex: skinning_pars_vertex,
  43187. skinning_vertex: skinning_vertex,
  43188. skinnormal_vertex: skinnormal_vertex,
  43189. specularmap_fragment: specularmap_fragment,
  43190. specularmap_pars_fragment: specularmap_pars_fragment,
  43191. tonemapping_fragment: tonemapping_fragment,
  43192. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43193. transmission_fragment: transmission_fragment,
  43194. transmission_pars_fragment: transmission_pars_fragment,
  43195. uv_pars_fragment: uv_pars_fragment,
  43196. uv_pars_vertex: uv_pars_vertex,
  43197. uv_vertex: uv_vertex,
  43198. worldpos_vertex: worldpos_vertex,
  43199. background_vert: vertex$h,
  43200. background_frag: fragment$h,
  43201. backgroundCube_vert: vertex$g,
  43202. backgroundCube_frag: fragment$g,
  43203. cube_vert: vertex$f,
  43204. cube_frag: fragment$f,
  43205. depth_vert: vertex$e,
  43206. depth_frag: fragment$e,
  43207. distance_vert: vertex$d,
  43208. distance_frag: fragment$d,
  43209. equirect_vert: vertex$c,
  43210. equirect_frag: fragment$c,
  43211. linedashed_vert: vertex$b,
  43212. linedashed_frag: fragment$b,
  43213. meshbasic_vert: vertex$a,
  43214. meshbasic_frag: fragment$a,
  43215. meshlambert_vert: vertex$9,
  43216. meshlambert_frag: fragment$9,
  43217. meshmatcap_vert: vertex$8,
  43218. meshmatcap_frag: fragment$8,
  43219. meshnormal_vert: vertex$7,
  43220. meshnormal_frag: fragment$7,
  43221. meshphong_vert: vertex$6,
  43222. meshphong_frag: fragment$6,
  43223. meshphysical_vert: vertex$5,
  43224. meshphysical_frag: fragment$5,
  43225. meshtoon_vert: vertex$4,
  43226. meshtoon_frag: fragment$4,
  43227. points_vert: vertex$3,
  43228. points_frag: fragment$3,
  43229. shadow_vert: vertex$2,
  43230. shadow_frag: fragment$2,
  43231. sprite_vert: vertex$1,
  43232. sprite_frag: fragment$1
  43233. };
  43234. // Uniforms library for shared webgl shaders
  43235. const UniformsLib = {
  43236. common: {
  43237. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43238. opacity: { value: 1.0 },
  43239. map: { value: null },
  43240. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43241. alphaMap: { value: null },
  43242. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43243. alphaTest: { value: 0 }
  43244. },
  43245. specularmap: {
  43246. specularMap: { value: null },
  43247. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43248. },
  43249. envmap: {
  43250. envMap: { value: null },
  43251. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43252. flipEnvMap: { value: -1 },
  43253. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43254. ior: { value: 1.5 }, // physical
  43255. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43256. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43257. },
  43258. aomap: {
  43259. aoMap: { value: null },
  43260. aoMapIntensity: { value: 1 },
  43261. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43262. },
  43263. lightmap: {
  43264. lightMap: { value: null },
  43265. lightMapIntensity: { value: 1 },
  43266. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43267. },
  43268. bumpmap: {
  43269. bumpMap: { value: null },
  43270. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43271. bumpScale: { value: 1 }
  43272. },
  43273. normalmap: {
  43274. normalMap: { value: null },
  43275. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43276. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43277. },
  43278. displacementmap: {
  43279. displacementMap: { value: null },
  43280. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43281. displacementScale: { value: 1 },
  43282. displacementBias: { value: 0 }
  43283. },
  43284. emissivemap: {
  43285. emissiveMap: { value: null },
  43286. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43287. },
  43288. metalnessmap: {
  43289. metalnessMap: { value: null },
  43290. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43291. },
  43292. roughnessmap: {
  43293. roughnessMap: { value: null },
  43294. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43295. },
  43296. gradientmap: {
  43297. gradientMap: { value: null }
  43298. },
  43299. fog: {
  43300. fogDensity: { value: 0.00025 },
  43301. fogNear: { value: 1 },
  43302. fogFar: { value: 2000 },
  43303. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43304. },
  43305. lights: {
  43306. ambientLightColor: { value: [] },
  43307. lightProbe: { value: [] },
  43308. directionalLights: { value: [], properties: {
  43309. direction: {},
  43310. color: {}
  43311. } },
  43312. directionalLightShadows: { value: [], properties: {
  43313. shadowIntensity: 1,
  43314. shadowBias: {},
  43315. shadowNormalBias: {},
  43316. shadowRadius: {},
  43317. shadowMapSize: {}
  43318. } },
  43319. directionalShadowMatrix: { value: [] },
  43320. spotLights: { value: [], properties: {
  43321. color: {},
  43322. position: {},
  43323. direction: {},
  43324. distance: {},
  43325. coneCos: {},
  43326. penumbraCos: {},
  43327. decay: {}
  43328. } },
  43329. spotLightShadows: { value: [], properties: {
  43330. shadowIntensity: 1,
  43331. shadowBias: {},
  43332. shadowNormalBias: {},
  43333. shadowRadius: {},
  43334. shadowMapSize: {}
  43335. } },
  43336. spotLightMap: { value: [] },
  43337. spotLightMatrix: { value: [] },
  43338. pointLights: { value: [], properties: {
  43339. color: {},
  43340. position: {},
  43341. decay: {},
  43342. distance: {}
  43343. } },
  43344. pointLightShadows: { value: [], properties: {
  43345. shadowIntensity: 1,
  43346. shadowBias: {},
  43347. shadowNormalBias: {},
  43348. shadowRadius: {},
  43349. shadowMapSize: {},
  43350. shadowCameraNear: {},
  43351. shadowCameraFar: {}
  43352. } },
  43353. pointShadowMatrix: { value: [] },
  43354. hemisphereLights: { value: [], properties: {
  43355. direction: {},
  43356. skyColor: {},
  43357. groundColor: {}
  43358. } },
  43359. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43360. rectAreaLights: { value: [], properties: {
  43361. color: {},
  43362. position: {},
  43363. width: {},
  43364. height: {}
  43365. } },
  43366. ltc_1: { value: null },
  43367. ltc_2: { value: null }
  43368. },
  43369. points: {
  43370. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43371. opacity: { value: 1.0 },
  43372. size: { value: 1.0 },
  43373. scale: { value: 1.0 },
  43374. map: { value: null },
  43375. alphaMap: { value: null },
  43376. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43377. alphaTest: { value: 0 },
  43378. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43379. },
  43380. sprite: {
  43381. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43382. opacity: { value: 1.0 },
  43383. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43384. rotation: { value: 0.0 },
  43385. map: { value: null },
  43386. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43387. alphaMap: { value: null },
  43388. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43389. alphaTest: { value: 0 }
  43390. }
  43391. };
  43392. const ShaderLib = {
  43393. basic: {
  43394. uniforms: /*@__PURE__*/ mergeUniforms( [
  43395. UniformsLib.common,
  43396. UniformsLib.specularmap,
  43397. UniformsLib.envmap,
  43398. UniformsLib.aomap,
  43399. UniformsLib.lightmap,
  43400. UniformsLib.fog
  43401. ] ),
  43402. vertexShader: ShaderChunk.meshbasic_vert,
  43403. fragmentShader: ShaderChunk.meshbasic_frag
  43404. },
  43405. lambert: {
  43406. uniforms: /*@__PURE__*/ mergeUniforms( [
  43407. UniformsLib.common,
  43408. UniformsLib.specularmap,
  43409. UniformsLib.envmap,
  43410. UniformsLib.aomap,
  43411. UniformsLib.lightmap,
  43412. UniformsLib.emissivemap,
  43413. UniformsLib.bumpmap,
  43414. UniformsLib.normalmap,
  43415. UniformsLib.displacementmap,
  43416. UniformsLib.fog,
  43417. UniformsLib.lights,
  43418. {
  43419. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43420. }
  43421. ] ),
  43422. vertexShader: ShaderChunk.meshlambert_vert,
  43423. fragmentShader: ShaderChunk.meshlambert_frag
  43424. },
  43425. phong: {
  43426. uniforms: /*@__PURE__*/ mergeUniforms( [
  43427. UniformsLib.common,
  43428. UniformsLib.specularmap,
  43429. UniformsLib.envmap,
  43430. UniformsLib.aomap,
  43431. UniformsLib.lightmap,
  43432. UniformsLib.emissivemap,
  43433. UniformsLib.bumpmap,
  43434. UniformsLib.normalmap,
  43435. UniformsLib.displacementmap,
  43436. UniformsLib.fog,
  43437. UniformsLib.lights,
  43438. {
  43439. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43440. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43441. shininess: { value: 30 }
  43442. }
  43443. ] ),
  43444. vertexShader: ShaderChunk.meshphong_vert,
  43445. fragmentShader: ShaderChunk.meshphong_frag
  43446. },
  43447. standard: {
  43448. uniforms: /*@__PURE__*/ mergeUniforms( [
  43449. UniformsLib.common,
  43450. UniformsLib.envmap,
  43451. UniformsLib.aomap,
  43452. UniformsLib.lightmap,
  43453. UniformsLib.emissivemap,
  43454. UniformsLib.bumpmap,
  43455. UniformsLib.normalmap,
  43456. UniformsLib.displacementmap,
  43457. UniformsLib.roughnessmap,
  43458. UniformsLib.metalnessmap,
  43459. UniformsLib.fog,
  43460. UniformsLib.lights,
  43461. {
  43462. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43463. roughness: { value: 1.0 },
  43464. metalness: { value: 0.0 },
  43465. envMapIntensity: { value: 1 }
  43466. }
  43467. ] ),
  43468. vertexShader: ShaderChunk.meshphysical_vert,
  43469. fragmentShader: ShaderChunk.meshphysical_frag
  43470. },
  43471. toon: {
  43472. uniforms: /*@__PURE__*/ mergeUniforms( [
  43473. UniformsLib.common,
  43474. UniformsLib.aomap,
  43475. UniformsLib.lightmap,
  43476. UniformsLib.emissivemap,
  43477. UniformsLib.bumpmap,
  43478. UniformsLib.normalmap,
  43479. UniformsLib.displacementmap,
  43480. UniformsLib.gradientmap,
  43481. UniformsLib.fog,
  43482. UniformsLib.lights,
  43483. {
  43484. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43485. }
  43486. ] ),
  43487. vertexShader: ShaderChunk.meshtoon_vert,
  43488. fragmentShader: ShaderChunk.meshtoon_frag
  43489. },
  43490. matcap: {
  43491. uniforms: /*@__PURE__*/ mergeUniforms( [
  43492. UniformsLib.common,
  43493. UniformsLib.bumpmap,
  43494. UniformsLib.normalmap,
  43495. UniformsLib.displacementmap,
  43496. UniformsLib.fog,
  43497. {
  43498. matcap: { value: null }
  43499. }
  43500. ] ),
  43501. vertexShader: ShaderChunk.meshmatcap_vert,
  43502. fragmentShader: ShaderChunk.meshmatcap_frag
  43503. },
  43504. points: {
  43505. uniforms: /*@__PURE__*/ mergeUniforms( [
  43506. UniformsLib.points,
  43507. UniformsLib.fog
  43508. ] ),
  43509. vertexShader: ShaderChunk.points_vert,
  43510. fragmentShader: ShaderChunk.points_frag
  43511. },
  43512. dashed: {
  43513. uniforms: /*@__PURE__*/ mergeUniforms( [
  43514. UniformsLib.common,
  43515. UniformsLib.fog,
  43516. {
  43517. scale: { value: 1 },
  43518. dashSize: { value: 1 },
  43519. totalSize: { value: 2 }
  43520. }
  43521. ] ),
  43522. vertexShader: ShaderChunk.linedashed_vert,
  43523. fragmentShader: ShaderChunk.linedashed_frag
  43524. },
  43525. depth: {
  43526. uniforms: /*@__PURE__*/ mergeUniforms( [
  43527. UniformsLib.common,
  43528. UniformsLib.displacementmap
  43529. ] ),
  43530. vertexShader: ShaderChunk.depth_vert,
  43531. fragmentShader: ShaderChunk.depth_frag
  43532. },
  43533. normal: {
  43534. uniforms: /*@__PURE__*/ mergeUniforms( [
  43535. UniformsLib.common,
  43536. UniformsLib.bumpmap,
  43537. UniformsLib.normalmap,
  43538. UniformsLib.displacementmap,
  43539. {
  43540. opacity: { value: 1.0 }
  43541. }
  43542. ] ),
  43543. vertexShader: ShaderChunk.meshnormal_vert,
  43544. fragmentShader: ShaderChunk.meshnormal_frag
  43545. },
  43546. sprite: {
  43547. uniforms: /*@__PURE__*/ mergeUniforms( [
  43548. UniformsLib.sprite,
  43549. UniformsLib.fog
  43550. ] ),
  43551. vertexShader: ShaderChunk.sprite_vert,
  43552. fragmentShader: ShaderChunk.sprite_frag
  43553. },
  43554. background: {
  43555. uniforms: {
  43556. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43557. t2D: { value: null },
  43558. backgroundIntensity: { value: 1 }
  43559. },
  43560. vertexShader: ShaderChunk.background_vert,
  43561. fragmentShader: ShaderChunk.background_frag
  43562. },
  43563. backgroundCube: {
  43564. uniforms: {
  43565. envMap: { value: null },
  43566. flipEnvMap: { value: -1 },
  43567. backgroundBlurriness: { value: 0 },
  43568. backgroundIntensity: { value: 1 },
  43569. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43570. },
  43571. vertexShader: ShaderChunk.backgroundCube_vert,
  43572. fragmentShader: ShaderChunk.backgroundCube_frag
  43573. },
  43574. cube: {
  43575. uniforms: {
  43576. tCube: { value: null },
  43577. tFlip: { value: -1 },
  43578. opacity: { value: 1.0 }
  43579. },
  43580. vertexShader: ShaderChunk.cube_vert,
  43581. fragmentShader: ShaderChunk.cube_frag
  43582. },
  43583. equirect: {
  43584. uniforms: {
  43585. tEquirect: { value: null },
  43586. },
  43587. vertexShader: ShaderChunk.equirect_vert,
  43588. fragmentShader: ShaderChunk.equirect_frag
  43589. },
  43590. distance: {
  43591. uniforms: /*@__PURE__*/ mergeUniforms( [
  43592. UniformsLib.common,
  43593. UniformsLib.displacementmap,
  43594. {
  43595. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43596. nearDistance: { value: 1 },
  43597. farDistance: { value: 1000 }
  43598. }
  43599. ] ),
  43600. vertexShader: ShaderChunk.distance_vert,
  43601. fragmentShader: ShaderChunk.distance_frag
  43602. },
  43603. shadow: {
  43604. uniforms: /*@__PURE__*/ mergeUniforms( [
  43605. UniformsLib.lights,
  43606. UniformsLib.fog,
  43607. {
  43608. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43609. opacity: { value: 1.0 }
  43610. },
  43611. ] ),
  43612. vertexShader: ShaderChunk.shadow_vert,
  43613. fragmentShader: ShaderChunk.shadow_frag
  43614. }
  43615. };
  43616. ShaderLib.physical = {
  43617. uniforms: /*@__PURE__*/ mergeUniforms( [
  43618. ShaderLib.standard.uniforms,
  43619. {
  43620. clearcoat: { value: 0 },
  43621. clearcoatMap: { value: null },
  43622. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43623. clearcoatNormalMap: { value: null },
  43624. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43625. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43626. clearcoatRoughness: { value: 0 },
  43627. clearcoatRoughnessMap: { value: null },
  43628. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43629. dispersion: { value: 0 },
  43630. iridescence: { value: 0 },
  43631. iridescenceMap: { value: null },
  43632. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43633. iridescenceIOR: { value: 1.3 },
  43634. iridescenceThicknessMinimum: { value: 100 },
  43635. iridescenceThicknessMaximum: { value: 400 },
  43636. iridescenceThicknessMap: { value: null },
  43637. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43638. sheen: { value: 0 },
  43639. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43640. sheenColorMap: { value: null },
  43641. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43642. sheenRoughness: { value: 1 },
  43643. sheenRoughnessMap: { value: null },
  43644. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43645. transmission: { value: 0 },
  43646. transmissionMap: { value: null },
  43647. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43648. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43649. transmissionSamplerMap: { value: null },
  43650. thickness: { value: 0 },
  43651. thicknessMap: { value: null },
  43652. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43653. attenuationDistance: { value: 0 },
  43654. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43655. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43656. specularColorMap: { value: null },
  43657. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43658. specularIntensity: { value: 1 },
  43659. specularIntensityMap: { value: null },
  43660. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43661. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43662. anisotropyMap: { value: null },
  43663. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43664. }
  43665. ] ),
  43666. vertexShader: ShaderChunk.meshphysical_vert,
  43667. fragmentShader: ShaderChunk.meshphysical_frag
  43668. };
  43669. const _rgb = { r: 0, b: 0, g: 0 };
  43670. const _e1$1 = /*@__PURE__*/ new Euler();
  43671. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43672. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43673. const clearColor = new Color( 0x000000 );
  43674. let clearAlpha = alpha === true ? 0 : 1;
  43675. let planeMesh;
  43676. let boxMesh;
  43677. let currentBackground = null;
  43678. let currentBackgroundVersion = 0;
  43679. let currentTonemapping = null;
  43680. function getBackground( scene ) {
  43681. let background = scene.isScene === true ? scene.background : null;
  43682. if ( background && background.isTexture ) {
  43683. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43684. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43685. }
  43686. return background;
  43687. }
  43688. function render( scene ) {
  43689. let forceClear = false;
  43690. const background = getBackground( scene );
  43691. if ( background === null ) {
  43692. setClear( clearColor, clearAlpha );
  43693. } else if ( background && background.isColor ) {
  43694. setClear( background, 1 );
  43695. forceClear = true;
  43696. }
  43697. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43698. if ( environmentBlendMode === 'additive' ) {
  43699. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43700. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43701. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43702. }
  43703. if ( renderer.autoClear || forceClear ) {
  43704. // buffers might not be writable which is required to ensure a correct clear
  43705. state.buffers.depth.setTest( true );
  43706. state.buffers.depth.setMask( true );
  43707. state.buffers.color.setMask( true );
  43708. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43709. }
  43710. }
  43711. function addToRenderList( renderList, scene ) {
  43712. const background = getBackground( scene );
  43713. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43714. if ( boxMesh === undefined ) {
  43715. boxMesh = new Mesh(
  43716. new BoxGeometry( 1, 1, 1 ),
  43717. new ShaderMaterial( {
  43718. name: 'BackgroundCubeMaterial',
  43719. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43720. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43721. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43722. side: BackSide,
  43723. depthTest: false,
  43724. depthWrite: false,
  43725. fog: false,
  43726. allowOverride: false
  43727. } )
  43728. );
  43729. boxMesh.geometry.deleteAttribute( 'normal' );
  43730. boxMesh.geometry.deleteAttribute( 'uv' );
  43731. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43732. this.matrixWorld.copyPosition( camera.matrixWorld );
  43733. };
  43734. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43735. Object.defineProperty( boxMesh.material, 'envMap', {
  43736. get: function () {
  43737. return this.uniforms.envMap.value;
  43738. }
  43739. } );
  43740. objects.update( boxMesh );
  43741. }
  43742. _e1$1.copy( scene.backgroundRotation );
  43743. // accommodate left-handed frame
  43744. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43745. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43746. // environment maps which are not cube render targets or PMREMs follow a different convention
  43747. _e1$1.y *= -1;
  43748. _e1$1.z *= -1;
  43749. }
  43750. boxMesh.material.uniforms.envMap.value = background;
  43751. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43752. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43753. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43754. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43755. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43756. if ( currentBackground !== background ||
  43757. currentBackgroundVersion !== background.version ||
  43758. currentTonemapping !== renderer.toneMapping ) {
  43759. boxMesh.material.needsUpdate = true;
  43760. currentBackground = background;
  43761. currentBackgroundVersion = background.version;
  43762. currentTonemapping = renderer.toneMapping;
  43763. }
  43764. boxMesh.layers.enableAll();
  43765. // push to the pre-sorted opaque render list
  43766. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43767. } else if ( background && background.isTexture ) {
  43768. if ( planeMesh === undefined ) {
  43769. planeMesh = new Mesh(
  43770. new PlaneGeometry( 2, 2 ),
  43771. new ShaderMaterial( {
  43772. name: 'BackgroundMaterial',
  43773. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43774. vertexShader: ShaderLib.background.vertexShader,
  43775. fragmentShader: ShaderLib.background.fragmentShader,
  43776. side: FrontSide,
  43777. depthTest: false,
  43778. depthWrite: false,
  43779. fog: false,
  43780. allowOverride: false
  43781. } )
  43782. );
  43783. planeMesh.geometry.deleteAttribute( 'normal' );
  43784. // add "map" material property so the renderer can evaluate it like for built-in materials
  43785. Object.defineProperty( planeMesh.material, 'map', {
  43786. get: function () {
  43787. return this.uniforms.t2D.value;
  43788. }
  43789. } );
  43790. objects.update( planeMesh );
  43791. }
  43792. planeMesh.material.uniforms.t2D.value = background;
  43793. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43794. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43795. if ( background.matrixAutoUpdate === true ) {
  43796. background.updateMatrix();
  43797. }
  43798. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43799. if ( currentBackground !== background ||
  43800. currentBackgroundVersion !== background.version ||
  43801. currentTonemapping !== renderer.toneMapping ) {
  43802. planeMesh.material.needsUpdate = true;
  43803. currentBackground = background;
  43804. currentBackgroundVersion = background.version;
  43805. currentTonemapping = renderer.toneMapping;
  43806. }
  43807. planeMesh.layers.enableAll();
  43808. // push to the pre-sorted opaque render list
  43809. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43810. }
  43811. }
  43812. function setClear( color, alpha ) {
  43813. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43814. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43815. }
  43816. function dispose() {
  43817. if ( boxMesh !== undefined ) {
  43818. boxMesh.geometry.dispose();
  43819. boxMesh.material.dispose();
  43820. boxMesh = undefined;
  43821. }
  43822. if ( planeMesh !== undefined ) {
  43823. planeMesh.geometry.dispose();
  43824. planeMesh.material.dispose();
  43825. planeMesh = undefined;
  43826. }
  43827. }
  43828. return {
  43829. getClearColor: function () {
  43830. return clearColor;
  43831. },
  43832. setClearColor: function ( color, alpha = 1 ) {
  43833. clearColor.set( color );
  43834. clearAlpha = alpha;
  43835. setClear( clearColor, clearAlpha );
  43836. },
  43837. getClearAlpha: function () {
  43838. return clearAlpha;
  43839. },
  43840. setClearAlpha: function ( alpha ) {
  43841. clearAlpha = alpha;
  43842. setClear( clearColor, clearAlpha );
  43843. },
  43844. render: render,
  43845. addToRenderList: addToRenderList,
  43846. dispose: dispose
  43847. };
  43848. }
  43849. function WebGLBindingStates( gl, attributes ) {
  43850. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43851. const bindingStates = {};
  43852. const defaultState = createBindingState( null );
  43853. let currentState = defaultState;
  43854. let forceUpdate = false;
  43855. function setup( object, material, program, geometry, index ) {
  43856. let updateBuffers = false;
  43857. const state = getBindingState( object, geometry, program, material );
  43858. if ( currentState !== state ) {
  43859. currentState = state;
  43860. bindVertexArrayObject( currentState.object );
  43861. }
  43862. updateBuffers = needsUpdate( object, geometry, program, index );
  43863. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43864. if ( index !== null ) {
  43865. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43866. }
  43867. if ( updateBuffers || forceUpdate ) {
  43868. forceUpdate = false;
  43869. setupVertexAttributes( object, material, program, geometry );
  43870. if ( index !== null ) {
  43871. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43872. }
  43873. }
  43874. }
  43875. function createVertexArrayObject() {
  43876. return gl.createVertexArray();
  43877. }
  43878. function bindVertexArrayObject( vao ) {
  43879. return gl.bindVertexArray( vao );
  43880. }
  43881. function deleteVertexArrayObject( vao ) {
  43882. return gl.deleteVertexArray( vao );
  43883. }
  43884. function getBindingState( object, geometry, program, material ) {
  43885. const wireframe = ( material.wireframe === true );
  43886. let objectMap = bindingStates[ geometry.id ];
  43887. if ( objectMap === undefined ) {
  43888. objectMap = {};
  43889. bindingStates[ geometry.id ] = objectMap;
  43890. }
  43891. // Each InstancedMesh requires unique binding states because it contains instanced attributes.
  43892. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  43893. let programMap = objectMap[ objectId ];
  43894. if ( programMap === undefined ) {
  43895. programMap = {};
  43896. objectMap[ objectId ] = programMap;
  43897. }
  43898. let stateMap = programMap[ program.id ];
  43899. if ( stateMap === undefined ) {
  43900. stateMap = {};
  43901. programMap[ program.id ] = stateMap;
  43902. }
  43903. let state = stateMap[ wireframe ];
  43904. if ( state === undefined ) {
  43905. state = createBindingState( createVertexArrayObject() );
  43906. stateMap[ wireframe ] = state;
  43907. }
  43908. return state;
  43909. }
  43910. function createBindingState( vao ) {
  43911. const newAttributes = [];
  43912. const enabledAttributes = [];
  43913. const attributeDivisors = [];
  43914. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43915. newAttributes[ i ] = 0;
  43916. enabledAttributes[ i ] = 0;
  43917. attributeDivisors[ i ] = 0;
  43918. }
  43919. return {
  43920. // for backward compatibility on non-VAO support browser
  43921. geometry: null,
  43922. program: null,
  43923. wireframe: false,
  43924. newAttributes: newAttributes,
  43925. enabledAttributes: enabledAttributes,
  43926. attributeDivisors: attributeDivisors,
  43927. object: vao,
  43928. attributes: {},
  43929. index: null
  43930. };
  43931. }
  43932. function needsUpdate( object, geometry, program, index ) {
  43933. const cachedAttributes = currentState.attributes;
  43934. const geometryAttributes = geometry.attributes;
  43935. let attributesNum = 0;
  43936. const programAttributes = program.getAttributes();
  43937. for ( const name in programAttributes ) {
  43938. const programAttribute = programAttributes[ name ];
  43939. if ( programAttribute.location >= 0 ) {
  43940. const cachedAttribute = cachedAttributes[ name ];
  43941. let geometryAttribute = geometryAttributes[ name ];
  43942. if ( geometryAttribute === undefined ) {
  43943. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43944. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43945. }
  43946. if ( cachedAttribute === undefined ) return true;
  43947. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43948. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43949. attributesNum ++;
  43950. }
  43951. }
  43952. if ( currentState.attributesNum !== attributesNum ) return true;
  43953. if ( currentState.index !== index ) return true;
  43954. return false;
  43955. }
  43956. function saveCache( object, geometry, program, index ) {
  43957. const cache = {};
  43958. const attributes = geometry.attributes;
  43959. let attributesNum = 0;
  43960. const programAttributes = program.getAttributes();
  43961. for ( const name in programAttributes ) {
  43962. const programAttribute = programAttributes[ name ];
  43963. if ( programAttribute.location >= 0 ) {
  43964. let attribute = attributes[ name ];
  43965. if ( attribute === undefined ) {
  43966. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43967. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43968. }
  43969. const data = {};
  43970. data.attribute = attribute;
  43971. if ( attribute && attribute.data ) {
  43972. data.data = attribute.data;
  43973. }
  43974. cache[ name ] = data;
  43975. attributesNum ++;
  43976. }
  43977. }
  43978. currentState.attributes = cache;
  43979. currentState.attributesNum = attributesNum;
  43980. currentState.index = index;
  43981. }
  43982. function initAttributes() {
  43983. const newAttributes = currentState.newAttributes;
  43984. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43985. newAttributes[ i ] = 0;
  43986. }
  43987. }
  43988. function enableAttribute( attribute ) {
  43989. enableAttributeAndDivisor( attribute, 0 );
  43990. }
  43991. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43992. const newAttributes = currentState.newAttributes;
  43993. const enabledAttributes = currentState.enabledAttributes;
  43994. const attributeDivisors = currentState.attributeDivisors;
  43995. newAttributes[ attribute ] = 1;
  43996. if ( enabledAttributes[ attribute ] === 0 ) {
  43997. gl.enableVertexAttribArray( attribute );
  43998. enabledAttributes[ attribute ] = 1;
  43999. }
  44000. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  44001. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  44002. attributeDivisors[ attribute ] = meshPerAttribute;
  44003. }
  44004. }
  44005. function disableUnusedAttributes() {
  44006. const newAttributes = currentState.newAttributes;
  44007. const enabledAttributes = currentState.enabledAttributes;
  44008. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  44009. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  44010. gl.disableVertexAttribArray( i );
  44011. enabledAttributes[ i ] = 0;
  44012. }
  44013. }
  44014. }
  44015. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  44016. if ( integer === true ) {
  44017. gl.vertexAttribIPointer( index, size, type, stride, offset );
  44018. } else {
  44019. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  44020. }
  44021. }
  44022. function setupVertexAttributes( object, material, program, geometry ) {
  44023. initAttributes();
  44024. const geometryAttributes = geometry.attributes;
  44025. const programAttributes = program.getAttributes();
  44026. const materialDefaultAttributeValues = material.defaultAttributeValues;
  44027. for ( const name in programAttributes ) {
  44028. const programAttribute = programAttributes[ name ];
  44029. if ( programAttribute.location >= 0 ) {
  44030. let geometryAttribute = geometryAttributes[ name ];
  44031. if ( geometryAttribute === undefined ) {
  44032. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44033. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44034. }
  44035. if ( geometryAttribute !== undefined ) {
  44036. const normalized = geometryAttribute.normalized;
  44037. const size = geometryAttribute.itemSize;
  44038. const attribute = attributes.get( geometryAttribute );
  44039. // TODO Attribute may not be available on context restore
  44040. if ( attribute === undefined ) continue;
  44041. const buffer = attribute.buffer;
  44042. const type = attribute.type;
  44043. const bytesPerElement = attribute.bytesPerElement;
  44044. // check for integer attributes
  44045. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44046. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44047. const data = geometryAttribute.data;
  44048. const stride = data.stride;
  44049. const offset = geometryAttribute.offset;
  44050. if ( data.isInstancedInterleavedBuffer ) {
  44051. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44052. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44053. }
  44054. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44055. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44056. }
  44057. } else {
  44058. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44059. enableAttribute( programAttribute.location + i );
  44060. }
  44061. }
  44062. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44063. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44064. vertexAttribPointer(
  44065. programAttribute.location + i,
  44066. size / programAttribute.locationSize,
  44067. type,
  44068. normalized,
  44069. stride * bytesPerElement,
  44070. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44071. integer
  44072. );
  44073. }
  44074. } else {
  44075. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44076. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44077. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44078. }
  44079. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44080. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44081. }
  44082. } else {
  44083. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44084. enableAttribute( programAttribute.location + i );
  44085. }
  44086. }
  44087. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44088. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44089. vertexAttribPointer(
  44090. programAttribute.location + i,
  44091. size / programAttribute.locationSize,
  44092. type,
  44093. normalized,
  44094. size * bytesPerElement,
  44095. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44096. integer
  44097. );
  44098. }
  44099. }
  44100. } else if ( materialDefaultAttributeValues !== undefined ) {
  44101. const value = materialDefaultAttributeValues[ name ];
  44102. if ( value !== undefined ) {
  44103. switch ( value.length ) {
  44104. case 2:
  44105. gl.vertexAttrib2fv( programAttribute.location, value );
  44106. break;
  44107. case 3:
  44108. gl.vertexAttrib3fv( programAttribute.location, value );
  44109. break;
  44110. case 4:
  44111. gl.vertexAttrib4fv( programAttribute.location, value );
  44112. break;
  44113. default:
  44114. gl.vertexAttrib1fv( programAttribute.location, value );
  44115. }
  44116. }
  44117. }
  44118. }
  44119. }
  44120. disableUnusedAttributes();
  44121. }
  44122. function dispose() {
  44123. reset();
  44124. for ( const geometryId in bindingStates ) {
  44125. const objectMap = bindingStates[ geometryId ];
  44126. for ( const objectId in objectMap ) {
  44127. const programMap = objectMap[ objectId ];
  44128. for ( const programId in programMap ) {
  44129. const stateMap = programMap[ programId ];
  44130. for ( const wireframe in stateMap ) {
  44131. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44132. delete stateMap[ wireframe ];
  44133. }
  44134. delete programMap[ programId ];
  44135. }
  44136. }
  44137. delete bindingStates[ geometryId ];
  44138. }
  44139. }
  44140. function releaseStatesOfGeometry( geometry ) {
  44141. if ( bindingStates[ geometry.id ] === undefined ) return;
  44142. const objectMap = bindingStates[ geometry.id ];
  44143. for ( const objectId in objectMap ) {
  44144. const programMap = objectMap[ objectId ];
  44145. for ( const programId in programMap ) {
  44146. const stateMap = programMap[ programId ];
  44147. for ( const wireframe in stateMap ) {
  44148. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44149. delete stateMap[ wireframe ];
  44150. }
  44151. delete programMap[ programId ];
  44152. }
  44153. }
  44154. delete bindingStates[ geometry.id ];
  44155. }
  44156. function releaseStatesOfProgram( program ) {
  44157. for ( const geometryId in bindingStates ) {
  44158. const objectMap = bindingStates[ geometryId ];
  44159. for ( const objectId in objectMap ) {
  44160. const programMap = objectMap[ objectId ];
  44161. if ( programMap[ program.id ] === undefined ) continue;
  44162. const stateMap = programMap[ program.id ];
  44163. for ( const wireframe in stateMap ) {
  44164. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44165. delete stateMap[ wireframe ];
  44166. }
  44167. delete programMap[ program.id ];
  44168. }
  44169. }
  44170. }
  44171. function releaseStatesOfObject( object ) {
  44172. for ( const geometryId in bindingStates ) {
  44173. const objectMap = bindingStates[ geometryId ];
  44174. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44175. const programMap = objectMap[ objectId ];
  44176. if ( programMap === undefined ) continue;
  44177. for ( const programId in programMap ) {
  44178. const stateMap = programMap[ programId ];
  44179. for ( const wireframe in stateMap ) {
  44180. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44181. delete stateMap[ wireframe ];
  44182. }
  44183. delete programMap[ programId ];
  44184. }
  44185. delete objectMap[ objectId ];
  44186. if ( Object.keys( objectMap ).length === 0 ) {
  44187. delete bindingStates[ geometryId ];
  44188. }
  44189. }
  44190. }
  44191. function reset() {
  44192. resetDefaultState();
  44193. forceUpdate = true;
  44194. if ( currentState === defaultState ) return;
  44195. currentState = defaultState;
  44196. bindVertexArrayObject( currentState.object );
  44197. }
  44198. // for backward-compatibility
  44199. function resetDefaultState() {
  44200. defaultState.geometry = null;
  44201. defaultState.program = null;
  44202. defaultState.wireframe = false;
  44203. }
  44204. return {
  44205. setup: setup,
  44206. reset: reset,
  44207. resetDefaultState: resetDefaultState,
  44208. dispose: dispose,
  44209. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44210. releaseStatesOfObject: releaseStatesOfObject,
  44211. releaseStatesOfProgram: releaseStatesOfProgram,
  44212. initAttributes: initAttributes,
  44213. enableAttribute: enableAttribute,
  44214. disableUnusedAttributes: disableUnusedAttributes
  44215. };
  44216. }
  44217. function WebGLBufferRenderer( gl, extensions, info ) {
  44218. let mode;
  44219. function setMode( value ) {
  44220. mode = value;
  44221. }
  44222. function render( start, count ) {
  44223. gl.drawArrays( mode, start, count );
  44224. info.update( count, mode, 1 );
  44225. }
  44226. function renderInstances( start, count, primcount ) {
  44227. if ( primcount === 0 ) return;
  44228. gl.drawArraysInstanced( mode, start, count, primcount );
  44229. info.update( count, mode, primcount );
  44230. }
  44231. function renderMultiDraw( starts, counts, drawCount ) {
  44232. if ( drawCount === 0 ) return;
  44233. const extension = extensions.get( 'WEBGL_multi_draw' );
  44234. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44235. let elementCount = 0;
  44236. for ( let i = 0; i < drawCount; i ++ ) {
  44237. elementCount += counts[ i ];
  44238. }
  44239. info.update( elementCount, mode, 1 );
  44240. }
  44241. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44242. if ( drawCount === 0 ) return;
  44243. const extension = extensions.get( 'WEBGL_multi_draw' );
  44244. if ( extension === null ) {
  44245. for ( let i = 0; i < starts.length; i ++ ) {
  44246. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44247. }
  44248. } else {
  44249. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44250. let elementCount = 0;
  44251. for ( let i = 0; i < drawCount; i ++ ) {
  44252. elementCount += counts[ i ] * primcount[ i ];
  44253. }
  44254. info.update( elementCount, mode, 1 );
  44255. }
  44256. }
  44257. //
  44258. this.setMode = setMode;
  44259. this.render = render;
  44260. this.renderInstances = renderInstances;
  44261. this.renderMultiDraw = renderMultiDraw;
  44262. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44263. }
  44264. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44265. let maxAnisotropy;
  44266. function getMaxAnisotropy() {
  44267. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44268. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44269. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44270. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44271. } else {
  44272. maxAnisotropy = 0;
  44273. }
  44274. return maxAnisotropy;
  44275. }
  44276. function textureFormatReadable( textureFormat ) {
  44277. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44278. return false;
  44279. }
  44280. return true;
  44281. }
  44282. function textureTypeReadable( textureType ) {
  44283. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44284. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44285. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44286. return false;
  44287. }
  44288. return true;
  44289. }
  44290. function getMaxPrecision( precision ) {
  44291. if ( precision === 'highp' ) {
  44292. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44293. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44294. return 'highp';
  44295. }
  44296. precision = 'mediump';
  44297. }
  44298. if ( precision === 'mediump' ) {
  44299. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44300. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44301. return 'mediump';
  44302. }
  44303. }
  44304. return 'lowp';
  44305. }
  44306. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44307. const maxPrecision = getMaxPrecision( precision );
  44308. if ( maxPrecision !== precision ) {
  44309. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44310. precision = maxPrecision;
  44311. }
  44312. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44313. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44314. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44315. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44316. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44317. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44318. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44319. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44320. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44321. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44322. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44323. const samples = gl.getParameter( gl.SAMPLES );
  44324. return {
  44325. isWebGL2: true, // keeping this for backwards compatibility
  44326. getMaxAnisotropy: getMaxAnisotropy,
  44327. getMaxPrecision: getMaxPrecision,
  44328. textureFormatReadable: textureFormatReadable,
  44329. textureTypeReadable: textureTypeReadable,
  44330. precision: precision,
  44331. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44332. reversedDepthBuffer: reversedDepthBuffer,
  44333. maxTextures: maxTextures,
  44334. maxVertexTextures: maxVertexTextures,
  44335. maxTextureSize: maxTextureSize,
  44336. maxCubemapSize: maxCubemapSize,
  44337. maxAttributes: maxAttributes,
  44338. maxVertexUniforms: maxVertexUniforms,
  44339. maxVaryings: maxVaryings,
  44340. maxFragmentUniforms: maxFragmentUniforms,
  44341. maxSamples: maxSamples,
  44342. samples: samples
  44343. };
  44344. }
  44345. function WebGLClipping( properties ) {
  44346. const scope = this;
  44347. let globalState = null,
  44348. numGlobalPlanes = 0,
  44349. localClippingEnabled = false,
  44350. renderingShadows = false;
  44351. const plane = new Plane(),
  44352. viewNormalMatrix = new Matrix3(),
  44353. uniform = { value: null, needsUpdate: false };
  44354. this.uniform = uniform;
  44355. this.numPlanes = 0;
  44356. this.numIntersection = 0;
  44357. this.init = function ( planes, enableLocalClipping ) {
  44358. const enabled =
  44359. planes.length !== 0 ||
  44360. enableLocalClipping ||
  44361. // enable state of previous frame - the clipping code has to
  44362. // run another frame in order to reset the state:
  44363. numGlobalPlanes !== 0 ||
  44364. localClippingEnabled;
  44365. localClippingEnabled = enableLocalClipping;
  44366. numGlobalPlanes = planes.length;
  44367. return enabled;
  44368. };
  44369. this.beginShadows = function () {
  44370. renderingShadows = true;
  44371. projectPlanes( null );
  44372. };
  44373. this.endShadows = function () {
  44374. renderingShadows = false;
  44375. };
  44376. this.setGlobalState = function ( planes, camera ) {
  44377. globalState = projectPlanes( planes, camera, 0 );
  44378. };
  44379. this.setState = function ( material, camera, useCache ) {
  44380. const planes = material.clippingPlanes,
  44381. clipIntersection = material.clipIntersection,
  44382. clipShadows = material.clipShadows;
  44383. const materialProperties = properties.get( material );
  44384. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44385. // there's no local clipping
  44386. if ( renderingShadows ) {
  44387. // there's no global clipping
  44388. projectPlanes( null );
  44389. } else {
  44390. resetGlobalState();
  44391. }
  44392. } else {
  44393. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44394. lGlobal = nGlobal * 4;
  44395. let dstArray = materialProperties.clippingState || null;
  44396. uniform.value = dstArray; // ensure unique state
  44397. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44398. for ( let i = 0; i !== lGlobal; ++ i ) {
  44399. dstArray[ i ] = globalState[ i ];
  44400. }
  44401. materialProperties.clippingState = dstArray;
  44402. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44403. this.numPlanes += nGlobal;
  44404. }
  44405. };
  44406. function resetGlobalState() {
  44407. if ( uniform.value !== globalState ) {
  44408. uniform.value = globalState;
  44409. uniform.needsUpdate = numGlobalPlanes > 0;
  44410. }
  44411. scope.numPlanes = numGlobalPlanes;
  44412. scope.numIntersection = 0;
  44413. }
  44414. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44415. const nPlanes = planes !== null ? planes.length : 0;
  44416. let dstArray = null;
  44417. if ( nPlanes !== 0 ) {
  44418. dstArray = uniform.value;
  44419. if ( skipTransform !== true || dstArray === null ) {
  44420. const flatSize = dstOffset + nPlanes * 4,
  44421. viewMatrix = camera.matrixWorldInverse;
  44422. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44423. if ( dstArray === null || dstArray.length < flatSize ) {
  44424. dstArray = new Float32Array( flatSize );
  44425. }
  44426. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44427. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44428. plane.normal.toArray( dstArray, i4 );
  44429. dstArray[ i4 + 3 ] = plane.constant;
  44430. }
  44431. }
  44432. uniform.value = dstArray;
  44433. uniform.needsUpdate = true;
  44434. }
  44435. scope.numPlanes = nPlanes;
  44436. scope.numIntersection = 0;
  44437. return dstArray;
  44438. }
  44439. }
  44440. function WebGLCubeMaps( renderer ) {
  44441. let cubemaps = new WeakMap();
  44442. function mapTextureMapping( texture, mapping ) {
  44443. if ( mapping === EquirectangularReflectionMapping ) {
  44444. texture.mapping = CubeReflectionMapping;
  44445. } else if ( mapping === EquirectangularRefractionMapping ) {
  44446. texture.mapping = CubeRefractionMapping;
  44447. }
  44448. return texture;
  44449. }
  44450. function get( texture ) {
  44451. if ( texture && texture.isTexture ) {
  44452. const mapping = texture.mapping;
  44453. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44454. if ( cubemaps.has( texture ) ) {
  44455. const cubemap = cubemaps.get( texture ).texture;
  44456. return mapTextureMapping( cubemap, texture.mapping );
  44457. } else {
  44458. const image = texture.image;
  44459. if ( image && image.height > 0 ) {
  44460. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44461. renderTarget.fromEquirectangularTexture( renderer, texture );
  44462. cubemaps.set( texture, renderTarget );
  44463. texture.addEventListener( 'dispose', onTextureDispose );
  44464. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44465. } else {
  44466. // image not yet ready. try the conversion next frame
  44467. return null;
  44468. }
  44469. }
  44470. }
  44471. }
  44472. return texture;
  44473. }
  44474. function onTextureDispose( event ) {
  44475. const texture = event.target;
  44476. texture.removeEventListener( 'dispose', onTextureDispose );
  44477. const cubemap = cubemaps.get( texture );
  44478. if ( cubemap !== undefined ) {
  44479. cubemaps.delete( texture );
  44480. cubemap.dispose();
  44481. }
  44482. }
  44483. function dispose() {
  44484. cubemaps = new WeakMap();
  44485. }
  44486. return {
  44487. get: get,
  44488. dispose: dispose
  44489. };
  44490. }
  44491. const LOD_MIN = 4;
  44492. // The standard deviations (radians) associated with the extra mips.
  44493. // Used for scene blur in fromScene() method.
  44494. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44495. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44496. // samples and exit early, but not recompile the shader.
  44497. // Used for scene blur in fromScene() method.
  44498. const MAX_SAMPLES = 20;
  44499. // GGX VNDF importance sampling configuration
  44500. const GGX_SAMPLES = 256;
  44501. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44502. const _clearColor = /*@__PURE__*/ new Color();
  44503. let _oldTarget = null;
  44504. let _oldActiveCubeFace = 0;
  44505. let _oldActiveMipmapLevel = 0;
  44506. let _oldXrEnabled = false;
  44507. const _origin = /*@__PURE__*/ new Vector3();
  44508. /**
  44509. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44510. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44511. * blur to be quickly accessed based on material roughness. It is packed into a
  44512. * special CubeUV format that allows us to perform custom interpolation so that
  44513. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44514. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44515. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44516. * higher roughness levels. In this way we maintain resolution to smoothly
  44517. * interpolate diffuse lighting while limiting sampling computation.
  44518. *
  44519. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44520. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44521. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44522. * used in material rendering for physically-based image-based lighting.
  44523. */
  44524. class PMREMGenerator {
  44525. /**
  44526. * Constructs a new PMREM generator.
  44527. *
  44528. * @param {WebGLRenderer} renderer - The renderer.
  44529. */
  44530. constructor( renderer ) {
  44531. this._renderer = renderer;
  44532. this._pingPongRenderTarget = null;
  44533. this._lodMax = 0;
  44534. this._cubeSize = 0;
  44535. this._sizeLods = [];
  44536. this._sigmas = [];
  44537. this._lodMeshes = [];
  44538. this._backgroundBox = null;
  44539. this._cubemapMaterial = null;
  44540. this._equirectMaterial = null;
  44541. this._blurMaterial = null;
  44542. this._ggxMaterial = null;
  44543. }
  44544. /**
  44545. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44546. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44547. * in radians to be applied to the scene before PMREM generation. Optional near
  44548. * and far planes ensure the scene is rendered in its entirety.
  44549. *
  44550. * @param {Scene} scene - The scene to be captured.
  44551. * @param {number} [sigma=0] - The blur radius in radians.
  44552. * @param {number} [near=0.1] - The near plane distance.
  44553. * @param {number} [far=100] - The far plane distance.
  44554. * @param {Object} [options={}] - The configuration options.
  44555. * @param {number} [options.size=256] - The texture size of the PMREM.
  44556. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44557. * @return {WebGLRenderTarget} The resulting PMREM.
  44558. */
  44559. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44560. const {
  44561. size = 256,
  44562. position = _origin,
  44563. } = options;
  44564. _oldTarget = this._renderer.getRenderTarget();
  44565. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44566. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44567. _oldXrEnabled = this._renderer.xr.enabled;
  44568. this._renderer.xr.enabled = false;
  44569. this._setSize( size );
  44570. const cubeUVRenderTarget = this._allocateTargets();
  44571. cubeUVRenderTarget.depthBuffer = true;
  44572. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44573. if ( sigma > 0 ) {
  44574. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44575. }
  44576. this._applyPMREM( cubeUVRenderTarget );
  44577. this._cleanup( cubeUVRenderTarget );
  44578. return cubeUVRenderTarget;
  44579. }
  44580. /**
  44581. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44582. * or HDR. The ideal input image size is 1k (1024 x 512),
  44583. * as this matches best with the 256 x 256 cubemap output.
  44584. *
  44585. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44586. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44587. * @return {WebGLRenderTarget} The resulting PMREM.
  44588. */
  44589. fromEquirectangular( equirectangular, renderTarget = null ) {
  44590. return this._fromTexture( equirectangular, renderTarget );
  44591. }
  44592. /**
  44593. * Generates a PMREM from an cubemap texture, which can be either LDR
  44594. * or HDR. The ideal input cube size is 256 x 256,
  44595. * as this matches best with the 256 x 256 cubemap output.
  44596. *
  44597. * @param {Texture} cubemap - The cubemap texture to be converted.
  44598. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44599. * @return {WebGLRenderTarget} The resulting PMREM.
  44600. */
  44601. fromCubemap( cubemap, renderTarget = null ) {
  44602. return this._fromTexture( cubemap, renderTarget );
  44603. }
  44604. /**
  44605. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44606. * your texture's network fetch for increased concurrency.
  44607. */
  44608. compileCubemapShader() {
  44609. if ( this._cubemapMaterial === null ) {
  44610. this._cubemapMaterial = _getCubemapMaterial();
  44611. this._compileMaterial( this._cubemapMaterial );
  44612. }
  44613. }
  44614. /**
  44615. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44616. * your texture's network fetch for increased concurrency.
  44617. */
  44618. compileEquirectangularShader() {
  44619. if ( this._equirectMaterial === null ) {
  44620. this._equirectMaterial = _getEquirectMaterial();
  44621. this._compileMaterial( this._equirectMaterial );
  44622. }
  44623. }
  44624. /**
  44625. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44626. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44627. * one of them will cause any others to also become unusable.
  44628. */
  44629. dispose() {
  44630. this._dispose();
  44631. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44632. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44633. if ( this._backgroundBox !== null ) {
  44634. this._backgroundBox.geometry.dispose();
  44635. this._backgroundBox.material.dispose();
  44636. }
  44637. }
  44638. // private interface
  44639. _setSize( cubeSize ) {
  44640. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44641. this._cubeSize = Math.pow( 2, this._lodMax );
  44642. }
  44643. _dispose() {
  44644. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44645. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44646. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44647. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44648. this._lodMeshes[ i ].geometry.dispose();
  44649. }
  44650. }
  44651. _cleanup( outputTarget ) {
  44652. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44653. this._renderer.xr.enabled = _oldXrEnabled;
  44654. outputTarget.scissorTest = false;
  44655. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44656. }
  44657. _fromTexture( texture, renderTarget ) {
  44658. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44659. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44660. } else { // Equirectangular
  44661. this._setSize( texture.image.width / 4 );
  44662. }
  44663. _oldTarget = this._renderer.getRenderTarget();
  44664. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44665. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44666. _oldXrEnabled = this._renderer.xr.enabled;
  44667. this._renderer.xr.enabled = false;
  44668. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44669. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44670. this._applyPMREM( cubeUVRenderTarget );
  44671. this._cleanup( cubeUVRenderTarget );
  44672. return cubeUVRenderTarget;
  44673. }
  44674. _allocateTargets() {
  44675. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44676. const height = 4 * this._cubeSize;
  44677. const params = {
  44678. magFilter: LinearFilter,
  44679. minFilter: LinearFilter,
  44680. generateMipmaps: false,
  44681. type: HalfFloatType,
  44682. format: RGBAFormat,
  44683. colorSpace: LinearSRGBColorSpace,
  44684. depthBuffer: false
  44685. };
  44686. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44687. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44688. if ( this._pingPongRenderTarget !== null ) {
  44689. this._dispose();
  44690. }
  44691. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44692. const { _lodMax } = this;
  44693. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44694. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44695. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  44696. }
  44697. return cubeUVRenderTarget;
  44698. }
  44699. _compileMaterial( material ) {
  44700. const mesh = new Mesh( new BufferGeometry(), material );
  44701. this._renderer.compile( mesh, _flatCamera );
  44702. }
  44703. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44704. const fov = 90;
  44705. const aspect = 1;
  44706. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44707. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44708. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44709. const renderer = this._renderer;
  44710. const originalAutoClear = renderer.autoClear;
  44711. const toneMapping = renderer.toneMapping;
  44712. renderer.getClearColor( _clearColor );
  44713. renderer.toneMapping = NoToneMapping;
  44714. renderer.autoClear = false;
  44715. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44716. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44717. if ( reversedDepthBuffer ) {
  44718. renderer.setRenderTarget( cubeUVRenderTarget );
  44719. renderer.clearDepth();
  44720. renderer.setRenderTarget( null );
  44721. }
  44722. if ( this._backgroundBox === null ) {
  44723. this._backgroundBox = new Mesh(
  44724. new BoxGeometry(),
  44725. new MeshBasicMaterial( {
  44726. name: 'PMREM.Background',
  44727. side: BackSide,
  44728. depthWrite: false,
  44729. depthTest: false,
  44730. } )
  44731. );
  44732. }
  44733. const backgroundBox = this._backgroundBox;
  44734. const backgroundMaterial = backgroundBox.material;
  44735. let useSolidColor = false;
  44736. const background = scene.background;
  44737. if ( background ) {
  44738. if ( background.isColor ) {
  44739. backgroundMaterial.color.copy( background );
  44740. scene.background = null;
  44741. useSolidColor = true;
  44742. }
  44743. } else {
  44744. backgroundMaterial.color.copy( _clearColor );
  44745. useSolidColor = true;
  44746. }
  44747. for ( let i = 0; i < 6; i ++ ) {
  44748. const col = i % 3;
  44749. if ( col === 0 ) {
  44750. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44751. cubeCamera.position.set( position.x, position.y, position.z );
  44752. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44753. } else if ( col === 1 ) {
  44754. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44755. cubeCamera.position.set( position.x, position.y, position.z );
  44756. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44757. } else {
  44758. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44759. cubeCamera.position.set( position.x, position.y, position.z );
  44760. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44761. }
  44762. const size = this._cubeSize;
  44763. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44764. renderer.setRenderTarget( cubeUVRenderTarget );
  44765. if ( useSolidColor ) {
  44766. renderer.render( backgroundBox, cubeCamera );
  44767. }
  44768. renderer.render( scene, cubeCamera );
  44769. }
  44770. renderer.toneMapping = toneMapping;
  44771. renderer.autoClear = originalAutoClear;
  44772. scene.background = background;
  44773. }
  44774. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44775. const renderer = this._renderer;
  44776. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44777. if ( isCubeTexture ) {
  44778. if ( this._cubemapMaterial === null ) {
  44779. this._cubemapMaterial = _getCubemapMaterial();
  44780. }
  44781. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44782. } else {
  44783. if ( this._equirectMaterial === null ) {
  44784. this._equirectMaterial = _getEquirectMaterial();
  44785. }
  44786. }
  44787. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44788. const mesh = this._lodMeshes[ 0 ];
  44789. mesh.material = material;
  44790. const uniforms = material.uniforms;
  44791. uniforms[ 'envMap' ].value = texture;
  44792. const size = this._cubeSize;
  44793. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44794. renderer.setRenderTarget( cubeUVRenderTarget );
  44795. renderer.render( mesh, _flatCamera );
  44796. }
  44797. _applyPMREM( cubeUVRenderTarget ) {
  44798. const renderer = this._renderer;
  44799. const autoClear = renderer.autoClear;
  44800. renderer.autoClear = false;
  44801. const n = this._lodMeshes.length;
  44802. // Use GGX VNDF importance sampling
  44803. for ( let i = 1; i < n; i ++ ) {
  44804. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  44805. }
  44806. renderer.autoClear = autoClear;
  44807. }
  44808. /**
  44809. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  44810. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  44811. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  44812. * applies incremental roughness filtering to avoid over-blurring.
  44813. *
  44814. * @private
  44815. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44816. * @param {number} lodIn - Source LOD level to read from
  44817. * @param {number} lodOut - Target LOD level to write to
  44818. */
  44819. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  44820. const renderer = this._renderer;
  44821. const pingPongRenderTarget = this._pingPongRenderTarget;
  44822. const ggxMaterial = this._ggxMaterial;
  44823. const ggxMesh = this._lodMeshes[ lodOut ];
  44824. ggxMesh.material = ggxMaterial;
  44825. const ggxUniforms = ggxMaterial.uniforms;
  44826. // Calculate incremental roughness between LOD levels
  44827. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  44828. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  44829. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  44830. // Apply blur strength mapping for better quality across the roughness range
  44831. const blurStrength = 0.0 + targetRoughness * 1.25;
  44832. const adjustedRoughness = incrementalRoughness * blurStrength;
  44833. // Calculate viewport position based on output LOD level
  44834. const { _lodMax } = this;
  44835. const outputSize = this._sizeLods[ lodOut ];
  44836. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44837. const y = 4 * ( this._cubeSize - outputSize );
  44838. // Read from previous LOD with incremental roughness
  44839. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  44840. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  44841. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  44842. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44843. renderer.setRenderTarget( pingPongRenderTarget );
  44844. renderer.render( ggxMesh, _flatCamera );
  44845. // Copy from pingPong back to cubeUV (simple direct copy)
  44846. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  44847. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  44848. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  44849. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44850. renderer.setRenderTarget( cubeUVRenderTarget );
  44851. renderer.render( ggxMesh, _flatCamera );
  44852. }
  44853. /**
  44854. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44855. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44856. * the blur latitudinally (around the poles), and then longitudinally (towards
  44857. * the poles) to approximate the orthogonally-separable blur. It is least
  44858. * accurate at the poles, but still does a decent job.
  44859. *
  44860. * Used for initial scene blur in fromScene() method when sigma > 0.
  44861. *
  44862. * @private
  44863. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44864. * @param {number} lodIn
  44865. * @param {number} lodOut
  44866. * @param {number} sigma
  44867. * @param {Vector3} [poleAxis]
  44868. */
  44869. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44870. const pingPongRenderTarget = this._pingPongRenderTarget;
  44871. this._halfBlur(
  44872. cubeUVRenderTarget,
  44873. pingPongRenderTarget,
  44874. lodIn,
  44875. lodOut,
  44876. sigma,
  44877. 'latitudinal',
  44878. poleAxis );
  44879. this._halfBlur(
  44880. pingPongRenderTarget,
  44881. cubeUVRenderTarget,
  44882. lodOut,
  44883. lodOut,
  44884. sigma,
  44885. 'longitudinal',
  44886. poleAxis );
  44887. }
  44888. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44889. const renderer = this._renderer;
  44890. const blurMaterial = this._blurMaterial;
  44891. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44892. error(
  44893. 'blur direction must be either latitudinal or longitudinal!' );
  44894. }
  44895. // Number of standard deviations at which to cut off the discrete approximation.
  44896. const STANDARD_DEVIATIONS = 3;
  44897. const blurMesh = this._lodMeshes[ lodOut ];
  44898. blurMesh.material = blurMaterial;
  44899. const blurUniforms = blurMaterial.uniforms;
  44900. const pixels = this._sizeLods[ lodIn ] - 1;
  44901. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44902. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44903. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44904. if ( samples > MAX_SAMPLES ) {
  44905. warn( `sigmaRadians, ${
  44906. sigmaRadians}, is too large and will clip, as it requested ${
  44907. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44908. }
  44909. const weights = [];
  44910. let sum = 0;
  44911. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44912. const x = i / sigmaPixels;
  44913. const weight = Math.exp( - x * x / 2 );
  44914. weights.push( weight );
  44915. if ( i === 0 ) {
  44916. sum += weight;
  44917. } else if ( i < samples ) {
  44918. sum += 2 * weight;
  44919. }
  44920. }
  44921. for ( let i = 0; i < weights.length; i ++ ) {
  44922. weights[ i ] = weights[ i ] / sum;
  44923. }
  44924. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44925. blurUniforms[ 'samples' ].value = samples;
  44926. blurUniforms[ 'weights' ].value = weights;
  44927. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44928. if ( poleAxis ) {
  44929. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44930. }
  44931. const { _lodMax } = this;
  44932. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44933. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44934. const outputSize = this._sizeLods[ lodOut ];
  44935. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44936. const y = 4 * ( this._cubeSize - outputSize );
  44937. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44938. renderer.setRenderTarget( targetOut );
  44939. renderer.render( blurMesh, _flatCamera );
  44940. }
  44941. }
  44942. function _createPlanes( lodMax ) {
  44943. const sizeLods = [];
  44944. const sigmas = [];
  44945. const lodMeshes = [];
  44946. let lod = lodMax;
  44947. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44948. for ( let i = 0; i < totalLods; i ++ ) {
  44949. const sizeLod = Math.pow( 2, lod );
  44950. sizeLods.push( sizeLod );
  44951. let sigma = 1.0 / sizeLod;
  44952. if ( i > lodMax - LOD_MIN ) {
  44953. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44954. } else if ( i === 0 ) {
  44955. sigma = 0;
  44956. }
  44957. sigmas.push( sigma );
  44958. const texelSize = 1.0 / ( sizeLod - 2 );
  44959. const min = - texelSize;
  44960. const max = 1 + texelSize;
  44961. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44962. const cubeFaces = 6;
  44963. const vertices = 6;
  44964. const positionSize = 3;
  44965. const uvSize = 2;
  44966. const faceIndexSize = 1;
  44967. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44968. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44969. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44970. for ( let face = 0; face < cubeFaces; face ++ ) {
  44971. const x = ( face % 3 ) * 2 / 3 - 1;
  44972. const y = face > 2 ? 0 : -1;
  44973. const coordinates = [
  44974. x, y, 0,
  44975. x + 2 / 3, y, 0,
  44976. x + 2 / 3, y + 1, 0,
  44977. x, y, 0,
  44978. x + 2 / 3, y + 1, 0,
  44979. x, y + 1, 0
  44980. ];
  44981. position.set( coordinates, positionSize * vertices * face );
  44982. uv.set( uv1, uvSize * vertices * face );
  44983. const fill = [ face, face, face, face, face, face ];
  44984. faceIndex.set( fill, faceIndexSize * vertices * face );
  44985. }
  44986. const planes = new BufferGeometry();
  44987. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44988. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44989. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44990. lodMeshes.push( new Mesh( planes, null ) );
  44991. if ( lod > LOD_MIN ) {
  44992. lod --;
  44993. }
  44994. }
  44995. return { lodMeshes, sizeLods, sigmas };
  44996. }
  44997. function _createRenderTarget( width, height, params ) {
  44998. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44999. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  45000. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  45001. cubeUVRenderTarget.scissorTest = true;
  45002. return cubeUVRenderTarget;
  45003. }
  45004. function _setViewport( target, x, y, width, height ) {
  45005. target.viewport.set( x, y, width, height );
  45006. target.scissor.set( x, y, width, height );
  45007. }
  45008. function _getGGXShader( lodMax, width, height ) {
  45009. const shaderMaterial = new ShaderMaterial( {
  45010. name: 'PMREMGGXConvolution',
  45011. defines: {
  45012. 'GGX_SAMPLES': GGX_SAMPLES,
  45013. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45014. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45015. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45016. },
  45017. uniforms: {
  45018. 'envMap': { value: null },
  45019. 'roughness': { value: 0.0 },
  45020. 'mipInt': { value: 0 }
  45021. },
  45022. vertexShader: _getCommonVertexShader(),
  45023. fragmentShader: /* glsl */`
  45024. precision highp float;
  45025. precision highp int;
  45026. varying vec3 vOutputDirection;
  45027. uniform sampler2D envMap;
  45028. uniform float roughness;
  45029. uniform float mipInt;
  45030. #define ENVMAP_TYPE_CUBE_UV
  45031. #include <cube_uv_reflection_fragment>
  45032. #define PI 3.14159265359
  45033. // Van der Corput radical inverse
  45034. float radicalInverse_VdC(uint bits) {
  45035. bits = (bits << 16u) | (bits >> 16u);
  45036. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  45037. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  45038. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  45039. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  45040. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  45041. }
  45042. // Hammersley sequence
  45043. vec2 hammersley(uint i, uint N) {
  45044. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  45045. }
  45046. // GGX VNDF importance sampling (Eric Heitz 2018)
  45047. // "Sampling the GGX Distribution of Visible Normals"
  45048. // https://jcgt.org/published/0007/04/01/
  45049. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  45050. float alpha = roughness * roughness;
  45051. // Section 3.2: Transform view direction to hemisphere configuration
  45052. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  45053. // Section 4.1: Orthonormal basis
  45054. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  45055. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  45056. vec3 T2 = cross(Vh, T1);
  45057. // Section 4.2: Parameterization of projected area
  45058. float r = sqrt(Xi.x);
  45059. float phi = 2.0 * PI * Xi.y;
  45060. float t1 = r * cos(phi);
  45061. float t2 = r * sin(phi);
  45062. float s = 0.5 * (1.0 + Vh.z);
  45063. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45064. // Section 4.3: Reprojection onto hemisphere
  45065. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  45066. // Section 3.4: Transform back to ellipsoid configuration
  45067. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45068. }
  45069. void main() {
  45070. vec3 N = normalize(vOutputDirection);
  45071. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45072. vec3 prefilteredColor = vec3(0.0);
  45073. float totalWeight = 0.0;
  45074. // For very low roughness, just sample the environment directly
  45075. if (roughness < 0.001) {
  45076. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45077. return;
  45078. }
  45079. // Tangent space basis for VNDF sampling
  45080. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45081. vec3 tangent = normalize(cross(up, N));
  45082. vec3 bitangent = cross(N, tangent);
  45083. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45084. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45085. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45086. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45087. // Transform H back to world space
  45088. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45089. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45090. float NdotL = max(dot(N, L), 0.0);
  45091. if(NdotL > 0.0) {
  45092. // Sample environment at fixed mip level
  45093. // VNDF importance sampling handles the distribution filtering
  45094. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45095. // Weight by NdotL for the split-sum approximation
  45096. // VNDF PDF naturally accounts for the visible microfacet distribution
  45097. prefilteredColor += sampleColor * NdotL;
  45098. totalWeight += NdotL;
  45099. }
  45100. }
  45101. if (totalWeight > 0.0) {
  45102. prefilteredColor = prefilteredColor / totalWeight;
  45103. }
  45104. gl_FragColor = vec4(prefilteredColor, 1.0);
  45105. }
  45106. `,
  45107. blending: NoBlending,
  45108. depthTest: false,
  45109. depthWrite: false
  45110. } );
  45111. return shaderMaterial;
  45112. }
  45113. function _getBlurShader( lodMax, width, height ) {
  45114. const weights = new Float32Array( MAX_SAMPLES );
  45115. const poleAxis = new Vector3( 0, 1, 0 );
  45116. const shaderMaterial = new ShaderMaterial( {
  45117. name: 'SphericalGaussianBlur',
  45118. defines: {
  45119. 'n': MAX_SAMPLES,
  45120. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45121. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45122. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45123. },
  45124. uniforms: {
  45125. 'envMap': { value: null },
  45126. 'samples': { value: 1 },
  45127. 'weights': { value: weights },
  45128. 'latitudinal': { value: false },
  45129. 'dTheta': { value: 0 },
  45130. 'mipInt': { value: 0 },
  45131. 'poleAxis': { value: poleAxis }
  45132. },
  45133. vertexShader: _getCommonVertexShader(),
  45134. fragmentShader: /* glsl */`
  45135. precision mediump float;
  45136. precision mediump int;
  45137. varying vec3 vOutputDirection;
  45138. uniform sampler2D envMap;
  45139. uniform int samples;
  45140. uniform float weights[ n ];
  45141. uniform bool latitudinal;
  45142. uniform float dTheta;
  45143. uniform float mipInt;
  45144. uniform vec3 poleAxis;
  45145. #define ENVMAP_TYPE_CUBE_UV
  45146. #include <cube_uv_reflection_fragment>
  45147. vec3 getSample( float theta, vec3 axis ) {
  45148. float cosTheta = cos( theta );
  45149. // Rodrigues' axis-angle rotation
  45150. vec3 sampleDirection = vOutputDirection * cosTheta
  45151. + cross( axis, vOutputDirection ) * sin( theta )
  45152. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45153. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45154. }
  45155. void main() {
  45156. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45157. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45158. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45159. }
  45160. axis = normalize( axis );
  45161. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45162. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45163. for ( int i = 1; i < n; i++ ) {
  45164. if ( i >= samples ) {
  45165. break;
  45166. }
  45167. float theta = dTheta * float( i );
  45168. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45169. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45170. }
  45171. }
  45172. `,
  45173. blending: NoBlending,
  45174. depthTest: false,
  45175. depthWrite: false
  45176. } );
  45177. return shaderMaterial;
  45178. }
  45179. function _getEquirectMaterial() {
  45180. return new ShaderMaterial( {
  45181. name: 'EquirectangularToCubeUV',
  45182. uniforms: {
  45183. 'envMap': { value: null }
  45184. },
  45185. vertexShader: _getCommonVertexShader(),
  45186. fragmentShader: /* glsl */`
  45187. precision mediump float;
  45188. precision mediump int;
  45189. varying vec3 vOutputDirection;
  45190. uniform sampler2D envMap;
  45191. #include <common>
  45192. void main() {
  45193. vec3 outputDirection = normalize( vOutputDirection );
  45194. vec2 uv = equirectUv( outputDirection );
  45195. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45196. }
  45197. `,
  45198. blending: NoBlending,
  45199. depthTest: false,
  45200. depthWrite: false
  45201. } );
  45202. }
  45203. function _getCubemapMaterial() {
  45204. return new ShaderMaterial( {
  45205. name: 'CubemapToCubeUV',
  45206. uniforms: {
  45207. 'envMap': { value: null },
  45208. 'flipEnvMap': { value: -1 }
  45209. },
  45210. vertexShader: _getCommonVertexShader(),
  45211. fragmentShader: /* glsl */`
  45212. precision mediump float;
  45213. precision mediump int;
  45214. uniform float flipEnvMap;
  45215. varying vec3 vOutputDirection;
  45216. uniform samplerCube envMap;
  45217. void main() {
  45218. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45219. }
  45220. `,
  45221. blending: NoBlending,
  45222. depthTest: false,
  45223. depthWrite: false
  45224. } );
  45225. }
  45226. function _getCommonVertexShader() {
  45227. return /* glsl */`
  45228. precision mediump float;
  45229. precision mediump int;
  45230. attribute float faceIndex;
  45231. varying vec3 vOutputDirection;
  45232. // RH coordinate system; PMREM face-indexing convention
  45233. vec3 getDirection( vec2 uv, float face ) {
  45234. uv = 2.0 * uv - 1.0;
  45235. vec3 direction = vec3( uv, 1.0 );
  45236. if ( face == 0.0 ) {
  45237. direction = direction.zyx; // ( 1, v, u ) pos x
  45238. } else if ( face == 1.0 ) {
  45239. direction = direction.xzy;
  45240. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45241. } else if ( face == 2.0 ) {
  45242. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45243. } else if ( face == 3.0 ) {
  45244. direction = direction.zyx;
  45245. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45246. } else if ( face == 4.0 ) {
  45247. direction = direction.xzy;
  45248. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45249. } else if ( face == 5.0 ) {
  45250. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45251. }
  45252. return direction;
  45253. }
  45254. void main() {
  45255. vOutputDirection = getDirection( uv, faceIndex );
  45256. gl_Position = vec4( position, 1.0 );
  45257. }
  45258. `;
  45259. }
  45260. function WebGLCubeUVMaps( renderer ) {
  45261. let cubeUVmaps = new WeakMap();
  45262. let pmremGenerator = null;
  45263. function get( texture ) {
  45264. if ( texture && texture.isTexture ) {
  45265. const mapping = texture.mapping;
  45266. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45267. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45268. // equirect/cube map to cubeUV conversion
  45269. if ( isEquirectMap || isCubeMap ) {
  45270. let renderTarget = cubeUVmaps.get( texture );
  45271. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45272. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45273. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45274. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45275. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45276. cubeUVmaps.set( texture, renderTarget );
  45277. return renderTarget.texture;
  45278. } else {
  45279. if ( renderTarget !== undefined ) {
  45280. return renderTarget.texture;
  45281. } else {
  45282. const image = texture.image;
  45283. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45284. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45285. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45286. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45287. cubeUVmaps.set( texture, renderTarget );
  45288. texture.addEventListener( 'dispose', onTextureDispose );
  45289. return renderTarget.texture;
  45290. } else {
  45291. // image not yet ready. try the conversion next frame
  45292. return null;
  45293. }
  45294. }
  45295. }
  45296. }
  45297. }
  45298. return texture;
  45299. }
  45300. function isCubeTextureComplete( image ) {
  45301. let count = 0;
  45302. const length = 6;
  45303. for ( let i = 0; i < length; i ++ ) {
  45304. if ( image[ i ] !== undefined ) count ++;
  45305. }
  45306. return count === length;
  45307. }
  45308. function onTextureDispose( event ) {
  45309. const texture = event.target;
  45310. texture.removeEventListener( 'dispose', onTextureDispose );
  45311. const cubemapUV = cubeUVmaps.get( texture );
  45312. if ( cubemapUV !== undefined ) {
  45313. cubeUVmaps.delete( texture );
  45314. cubemapUV.dispose();
  45315. }
  45316. }
  45317. function dispose() {
  45318. cubeUVmaps = new WeakMap();
  45319. if ( pmremGenerator !== null ) {
  45320. pmremGenerator.dispose();
  45321. pmremGenerator = null;
  45322. }
  45323. }
  45324. return {
  45325. get: get,
  45326. dispose: dispose
  45327. };
  45328. }
  45329. function WebGLExtensions( gl ) {
  45330. const extensions = {};
  45331. function getExtension( name ) {
  45332. if ( extensions[ name ] !== undefined ) {
  45333. return extensions[ name ];
  45334. }
  45335. const extension = gl.getExtension( name );
  45336. extensions[ name ] = extension;
  45337. return extension;
  45338. }
  45339. return {
  45340. has: function ( name ) {
  45341. return getExtension( name ) !== null;
  45342. },
  45343. init: function () {
  45344. getExtension( 'EXT_color_buffer_float' );
  45345. getExtension( 'WEBGL_clip_cull_distance' );
  45346. getExtension( 'OES_texture_float_linear' );
  45347. getExtension( 'EXT_color_buffer_half_float' );
  45348. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45349. getExtension( 'WEBGL_render_shared_exponent' );
  45350. },
  45351. get: function ( name ) {
  45352. const extension = getExtension( name );
  45353. if ( extension === null ) {
  45354. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45355. }
  45356. return extension;
  45357. }
  45358. };
  45359. }
  45360. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45361. const geometries = {};
  45362. const wireframeAttributes = new WeakMap();
  45363. function onGeometryDispose( event ) {
  45364. const geometry = event.target;
  45365. if ( geometry.index !== null ) {
  45366. attributes.remove( geometry.index );
  45367. }
  45368. for ( const name in geometry.attributes ) {
  45369. attributes.remove( geometry.attributes[ name ] );
  45370. }
  45371. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45372. delete geometries[ geometry.id ];
  45373. const attribute = wireframeAttributes.get( geometry );
  45374. if ( attribute ) {
  45375. attributes.remove( attribute );
  45376. wireframeAttributes.delete( geometry );
  45377. }
  45378. bindingStates.releaseStatesOfGeometry( geometry );
  45379. if ( geometry.isInstancedBufferGeometry === true ) {
  45380. delete geometry._maxInstanceCount;
  45381. }
  45382. //
  45383. info.memory.geometries --;
  45384. }
  45385. function get( object, geometry ) {
  45386. if ( geometries[ geometry.id ] === true ) return geometry;
  45387. geometry.addEventListener( 'dispose', onGeometryDispose );
  45388. geometries[ geometry.id ] = true;
  45389. info.memory.geometries ++;
  45390. return geometry;
  45391. }
  45392. function update( geometry ) {
  45393. const geometryAttributes = geometry.attributes;
  45394. // Updating index buffer in VAO now. See WebGLBindingStates.
  45395. for ( const name in geometryAttributes ) {
  45396. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45397. }
  45398. }
  45399. function updateWireframeAttribute( geometry ) {
  45400. const indices = [];
  45401. const geometryIndex = geometry.index;
  45402. const geometryPosition = geometry.attributes.position;
  45403. let version = 0;
  45404. if ( geometryIndex !== null ) {
  45405. const array = geometryIndex.array;
  45406. version = geometryIndex.version;
  45407. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45408. const a = array[ i + 0 ];
  45409. const b = array[ i + 1 ];
  45410. const c = array[ i + 2 ];
  45411. indices.push( a, b, b, c, c, a );
  45412. }
  45413. } else if ( geometryPosition !== undefined ) {
  45414. const array = geometryPosition.array;
  45415. version = geometryPosition.version;
  45416. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45417. const a = i + 0;
  45418. const b = i + 1;
  45419. const c = i + 2;
  45420. indices.push( a, b, b, c, c, a );
  45421. }
  45422. } else {
  45423. return;
  45424. }
  45425. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45426. attribute.version = version;
  45427. // Updating index buffer in VAO now. See WebGLBindingStates
  45428. //
  45429. const previousAttribute = wireframeAttributes.get( geometry );
  45430. if ( previousAttribute ) attributes.remove( previousAttribute );
  45431. //
  45432. wireframeAttributes.set( geometry, attribute );
  45433. }
  45434. function getWireframeAttribute( geometry ) {
  45435. const currentAttribute = wireframeAttributes.get( geometry );
  45436. if ( currentAttribute ) {
  45437. const geometryIndex = geometry.index;
  45438. if ( geometryIndex !== null ) {
  45439. // if the attribute is obsolete, create a new one
  45440. if ( currentAttribute.version < geometryIndex.version ) {
  45441. updateWireframeAttribute( geometry );
  45442. }
  45443. }
  45444. } else {
  45445. updateWireframeAttribute( geometry );
  45446. }
  45447. return wireframeAttributes.get( geometry );
  45448. }
  45449. return {
  45450. get: get,
  45451. update: update,
  45452. getWireframeAttribute: getWireframeAttribute
  45453. };
  45454. }
  45455. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45456. let mode;
  45457. function setMode( value ) {
  45458. mode = value;
  45459. }
  45460. let type, bytesPerElement;
  45461. function setIndex( value ) {
  45462. type = value.type;
  45463. bytesPerElement = value.bytesPerElement;
  45464. }
  45465. function render( start, count ) {
  45466. gl.drawElements( mode, count, type, start * bytesPerElement );
  45467. info.update( count, mode, 1 );
  45468. }
  45469. function renderInstances( start, count, primcount ) {
  45470. if ( primcount === 0 ) return;
  45471. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45472. info.update( count, mode, primcount );
  45473. }
  45474. function renderMultiDraw( starts, counts, drawCount ) {
  45475. if ( drawCount === 0 ) return;
  45476. const extension = extensions.get( 'WEBGL_multi_draw' );
  45477. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45478. let elementCount = 0;
  45479. for ( let i = 0; i < drawCount; i ++ ) {
  45480. elementCount += counts[ i ];
  45481. }
  45482. info.update( elementCount, mode, 1 );
  45483. }
  45484. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45485. if ( drawCount === 0 ) return;
  45486. const extension = extensions.get( 'WEBGL_multi_draw' );
  45487. if ( extension === null ) {
  45488. for ( let i = 0; i < starts.length; i ++ ) {
  45489. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45490. }
  45491. } else {
  45492. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45493. let elementCount = 0;
  45494. for ( let i = 0; i < drawCount; i ++ ) {
  45495. elementCount += counts[ i ] * primcount[ i ];
  45496. }
  45497. info.update( elementCount, mode, 1 );
  45498. }
  45499. }
  45500. //
  45501. this.setMode = setMode;
  45502. this.setIndex = setIndex;
  45503. this.render = render;
  45504. this.renderInstances = renderInstances;
  45505. this.renderMultiDraw = renderMultiDraw;
  45506. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45507. }
  45508. function WebGLInfo( gl ) {
  45509. const memory = {
  45510. geometries: 0,
  45511. textures: 0
  45512. };
  45513. const render = {
  45514. frame: 0,
  45515. calls: 0,
  45516. triangles: 0,
  45517. points: 0,
  45518. lines: 0
  45519. };
  45520. function update( count, mode, instanceCount ) {
  45521. render.calls ++;
  45522. switch ( mode ) {
  45523. case gl.TRIANGLES:
  45524. render.triangles += instanceCount * ( count / 3 );
  45525. break;
  45526. case gl.LINES:
  45527. render.lines += instanceCount * ( count / 2 );
  45528. break;
  45529. case gl.LINE_STRIP:
  45530. render.lines += instanceCount * ( count - 1 );
  45531. break;
  45532. case gl.LINE_LOOP:
  45533. render.lines += instanceCount * count;
  45534. break;
  45535. case gl.POINTS:
  45536. render.points += instanceCount * count;
  45537. break;
  45538. default:
  45539. error( 'WebGLInfo: Unknown draw mode:', mode );
  45540. break;
  45541. }
  45542. }
  45543. function reset() {
  45544. render.calls = 0;
  45545. render.triangles = 0;
  45546. render.points = 0;
  45547. render.lines = 0;
  45548. }
  45549. return {
  45550. memory: memory,
  45551. render: render,
  45552. programs: null,
  45553. autoReset: true,
  45554. reset: reset,
  45555. update: update
  45556. };
  45557. }
  45558. function WebGLMorphtargets( gl, capabilities, textures ) {
  45559. const morphTextures = new WeakMap();
  45560. const morph = new Vector4();
  45561. function update( object, geometry, program ) {
  45562. const objectInfluences = object.morphTargetInfluences;
  45563. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45564. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45565. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45566. let entry = morphTextures.get( geometry );
  45567. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45568. if ( entry !== undefined ) entry.texture.dispose();
  45569. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45570. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45571. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45572. const morphTargets = geometry.morphAttributes.position || [];
  45573. const morphNormals = geometry.morphAttributes.normal || [];
  45574. const morphColors = geometry.morphAttributes.color || [];
  45575. let vertexDataCount = 0;
  45576. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45577. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45578. if ( hasMorphColors === true ) vertexDataCount = 3;
  45579. let width = geometry.attributes.position.count * vertexDataCount;
  45580. let height = 1;
  45581. if ( width > capabilities.maxTextureSize ) {
  45582. height = Math.ceil( width / capabilities.maxTextureSize );
  45583. width = capabilities.maxTextureSize;
  45584. }
  45585. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45586. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45587. texture.type = FloatType;
  45588. texture.needsUpdate = true;
  45589. // fill buffer
  45590. const vertexDataStride = vertexDataCount * 4;
  45591. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45592. const morphTarget = morphTargets[ i ];
  45593. const morphNormal = morphNormals[ i ];
  45594. const morphColor = morphColors[ i ];
  45595. const offset = width * height * 4 * i;
  45596. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45597. const stride = j * vertexDataStride;
  45598. if ( hasMorphPosition === true ) {
  45599. morph.fromBufferAttribute( morphTarget, j );
  45600. buffer[ offset + stride + 0 ] = morph.x;
  45601. buffer[ offset + stride + 1 ] = morph.y;
  45602. buffer[ offset + stride + 2 ] = morph.z;
  45603. buffer[ offset + stride + 3 ] = 0;
  45604. }
  45605. if ( hasMorphNormals === true ) {
  45606. morph.fromBufferAttribute( morphNormal, j );
  45607. buffer[ offset + stride + 4 ] = morph.x;
  45608. buffer[ offset + stride + 5 ] = morph.y;
  45609. buffer[ offset + stride + 6 ] = morph.z;
  45610. buffer[ offset + stride + 7 ] = 0;
  45611. }
  45612. if ( hasMorphColors === true ) {
  45613. morph.fromBufferAttribute( morphColor, j );
  45614. buffer[ offset + stride + 8 ] = morph.x;
  45615. buffer[ offset + stride + 9 ] = morph.y;
  45616. buffer[ offset + stride + 10 ] = morph.z;
  45617. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45618. }
  45619. }
  45620. }
  45621. entry = {
  45622. count: morphTargetsCount,
  45623. texture: texture,
  45624. size: new Vector2( width, height )
  45625. };
  45626. morphTextures.set( geometry, entry );
  45627. function disposeTexture() {
  45628. texture.dispose();
  45629. morphTextures.delete( geometry );
  45630. geometry.removeEventListener( 'dispose', disposeTexture );
  45631. }
  45632. geometry.addEventListener( 'dispose', disposeTexture );
  45633. }
  45634. //
  45635. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45636. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45637. } else {
  45638. let morphInfluencesSum = 0;
  45639. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45640. morphInfluencesSum += objectInfluences[ i ];
  45641. }
  45642. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45643. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45644. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45645. }
  45646. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45647. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45648. }
  45649. return {
  45650. update: update
  45651. };
  45652. }
  45653. function WebGLObjects( gl, geometries, attributes, bindingStates, info ) {
  45654. let updateMap = new WeakMap();
  45655. function update( object ) {
  45656. const frame = info.render.frame;
  45657. const geometry = object.geometry;
  45658. const buffergeometry = geometries.get( object, geometry );
  45659. // Update once per frame
  45660. if ( updateMap.get( buffergeometry ) !== frame ) {
  45661. geometries.update( buffergeometry );
  45662. updateMap.set( buffergeometry, frame );
  45663. }
  45664. if ( object.isInstancedMesh ) {
  45665. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45666. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45667. }
  45668. if ( updateMap.get( object ) !== frame ) {
  45669. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45670. if ( object.instanceColor !== null ) {
  45671. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45672. }
  45673. updateMap.set( object, frame );
  45674. }
  45675. }
  45676. if ( object.isSkinnedMesh ) {
  45677. const skeleton = object.skeleton;
  45678. if ( updateMap.get( skeleton ) !== frame ) {
  45679. skeleton.update();
  45680. updateMap.set( skeleton, frame );
  45681. }
  45682. }
  45683. return buffergeometry;
  45684. }
  45685. function dispose() {
  45686. updateMap = new WeakMap();
  45687. }
  45688. function onInstancedMeshDispose( event ) {
  45689. const instancedMesh = event.target;
  45690. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45691. bindingStates.releaseStatesOfObject( instancedMesh );
  45692. attributes.remove( instancedMesh.instanceMatrix );
  45693. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45694. }
  45695. return {
  45696. update: update,
  45697. dispose: dispose
  45698. };
  45699. }
  45700. const toneMappingMap = {
  45701. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  45702. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  45703. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  45704. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  45705. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  45706. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  45707. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  45708. };
  45709. function WebGLOutput( type, width, height, depth, stencil ) {
  45710. // render targets for scene and post-processing
  45711. const targetA = new WebGLRenderTarget( width, height, {
  45712. type: type,
  45713. depthBuffer: depth,
  45714. stencilBuffer: stencil
  45715. } );
  45716. const targetB = new WebGLRenderTarget( width, height, {
  45717. type: HalfFloatType,
  45718. depthBuffer: false,
  45719. stencilBuffer: false
  45720. } );
  45721. // create fullscreen triangle geometry
  45722. const geometry = new BufferGeometry();
  45723. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  45724. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  45725. // create output material with tone mapping support
  45726. const material = new RawShaderMaterial( {
  45727. uniforms: {
  45728. tDiffuse: { value: null }
  45729. },
  45730. vertexShader: /* glsl */`
  45731. precision highp float;
  45732. uniform mat4 modelViewMatrix;
  45733. uniform mat4 projectionMatrix;
  45734. attribute vec3 position;
  45735. attribute vec2 uv;
  45736. varying vec2 vUv;
  45737. void main() {
  45738. vUv = uv;
  45739. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  45740. }`,
  45741. fragmentShader: /* glsl */`
  45742. precision highp float;
  45743. uniform sampler2D tDiffuse;
  45744. varying vec2 vUv;
  45745. #include <tonemapping_pars_fragment>
  45746. #include <colorspace_pars_fragment>
  45747. void main() {
  45748. gl_FragColor = texture2D( tDiffuse, vUv );
  45749. #ifdef LINEAR_TONE_MAPPING
  45750. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  45751. #elif defined( REINHARD_TONE_MAPPING )
  45752. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  45753. #elif defined( CINEON_TONE_MAPPING )
  45754. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  45755. #elif defined( ACES_FILMIC_TONE_MAPPING )
  45756. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  45757. #elif defined( AGX_TONE_MAPPING )
  45758. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  45759. #elif defined( NEUTRAL_TONE_MAPPING )
  45760. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  45761. #elif defined( CUSTOM_TONE_MAPPING )
  45762. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  45763. #endif
  45764. #ifdef SRGB_TRANSFER
  45765. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  45766. #endif
  45767. }`,
  45768. depthTest: false,
  45769. depthWrite: false
  45770. } );
  45771. const mesh = new Mesh( geometry, material );
  45772. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  45773. let _outputColorSpace = null;
  45774. let _outputToneMapping = null;
  45775. let _isCompositing = false;
  45776. let _savedToneMapping;
  45777. let _savedRenderTarget = null;
  45778. let _effects = [];
  45779. let _hasRenderPass = false;
  45780. this.setSize = function ( width, height ) {
  45781. targetA.setSize( width, height );
  45782. targetB.setSize( width, height );
  45783. for ( let i = 0; i < _effects.length; i ++ ) {
  45784. const effect = _effects[ i ];
  45785. if ( effect.setSize ) effect.setSize( width, height );
  45786. }
  45787. };
  45788. this.setEffects = function ( effects ) {
  45789. _effects = effects;
  45790. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  45791. const width = targetA.width;
  45792. const height = targetA.height;
  45793. for ( let i = 0; i < _effects.length; i ++ ) {
  45794. const effect = _effects[ i ];
  45795. if ( effect.setSize ) effect.setSize( width, height );
  45796. }
  45797. };
  45798. this.begin = function ( renderer, renderTarget ) {
  45799. // Don't begin during compositing phase (post-processing effects call render())
  45800. if ( _isCompositing ) return false;
  45801. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  45802. _savedRenderTarget = renderTarget;
  45803. // resize internal buffers to match render target (e.g. XR resolution)
  45804. if ( renderTarget !== null ) {
  45805. const width = renderTarget.width;
  45806. const height = renderTarget.height;
  45807. if ( targetA.width !== width || targetA.height !== height ) {
  45808. this.setSize( width, height );
  45809. }
  45810. }
  45811. // if first effect is a RenderPass, it will set its own render target
  45812. if ( _hasRenderPass === false ) {
  45813. renderer.setRenderTarget( targetA );
  45814. }
  45815. // disable tone mapping during render - it will be applied in end()
  45816. _savedToneMapping = renderer.toneMapping;
  45817. renderer.toneMapping = NoToneMapping;
  45818. return true;
  45819. };
  45820. this.hasRenderPass = function () {
  45821. return _hasRenderPass;
  45822. };
  45823. this.end = function ( renderer, deltaTime ) {
  45824. // restore tone mapping
  45825. renderer.toneMapping = _savedToneMapping;
  45826. _isCompositing = true;
  45827. // run post-processing effects
  45828. let readBuffer = targetA;
  45829. let writeBuffer = targetB;
  45830. for ( let i = 0; i < _effects.length; i ++ ) {
  45831. const effect = _effects[ i ];
  45832. if ( effect.enabled === false ) continue;
  45833. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  45834. if ( effect.needsSwap !== false ) {
  45835. const temp = readBuffer;
  45836. readBuffer = writeBuffer;
  45837. writeBuffer = temp;
  45838. }
  45839. }
  45840. // update output material defines if settings changed
  45841. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  45842. _outputColorSpace = renderer.outputColorSpace;
  45843. _outputToneMapping = renderer.toneMapping;
  45844. material.defines = {};
  45845. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  45846. const toneMapping = toneMappingMap[ _outputToneMapping ];
  45847. if ( toneMapping ) material.defines[ toneMapping ] = '';
  45848. material.needsUpdate = true;
  45849. }
  45850. // final output to canvas (or XR render target)
  45851. material.uniforms.tDiffuse.value = readBuffer.texture;
  45852. renderer.setRenderTarget( _savedRenderTarget );
  45853. renderer.render( mesh, camera );
  45854. _savedRenderTarget = null;
  45855. _isCompositing = false;
  45856. };
  45857. this.isCompositing = function () {
  45858. return _isCompositing;
  45859. };
  45860. this.dispose = function () {
  45861. targetA.dispose();
  45862. targetB.dispose();
  45863. geometry.dispose();
  45864. material.dispose();
  45865. };
  45866. }
  45867. /**
  45868. * Uniforms of a program.
  45869. * Those form a tree structure with a special top-level container for the root,
  45870. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45871. *
  45872. *
  45873. * Properties of inner nodes including the top-level container:
  45874. *
  45875. * .seq - array of nested uniforms
  45876. * .map - nested uniforms by name
  45877. *
  45878. *
  45879. * Methods of all nodes except the top-level container:
  45880. *
  45881. * .setValue( gl, value, [textures] )
  45882. *
  45883. * uploads a uniform value(s)
  45884. * the 'textures' parameter is needed for sampler uniforms
  45885. *
  45886. *
  45887. * Static methods of the top-level container (textures factorizations):
  45888. *
  45889. * .upload( gl, seq, values, textures )
  45890. *
  45891. * sets uniforms in 'seq' to 'values[id].value'
  45892. *
  45893. * .seqWithValue( seq, values ) : filteredSeq
  45894. *
  45895. * filters 'seq' entries with corresponding entry in values
  45896. *
  45897. *
  45898. * Methods of the top-level container (textures factorizations):
  45899. *
  45900. * .setValue( gl, name, value, textures )
  45901. *
  45902. * sets uniform with name 'name' to 'value'
  45903. *
  45904. * .setOptional( gl, obj, prop )
  45905. *
  45906. * like .set for an optional property of the object
  45907. *
  45908. */
  45909. const emptyTexture = /*@__PURE__*/ new Texture();
  45910. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45911. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45912. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45913. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45914. // --- Utilities ---
  45915. // Array Caches (provide typed arrays for temporary by size)
  45916. const arrayCacheF32 = [];
  45917. const arrayCacheI32 = [];
  45918. // Float32Array caches used for uploading Matrix uniforms
  45919. const mat4array = new Float32Array( 16 );
  45920. const mat3array = new Float32Array( 9 );
  45921. const mat2array = new Float32Array( 4 );
  45922. // Flattening for arrays of vectors and matrices
  45923. function flatten( array, nBlocks, blockSize ) {
  45924. const firstElem = array[ 0 ];
  45925. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45926. // unoptimized: ! isNaN( firstElem )
  45927. // see http://jacksondunstan.com/articles/983
  45928. const n = nBlocks * blockSize;
  45929. let r = arrayCacheF32[ n ];
  45930. if ( r === undefined ) {
  45931. r = new Float32Array( n );
  45932. arrayCacheF32[ n ] = r;
  45933. }
  45934. if ( nBlocks !== 0 ) {
  45935. firstElem.toArray( r, 0 );
  45936. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45937. offset += blockSize;
  45938. array[ i ].toArray( r, offset );
  45939. }
  45940. }
  45941. return r;
  45942. }
  45943. function arraysEqual( a, b ) {
  45944. if ( a.length !== b.length ) return false;
  45945. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45946. if ( a[ i ] !== b[ i ] ) return false;
  45947. }
  45948. return true;
  45949. }
  45950. function copyArray( a, b ) {
  45951. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45952. a[ i ] = b[ i ];
  45953. }
  45954. }
  45955. // Texture unit allocation
  45956. function allocTexUnits( textures, n ) {
  45957. let r = arrayCacheI32[ n ];
  45958. if ( r === undefined ) {
  45959. r = new Int32Array( n );
  45960. arrayCacheI32[ n ] = r;
  45961. }
  45962. for ( let i = 0; i !== n; ++ i ) {
  45963. r[ i ] = textures.allocateTextureUnit();
  45964. }
  45965. return r;
  45966. }
  45967. // --- Setters ---
  45968. // Note: Defining these methods externally, because they come in a bunch
  45969. // and this way their names minify.
  45970. // Single scalar
  45971. function setValueV1f( gl, v ) {
  45972. const cache = this.cache;
  45973. if ( cache[ 0 ] === v ) return;
  45974. gl.uniform1f( this.addr, v );
  45975. cache[ 0 ] = v;
  45976. }
  45977. // Single float vector (from flat array or THREE.VectorN)
  45978. function setValueV2f( gl, v ) {
  45979. const cache = this.cache;
  45980. if ( v.x !== undefined ) {
  45981. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45982. gl.uniform2f( this.addr, v.x, v.y );
  45983. cache[ 0 ] = v.x;
  45984. cache[ 1 ] = v.y;
  45985. }
  45986. } else {
  45987. if ( arraysEqual( cache, v ) ) return;
  45988. gl.uniform2fv( this.addr, v );
  45989. copyArray( cache, v );
  45990. }
  45991. }
  45992. function setValueV3f( gl, v ) {
  45993. const cache = this.cache;
  45994. if ( v.x !== undefined ) {
  45995. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45996. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45997. cache[ 0 ] = v.x;
  45998. cache[ 1 ] = v.y;
  45999. cache[ 2 ] = v.z;
  46000. }
  46001. } else if ( v.r !== undefined ) {
  46002. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  46003. gl.uniform3f( this.addr, v.r, v.g, v.b );
  46004. cache[ 0 ] = v.r;
  46005. cache[ 1 ] = v.g;
  46006. cache[ 2 ] = v.b;
  46007. }
  46008. } else {
  46009. if ( arraysEqual( cache, v ) ) return;
  46010. gl.uniform3fv( this.addr, v );
  46011. copyArray( cache, v );
  46012. }
  46013. }
  46014. function setValueV4f( gl, v ) {
  46015. const cache = this.cache;
  46016. if ( v.x !== undefined ) {
  46017. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46018. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  46019. cache[ 0 ] = v.x;
  46020. cache[ 1 ] = v.y;
  46021. cache[ 2 ] = v.z;
  46022. cache[ 3 ] = v.w;
  46023. }
  46024. } else {
  46025. if ( arraysEqual( cache, v ) ) return;
  46026. gl.uniform4fv( this.addr, v );
  46027. copyArray( cache, v );
  46028. }
  46029. }
  46030. // Single matrix (from flat array or THREE.MatrixN)
  46031. function setValueM2( gl, v ) {
  46032. const cache = this.cache;
  46033. const elements = v.elements;
  46034. if ( elements === undefined ) {
  46035. if ( arraysEqual( cache, v ) ) return;
  46036. gl.uniformMatrix2fv( this.addr, false, v );
  46037. copyArray( cache, v );
  46038. } else {
  46039. if ( arraysEqual( cache, elements ) ) return;
  46040. mat2array.set( elements );
  46041. gl.uniformMatrix2fv( this.addr, false, mat2array );
  46042. copyArray( cache, elements );
  46043. }
  46044. }
  46045. function setValueM3( gl, v ) {
  46046. const cache = this.cache;
  46047. const elements = v.elements;
  46048. if ( elements === undefined ) {
  46049. if ( arraysEqual( cache, v ) ) return;
  46050. gl.uniformMatrix3fv( this.addr, false, v );
  46051. copyArray( cache, v );
  46052. } else {
  46053. if ( arraysEqual( cache, elements ) ) return;
  46054. mat3array.set( elements );
  46055. gl.uniformMatrix3fv( this.addr, false, mat3array );
  46056. copyArray( cache, elements );
  46057. }
  46058. }
  46059. function setValueM4( gl, v ) {
  46060. const cache = this.cache;
  46061. const elements = v.elements;
  46062. if ( elements === undefined ) {
  46063. if ( arraysEqual( cache, v ) ) return;
  46064. gl.uniformMatrix4fv( this.addr, false, v );
  46065. copyArray( cache, v );
  46066. } else {
  46067. if ( arraysEqual( cache, elements ) ) return;
  46068. mat4array.set( elements );
  46069. gl.uniformMatrix4fv( this.addr, false, mat4array );
  46070. copyArray( cache, elements );
  46071. }
  46072. }
  46073. // Single integer / boolean
  46074. function setValueV1i( gl, v ) {
  46075. const cache = this.cache;
  46076. if ( cache[ 0 ] === v ) return;
  46077. gl.uniform1i( this.addr, v );
  46078. cache[ 0 ] = v;
  46079. }
  46080. // Single integer / boolean vector (from flat array or THREE.VectorN)
  46081. function setValueV2i( gl, v ) {
  46082. const cache = this.cache;
  46083. if ( v.x !== undefined ) {
  46084. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46085. gl.uniform2i( this.addr, v.x, v.y );
  46086. cache[ 0 ] = v.x;
  46087. cache[ 1 ] = v.y;
  46088. }
  46089. } else {
  46090. if ( arraysEqual( cache, v ) ) return;
  46091. gl.uniform2iv( this.addr, v );
  46092. copyArray( cache, v );
  46093. }
  46094. }
  46095. function setValueV3i( gl, v ) {
  46096. const cache = this.cache;
  46097. if ( v.x !== undefined ) {
  46098. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46099. gl.uniform3i( this.addr, v.x, v.y, v.z );
  46100. cache[ 0 ] = v.x;
  46101. cache[ 1 ] = v.y;
  46102. cache[ 2 ] = v.z;
  46103. }
  46104. } else {
  46105. if ( arraysEqual( cache, v ) ) return;
  46106. gl.uniform3iv( this.addr, v );
  46107. copyArray( cache, v );
  46108. }
  46109. }
  46110. function setValueV4i( gl, v ) {
  46111. const cache = this.cache;
  46112. if ( v.x !== undefined ) {
  46113. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46114. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  46115. cache[ 0 ] = v.x;
  46116. cache[ 1 ] = v.y;
  46117. cache[ 2 ] = v.z;
  46118. cache[ 3 ] = v.w;
  46119. }
  46120. } else {
  46121. if ( arraysEqual( cache, v ) ) return;
  46122. gl.uniform4iv( this.addr, v );
  46123. copyArray( cache, v );
  46124. }
  46125. }
  46126. // Single unsigned integer
  46127. function setValueV1ui( gl, v ) {
  46128. const cache = this.cache;
  46129. if ( cache[ 0 ] === v ) return;
  46130. gl.uniform1ui( this.addr, v );
  46131. cache[ 0 ] = v;
  46132. }
  46133. // Single unsigned integer vector (from flat array or THREE.VectorN)
  46134. function setValueV2ui( gl, v ) {
  46135. const cache = this.cache;
  46136. if ( v.x !== undefined ) {
  46137. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46138. gl.uniform2ui( this.addr, v.x, v.y );
  46139. cache[ 0 ] = v.x;
  46140. cache[ 1 ] = v.y;
  46141. }
  46142. } else {
  46143. if ( arraysEqual( cache, v ) ) return;
  46144. gl.uniform2uiv( this.addr, v );
  46145. copyArray( cache, v );
  46146. }
  46147. }
  46148. function setValueV3ui( gl, v ) {
  46149. const cache = this.cache;
  46150. if ( v.x !== undefined ) {
  46151. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46152. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  46153. cache[ 0 ] = v.x;
  46154. cache[ 1 ] = v.y;
  46155. cache[ 2 ] = v.z;
  46156. }
  46157. } else {
  46158. if ( arraysEqual( cache, v ) ) return;
  46159. gl.uniform3uiv( this.addr, v );
  46160. copyArray( cache, v );
  46161. }
  46162. }
  46163. function setValueV4ui( gl, v ) {
  46164. const cache = this.cache;
  46165. if ( v.x !== undefined ) {
  46166. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46167. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  46168. cache[ 0 ] = v.x;
  46169. cache[ 1 ] = v.y;
  46170. cache[ 2 ] = v.z;
  46171. cache[ 3 ] = v.w;
  46172. }
  46173. } else {
  46174. if ( arraysEqual( cache, v ) ) return;
  46175. gl.uniform4uiv( this.addr, v );
  46176. copyArray( cache, v );
  46177. }
  46178. }
  46179. // Single texture (2D / Cube)
  46180. function setValueT1( gl, v, textures ) {
  46181. const cache = this.cache;
  46182. const unit = textures.allocateTextureUnit();
  46183. if ( cache[ 0 ] !== unit ) {
  46184. gl.uniform1i( this.addr, unit );
  46185. cache[ 0 ] = unit;
  46186. }
  46187. let emptyTexture2D;
  46188. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46189. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  46190. emptyTexture2D = emptyShadowTexture;
  46191. } else {
  46192. emptyTexture2D = emptyTexture;
  46193. }
  46194. textures.setTexture2D( v || emptyTexture2D, unit );
  46195. }
  46196. function setValueT3D1( gl, v, textures ) {
  46197. const cache = this.cache;
  46198. const unit = textures.allocateTextureUnit();
  46199. if ( cache[ 0 ] !== unit ) {
  46200. gl.uniform1i( this.addr, unit );
  46201. cache[ 0 ] = unit;
  46202. }
  46203. textures.setTexture3D( v || empty3dTexture, unit );
  46204. }
  46205. function setValueT6( gl, v, textures ) {
  46206. const cache = this.cache;
  46207. const unit = textures.allocateTextureUnit();
  46208. if ( cache[ 0 ] !== unit ) {
  46209. gl.uniform1i( this.addr, unit );
  46210. cache[ 0 ] = unit;
  46211. }
  46212. textures.setTextureCube( v || emptyCubeTexture, unit );
  46213. }
  46214. function setValueT2DArray1( gl, v, textures ) {
  46215. const cache = this.cache;
  46216. const unit = textures.allocateTextureUnit();
  46217. if ( cache[ 0 ] !== unit ) {
  46218. gl.uniform1i( this.addr, unit );
  46219. cache[ 0 ] = unit;
  46220. }
  46221. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46222. }
  46223. // Helper to pick the right setter for the singular case
  46224. function getSingularSetter( type ) {
  46225. switch ( type ) {
  46226. case 0x1406: return setValueV1f; // FLOAT
  46227. case 0x8b50: return setValueV2f; // _VEC2
  46228. case 0x8b51: return setValueV3f; // _VEC3
  46229. case 0x8b52: return setValueV4f; // _VEC4
  46230. case 0x8b5a: return setValueM2; // _MAT2
  46231. case 0x8b5b: return setValueM3; // _MAT3
  46232. case 0x8b5c: return setValueM4; // _MAT4
  46233. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46234. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46235. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46236. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46237. case 0x1405: return setValueV1ui; // UINT
  46238. case 0x8dc6: return setValueV2ui; // _VEC2
  46239. case 0x8dc7: return setValueV3ui; // _VEC3
  46240. case 0x8dc8: return setValueV4ui; // _VEC4
  46241. case 0x8b5e: // SAMPLER_2D
  46242. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46243. case 0x8dca: // INT_SAMPLER_2D
  46244. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46245. case 0x8b62: // SAMPLER_2D_SHADOW
  46246. return setValueT1;
  46247. case 0x8b5f: // SAMPLER_3D
  46248. case 0x8dcb: // INT_SAMPLER_3D
  46249. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46250. return setValueT3D1;
  46251. case 0x8b60: // SAMPLER_CUBE
  46252. case 0x8dcc: // INT_SAMPLER_CUBE
  46253. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46254. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46255. return setValueT6;
  46256. case 0x8dc1: // SAMPLER_2D_ARRAY
  46257. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46258. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46259. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46260. return setValueT2DArray1;
  46261. }
  46262. }
  46263. // Array of scalars
  46264. function setValueV1fArray( gl, v ) {
  46265. gl.uniform1fv( this.addr, v );
  46266. }
  46267. // Array of vectors (from flat array or array of THREE.VectorN)
  46268. function setValueV2fArray( gl, v ) {
  46269. const data = flatten( v, this.size, 2 );
  46270. gl.uniform2fv( this.addr, data );
  46271. }
  46272. function setValueV3fArray( gl, v ) {
  46273. const data = flatten( v, this.size, 3 );
  46274. gl.uniform3fv( this.addr, data );
  46275. }
  46276. function setValueV4fArray( gl, v ) {
  46277. const data = flatten( v, this.size, 4 );
  46278. gl.uniform4fv( this.addr, data );
  46279. }
  46280. // Array of matrices (from flat array or array of THREE.MatrixN)
  46281. function setValueM2Array( gl, v ) {
  46282. const data = flatten( v, this.size, 4 );
  46283. gl.uniformMatrix2fv( this.addr, false, data );
  46284. }
  46285. function setValueM3Array( gl, v ) {
  46286. const data = flatten( v, this.size, 9 );
  46287. gl.uniformMatrix3fv( this.addr, false, data );
  46288. }
  46289. function setValueM4Array( gl, v ) {
  46290. const data = flatten( v, this.size, 16 );
  46291. gl.uniformMatrix4fv( this.addr, false, data );
  46292. }
  46293. // Array of integer / boolean
  46294. function setValueV1iArray( gl, v ) {
  46295. gl.uniform1iv( this.addr, v );
  46296. }
  46297. // Array of integer / boolean vectors (from flat array)
  46298. function setValueV2iArray( gl, v ) {
  46299. gl.uniform2iv( this.addr, v );
  46300. }
  46301. function setValueV3iArray( gl, v ) {
  46302. gl.uniform3iv( this.addr, v );
  46303. }
  46304. function setValueV4iArray( gl, v ) {
  46305. gl.uniform4iv( this.addr, v );
  46306. }
  46307. // Array of unsigned integer
  46308. function setValueV1uiArray( gl, v ) {
  46309. gl.uniform1uiv( this.addr, v );
  46310. }
  46311. // Array of unsigned integer vectors (from flat array)
  46312. function setValueV2uiArray( gl, v ) {
  46313. gl.uniform2uiv( this.addr, v );
  46314. }
  46315. function setValueV3uiArray( gl, v ) {
  46316. gl.uniform3uiv( this.addr, v );
  46317. }
  46318. function setValueV4uiArray( gl, v ) {
  46319. gl.uniform4uiv( this.addr, v );
  46320. }
  46321. // Array of textures (2D / 3D / Cube / 2DArray)
  46322. function setValueT1Array( gl, v, textures ) {
  46323. const cache = this.cache;
  46324. const n = v.length;
  46325. const units = allocTexUnits( textures, n );
  46326. if ( ! arraysEqual( cache, units ) ) {
  46327. gl.uniform1iv( this.addr, units );
  46328. copyArray( cache, units );
  46329. }
  46330. let emptyTexture2D;
  46331. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46332. emptyTexture2D = emptyShadowTexture;
  46333. } else {
  46334. emptyTexture2D = emptyTexture;
  46335. }
  46336. for ( let i = 0; i !== n; ++ i ) {
  46337. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46338. }
  46339. }
  46340. function setValueT3DArray( gl, v, textures ) {
  46341. const cache = this.cache;
  46342. const n = v.length;
  46343. const units = allocTexUnits( textures, n );
  46344. if ( ! arraysEqual( cache, units ) ) {
  46345. gl.uniform1iv( this.addr, units );
  46346. copyArray( cache, units );
  46347. }
  46348. for ( let i = 0; i !== n; ++ i ) {
  46349. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46350. }
  46351. }
  46352. function setValueT6Array( gl, v, textures ) {
  46353. const cache = this.cache;
  46354. const n = v.length;
  46355. const units = allocTexUnits( textures, n );
  46356. if ( ! arraysEqual( cache, units ) ) {
  46357. gl.uniform1iv( this.addr, units );
  46358. copyArray( cache, units );
  46359. }
  46360. for ( let i = 0; i !== n; ++ i ) {
  46361. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46362. }
  46363. }
  46364. function setValueT2DArrayArray( gl, v, textures ) {
  46365. const cache = this.cache;
  46366. const n = v.length;
  46367. const units = allocTexUnits( textures, n );
  46368. if ( ! arraysEqual( cache, units ) ) {
  46369. gl.uniform1iv( this.addr, units );
  46370. copyArray( cache, units );
  46371. }
  46372. for ( let i = 0; i !== n; ++ i ) {
  46373. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46374. }
  46375. }
  46376. // Helper to pick the right setter for a pure (bottom-level) array
  46377. function getPureArraySetter( type ) {
  46378. switch ( type ) {
  46379. case 0x1406: return setValueV1fArray; // FLOAT
  46380. case 0x8b50: return setValueV2fArray; // _VEC2
  46381. case 0x8b51: return setValueV3fArray; // _VEC3
  46382. case 0x8b52: return setValueV4fArray; // _VEC4
  46383. case 0x8b5a: return setValueM2Array; // _MAT2
  46384. case 0x8b5b: return setValueM3Array; // _MAT3
  46385. case 0x8b5c: return setValueM4Array; // _MAT4
  46386. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46387. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46388. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46389. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46390. case 0x1405: return setValueV1uiArray; // UINT
  46391. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46392. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46393. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46394. case 0x8b5e: // SAMPLER_2D
  46395. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46396. case 0x8dca: // INT_SAMPLER_2D
  46397. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46398. case 0x8b62: // SAMPLER_2D_SHADOW
  46399. return setValueT1Array;
  46400. case 0x8b5f: // SAMPLER_3D
  46401. case 0x8dcb: // INT_SAMPLER_3D
  46402. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46403. return setValueT3DArray;
  46404. case 0x8b60: // SAMPLER_CUBE
  46405. case 0x8dcc: // INT_SAMPLER_CUBE
  46406. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46407. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46408. return setValueT6Array;
  46409. case 0x8dc1: // SAMPLER_2D_ARRAY
  46410. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46411. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46412. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46413. return setValueT2DArrayArray;
  46414. }
  46415. }
  46416. // --- Uniform Classes ---
  46417. class SingleUniform {
  46418. constructor( id, activeInfo, addr ) {
  46419. this.id = id;
  46420. this.addr = addr;
  46421. this.cache = [];
  46422. this.type = activeInfo.type;
  46423. this.setValue = getSingularSetter( activeInfo.type );
  46424. // this.path = activeInfo.name; // DEBUG
  46425. }
  46426. }
  46427. class PureArrayUniform {
  46428. constructor( id, activeInfo, addr ) {
  46429. this.id = id;
  46430. this.addr = addr;
  46431. this.cache = [];
  46432. this.type = activeInfo.type;
  46433. this.size = activeInfo.size;
  46434. this.setValue = getPureArraySetter( activeInfo.type );
  46435. // this.path = activeInfo.name; // DEBUG
  46436. }
  46437. }
  46438. class StructuredUniform {
  46439. constructor( id ) {
  46440. this.id = id;
  46441. this.seq = [];
  46442. this.map = {};
  46443. }
  46444. setValue( gl, value, textures ) {
  46445. const seq = this.seq;
  46446. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46447. const u = seq[ i ];
  46448. u.setValue( gl, value[ u.id ], textures );
  46449. }
  46450. }
  46451. }
  46452. // --- Top-level ---
  46453. // Parser - builds up the property tree from the path strings
  46454. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46455. // extracts
  46456. // - the identifier (member name or array index)
  46457. // - followed by an optional right bracket (found when array index)
  46458. // - followed by an optional left bracket or dot (type of subscript)
  46459. //
  46460. // Note: These portions can be read in a non-overlapping fashion and
  46461. // allow straightforward parsing of the hierarchy that WebGL encodes
  46462. // in the uniform names.
  46463. function addUniform( container, uniformObject ) {
  46464. container.seq.push( uniformObject );
  46465. container.map[ uniformObject.id ] = uniformObject;
  46466. }
  46467. function parseUniform( activeInfo, addr, container ) {
  46468. const path = activeInfo.name,
  46469. pathLength = path.length;
  46470. // reset RegExp object, because of the early exit of a previous run
  46471. RePathPart.lastIndex = 0;
  46472. while ( true ) {
  46473. const match = RePathPart.exec( path ),
  46474. matchEnd = RePathPart.lastIndex;
  46475. let id = match[ 1 ];
  46476. const idIsIndex = match[ 2 ] === ']',
  46477. subscript = match[ 3 ];
  46478. if ( idIsIndex ) id = id | 0; // convert to integer
  46479. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46480. // bare name or "pure" bottom-level array "[0]" suffix
  46481. addUniform( container, subscript === undefined ?
  46482. new SingleUniform( id, activeInfo, addr ) :
  46483. new PureArrayUniform( id, activeInfo, addr ) );
  46484. break;
  46485. } else {
  46486. // step into inner node / create it in case it doesn't exist
  46487. const map = container.map;
  46488. let next = map[ id ];
  46489. if ( next === undefined ) {
  46490. next = new StructuredUniform( id );
  46491. addUniform( container, next );
  46492. }
  46493. container = next;
  46494. }
  46495. }
  46496. }
  46497. // Root Container
  46498. class WebGLUniforms {
  46499. constructor( gl, program ) {
  46500. this.seq = [];
  46501. this.map = {};
  46502. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46503. for ( let i = 0; i < n; ++ i ) {
  46504. const info = gl.getActiveUniform( program, i ),
  46505. addr = gl.getUniformLocation( program, info.name );
  46506. parseUniform( info, addr, this );
  46507. }
  46508. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46509. const shadowSamplers = [];
  46510. const otherUniforms = [];
  46511. for ( const u of this.seq ) {
  46512. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46513. shadowSamplers.push( u );
  46514. } else {
  46515. otherUniforms.push( u );
  46516. }
  46517. }
  46518. if ( shadowSamplers.length > 0 ) {
  46519. this.seq = shadowSamplers.concat( otherUniforms );
  46520. }
  46521. }
  46522. setValue( gl, name, value, textures ) {
  46523. const u = this.map[ name ];
  46524. if ( u !== undefined ) u.setValue( gl, value, textures );
  46525. }
  46526. setOptional( gl, object, name ) {
  46527. const v = object[ name ];
  46528. if ( v !== undefined ) this.setValue( gl, name, v );
  46529. }
  46530. static upload( gl, seq, values, textures ) {
  46531. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46532. const u = seq[ i ],
  46533. v = values[ u.id ];
  46534. if ( v.needsUpdate !== false ) {
  46535. // note: always updating when .needsUpdate is undefined
  46536. u.setValue( gl, v.value, textures );
  46537. }
  46538. }
  46539. }
  46540. static seqWithValue( seq, values ) {
  46541. const r = [];
  46542. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46543. const u = seq[ i ];
  46544. if ( u.id in values ) r.push( u );
  46545. }
  46546. return r;
  46547. }
  46548. }
  46549. function WebGLShader( gl, type, string ) {
  46550. const shader = gl.createShader( type );
  46551. gl.shaderSource( shader, string );
  46552. gl.compileShader( shader );
  46553. return shader;
  46554. }
  46555. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46556. const COMPLETION_STATUS_KHR = 0x91B1;
  46557. let programIdCount = 0;
  46558. function handleSource( string, errorLine ) {
  46559. const lines = string.split( '\n' );
  46560. const lines2 = [];
  46561. const from = Math.max( errorLine - 6, 0 );
  46562. const to = Math.min( errorLine + 6, lines.length );
  46563. for ( let i = from; i < to; i ++ ) {
  46564. const line = i + 1;
  46565. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46566. }
  46567. return lines2.join( '\n' );
  46568. }
  46569. const _m0 = /*@__PURE__*/ new Matrix3();
  46570. function getEncodingComponents( colorSpace ) {
  46571. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46572. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46573. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46574. case LinearTransfer:
  46575. return [ encodingMatrix, 'LinearTransferOETF' ];
  46576. case SRGBTransfer:
  46577. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46578. default:
  46579. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46580. return [ encodingMatrix, 'LinearTransferOETF' ];
  46581. }
  46582. }
  46583. function getShaderErrors( gl, shader, type ) {
  46584. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46585. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46586. const errors = shaderInfoLog.trim();
  46587. if ( status && errors === '' ) return '';
  46588. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46589. if ( errorMatches ) {
  46590. // --enable-privileged-webgl-extension
  46591. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46592. const errorLine = parseInt( errorMatches[ 1 ] );
  46593. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46594. } else {
  46595. return errors;
  46596. }
  46597. }
  46598. function getTexelEncodingFunction( functionName, colorSpace ) {
  46599. const components = getEncodingComponents( colorSpace );
  46600. return [
  46601. `vec4 ${functionName}( vec4 value ) {`,
  46602. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46603. '}',
  46604. ].join( '\n' );
  46605. }
  46606. const toneMappingFunctions = {
  46607. [ LinearToneMapping ]: 'Linear',
  46608. [ ReinhardToneMapping ]: 'Reinhard',
  46609. [ CineonToneMapping ]: 'Cineon',
  46610. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  46611. [ AgXToneMapping ]: 'AgX',
  46612. [ NeutralToneMapping ]: 'Neutral',
  46613. [ CustomToneMapping ]: 'Custom'
  46614. };
  46615. function getToneMappingFunction( functionName, toneMapping ) {
  46616. const toneMappingName = toneMappingFunctions[ toneMapping ];
  46617. if ( toneMappingName === undefined ) {
  46618. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46619. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  46620. }
  46621. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46622. }
  46623. const _v0 = /*@__PURE__*/ new Vector3();
  46624. function getLuminanceFunction() {
  46625. ColorManagement.getLuminanceCoefficients( _v0 );
  46626. const r = _v0.x.toFixed( 4 );
  46627. const g = _v0.y.toFixed( 4 );
  46628. const b = _v0.z.toFixed( 4 );
  46629. return [
  46630. 'float luminance( const in vec3 rgb ) {',
  46631. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46632. ' return dot( weights, rgb );',
  46633. '}'
  46634. ].join( '\n' );
  46635. }
  46636. function generateVertexExtensions( parameters ) {
  46637. const chunks = [
  46638. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46639. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46640. ];
  46641. return chunks.filter( filterEmptyLine ).join( '\n' );
  46642. }
  46643. function generateDefines( defines ) {
  46644. const chunks = [];
  46645. for ( const name in defines ) {
  46646. const value = defines[ name ];
  46647. if ( value === false ) continue;
  46648. chunks.push( '#define ' + name + ' ' + value );
  46649. }
  46650. return chunks.join( '\n' );
  46651. }
  46652. function fetchAttributeLocations( gl, program ) {
  46653. const attributes = {};
  46654. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46655. for ( let i = 0; i < n; i ++ ) {
  46656. const info = gl.getActiveAttrib( program, i );
  46657. const name = info.name;
  46658. let locationSize = 1;
  46659. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46660. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46661. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46662. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46663. attributes[ name ] = {
  46664. type: info.type,
  46665. location: gl.getAttribLocation( program, name ),
  46666. locationSize: locationSize
  46667. };
  46668. }
  46669. return attributes;
  46670. }
  46671. function filterEmptyLine( string ) {
  46672. return string !== '';
  46673. }
  46674. function replaceLightNums( string, parameters ) {
  46675. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46676. return string
  46677. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46678. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46679. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46680. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46681. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46682. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46683. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46684. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46685. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46686. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46687. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46688. }
  46689. function replaceClippingPlaneNums( string, parameters ) {
  46690. return string
  46691. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46692. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46693. }
  46694. // Resolve Includes
  46695. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46696. function resolveIncludes( string ) {
  46697. return string.replace( includePattern, includeReplacer );
  46698. }
  46699. const shaderChunkMap = new Map();
  46700. function includeReplacer( match, include ) {
  46701. let string = ShaderChunk[ include ];
  46702. if ( string === undefined ) {
  46703. const newInclude = shaderChunkMap.get( include );
  46704. if ( newInclude !== undefined ) {
  46705. string = ShaderChunk[ newInclude ];
  46706. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46707. } else {
  46708. throw new Error( 'Can not resolve #include <' + include + '>' );
  46709. }
  46710. }
  46711. return resolveIncludes( string );
  46712. }
  46713. // Unroll Loops
  46714. 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;
  46715. function unrollLoops( string ) {
  46716. return string.replace( unrollLoopPattern, loopReplacer );
  46717. }
  46718. function loopReplacer( match, start, end, snippet ) {
  46719. let string = '';
  46720. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46721. string += snippet
  46722. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46723. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46724. }
  46725. return string;
  46726. }
  46727. //
  46728. function generatePrecision( parameters ) {
  46729. let precisionstring = `precision ${parameters.precision} float;
  46730. precision ${parameters.precision} int;
  46731. precision ${parameters.precision} sampler2D;
  46732. precision ${parameters.precision} samplerCube;
  46733. precision ${parameters.precision} sampler3D;
  46734. precision ${parameters.precision} sampler2DArray;
  46735. precision ${parameters.precision} sampler2DShadow;
  46736. precision ${parameters.precision} samplerCubeShadow;
  46737. precision ${parameters.precision} sampler2DArrayShadow;
  46738. precision ${parameters.precision} isampler2D;
  46739. precision ${parameters.precision} isampler3D;
  46740. precision ${parameters.precision} isamplerCube;
  46741. precision ${parameters.precision} isampler2DArray;
  46742. precision ${parameters.precision} usampler2D;
  46743. precision ${parameters.precision} usampler3D;
  46744. precision ${parameters.precision} usamplerCube;
  46745. precision ${parameters.precision} usampler2DArray;
  46746. `;
  46747. if ( parameters.precision === 'highp' ) {
  46748. precisionstring += '\n#define HIGH_PRECISION';
  46749. } else if ( parameters.precision === 'mediump' ) {
  46750. precisionstring += '\n#define MEDIUM_PRECISION';
  46751. } else if ( parameters.precision === 'lowp' ) {
  46752. precisionstring += '\n#define LOW_PRECISION';
  46753. }
  46754. return precisionstring;
  46755. }
  46756. const shadowMapTypeDefines = {
  46757. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  46758. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  46759. };
  46760. function generateShadowMapTypeDefine( parameters ) {
  46761. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  46762. }
  46763. const envMapTypeDefines = {
  46764. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  46765. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  46766. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  46767. };
  46768. function generateEnvMapTypeDefine( parameters ) {
  46769. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  46770. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  46771. }
  46772. const envMapModeDefines = {
  46773. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  46774. };
  46775. function generateEnvMapModeDefine( parameters ) {
  46776. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  46777. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  46778. }
  46779. const envMapBlendingDefines = {
  46780. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  46781. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  46782. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  46783. };
  46784. function generateEnvMapBlendingDefine( parameters ) {
  46785. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  46786. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  46787. }
  46788. function generateCubeUVSize( parameters ) {
  46789. const imageHeight = parameters.envMapCubeUVHeight;
  46790. if ( imageHeight === null ) return null;
  46791. const maxMip = Math.log2( imageHeight ) - 2;
  46792. const texelHeight = 1.0 / imageHeight;
  46793. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46794. return { texelWidth, texelHeight, maxMip };
  46795. }
  46796. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46797. // TODO Send this event to Three.js DevTools
  46798. // log( 'WebGLProgram', cacheKey );
  46799. const gl = renderer.getContext();
  46800. const defines = parameters.defines;
  46801. let vertexShader = parameters.vertexShader;
  46802. let fragmentShader = parameters.fragmentShader;
  46803. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46804. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46805. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46806. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46807. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46808. const customVertexExtensions = generateVertexExtensions( parameters );
  46809. const customDefines = generateDefines( defines );
  46810. const program = gl.createProgram();
  46811. let prefixVertex, prefixFragment;
  46812. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46813. if ( parameters.isRawShaderMaterial ) {
  46814. prefixVertex = [
  46815. '#define SHADER_TYPE ' + parameters.shaderType,
  46816. '#define SHADER_NAME ' + parameters.shaderName,
  46817. customDefines
  46818. ].filter( filterEmptyLine ).join( '\n' );
  46819. if ( prefixVertex.length > 0 ) {
  46820. prefixVertex += '\n';
  46821. }
  46822. prefixFragment = [
  46823. '#define SHADER_TYPE ' + parameters.shaderType,
  46824. '#define SHADER_NAME ' + parameters.shaderName,
  46825. customDefines
  46826. ].filter( filterEmptyLine ).join( '\n' );
  46827. if ( prefixFragment.length > 0 ) {
  46828. prefixFragment += '\n';
  46829. }
  46830. } else {
  46831. prefixVertex = [
  46832. generatePrecision( parameters ),
  46833. '#define SHADER_TYPE ' + parameters.shaderType,
  46834. '#define SHADER_NAME ' + parameters.shaderName,
  46835. customDefines,
  46836. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46837. parameters.batching ? '#define USE_BATCHING' : '',
  46838. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46839. parameters.instancing ? '#define USE_INSTANCING' : '',
  46840. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46841. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46842. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46843. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46844. parameters.map ? '#define USE_MAP' : '',
  46845. parameters.envMap ? '#define USE_ENVMAP' : '',
  46846. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46847. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46848. parameters.aoMap ? '#define USE_AOMAP' : '',
  46849. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46850. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46851. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46852. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46853. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46854. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46855. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46856. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46857. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46858. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46859. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46860. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46861. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46862. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46863. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46864. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46865. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46866. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46867. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46868. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46869. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46870. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46871. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46872. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46873. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46874. //
  46875. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46876. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46877. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46878. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46879. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46880. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46881. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46882. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46883. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46884. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46885. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46886. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46887. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46888. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46889. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46890. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46891. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46892. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46893. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46894. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46895. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46896. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46897. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46898. //
  46899. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46900. parameters.vertexColors ? '#define USE_COLOR' : '',
  46901. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46902. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46903. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46904. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46905. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46906. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46907. parameters.skinning ? '#define USE_SKINNING' : '',
  46908. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46909. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46910. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46911. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46912. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46913. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46914. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46915. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46916. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46917. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46918. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46919. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46920. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46921. 'uniform mat4 modelMatrix;',
  46922. 'uniform mat4 modelViewMatrix;',
  46923. 'uniform mat4 projectionMatrix;',
  46924. 'uniform mat4 viewMatrix;',
  46925. 'uniform mat3 normalMatrix;',
  46926. 'uniform vec3 cameraPosition;',
  46927. 'uniform bool isOrthographic;',
  46928. '#ifdef USE_INSTANCING',
  46929. ' attribute mat4 instanceMatrix;',
  46930. '#endif',
  46931. '#ifdef USE_INSTANCING_COLOR',
  46932. ' attribute vec3 instanceColor;',
  46933. '#endif',
  46934. '#ifdef USE_INSTANCING_MORPH',
  46935. ' uniform sampler2D morphTexture;',
  46936. '#endif',
  46937. 'attribute vec3 position;',
  46938. 'attribute vec3 normal;',
  46939. 'attribute vec2 uv;',
  46940. '#ifdef USE_UV1',
  46941. ' attribute vec2 uv1;',
  46942. '#endif',
  46943. '#ifdef USE_UV2',
  46944. ' attribute vec2 uv2;',
  46945. '#endif',
  46946. '#ifdef USE_UV3',
  46947. ' attribute vec2 uv3;',
  46948. '#endif',
  46949. '#ifdef USE_TANGENT',
  46950. ' attribute vec4 tangent;',
  46951. '#endif',
  46952. '#if defined( USE_COLOR_ALPHA )',
  46953. ' attribute vec4 color;',
  46954. '#elif defined( USE_COLOR )',
  46955. ' attribute vec3 color;',
  46956. '#endif',
  46957. '#ifdef USE_SKINNING',
  46958. ' attribute vec4 skinIndex;',
  46959. ' attribute vec4 skinWeight;',
  46960. '#endif',
  46961. '\n'
  46962. ].filter( filterEmptyLine ).join( '\n' );
  46963. prefixFragment = [
  46964. generatePrecision( parameters ),
  46965. '#define SHADER_TYPE ' + parameters.shaderType,
  46966. '#define SHADER_NAME ' + parameters.shaderName,
  46967. customDefines,
  46968. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46969. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46970. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46971. parameters.map ? '#define USE_MAP' : '',
  46972. parameters.matcap ? '#define USE_MATCAP' : '',
  46973. parameters.envMap ? '#define USE_ENVMAP' : '',
  46974. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46975. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46976. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46977. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46978. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46979. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46980. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46981. parameters.aoMap ? '#define USE_AOMAP' : '',
  46982. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46983. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46984. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46985. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46986. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46987. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46988. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46989. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46990. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46991. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46992. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46993. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46994. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46995. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46996. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46997. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46998. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46999. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47000. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47001. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47002. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47003. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  47004. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47005. parameters.sheen ? '#define USE_SHEEN' : '',
  47006. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47007. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47008. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47009. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47010. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47011. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47012. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  47013. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  47014. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47015. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47016. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47017. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47018. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  47019. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47020. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47021. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47022. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47023. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47024. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  47025. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47026. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  47027. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  47028. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47029. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47030. 'uniform mat4 viewMatrix;',
  47031. 'uniform vec3 cameraPosition;',
  47032. 'uniform bool isOrthographic;',
  47033. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  47034. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  47035. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  47036. parameters.dithering ? '#define DITHERING' : '',
  47037. parameters.opaque ? '#define OPAQUE' : '',
  47038. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  47039. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  47040. getLuminanceFunction(),
  47041. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  47042. '\n'
  47043. ].filter( filterEmptyLine ).join( '\n' );
  47044. }
  47045. vertexShader = resolveIncludes( vertexShader );
  47046. vertexShader = replaceLightNums( vertexShader, parameters );
  47047. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  47048. fragmentShader = resolveIncludes( fragmentShader );
  47049. fragmentShader = replaceLightNums( fragmentShader, parameters );
  47050. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  47051. vertexShader = unrollLoops( vertexShader );
  47052. fragmentShader = unrollLoops( fragmentShader );
  47053. if ( parameters.isRawShaderMaterial !== true ) {
  47054. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  47055. versionString = '#version 300 es\n';
  47056. prefixVertex = [
  47057. customVertexExtensions,
  47058. '#define attribute in',
  47059. '#define varying out',
  47060. '#define texture2D texture'
  47061. ].join( '\n' ) + '\n' + prefixVertex;
  47062. prefixFragment = [
  47063. '#define varying in',
  47064. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  47065. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  47066. '#define gl_FragDepthEXT gl_FragDepth',
  47067. '#define texture2D texture',
  47068. '#define textureCube texture',
  47069. '#define texture2DProj textureProj',
  47070. '#define texture2DLodEXT textureLod',
  47071. '#define texture2DProjLodEXT textureProjLod',
  47072. '#define textureCubeLodEXT textureLod',
  47073. '#define texture2DGradEXT textureGrad',
  47074. '#define texture2DProjGradEXT textureProjGrad',
  47075. '#define textureCubeGradEXT textureGrad'
  47076. ].join( '\n' ) + '\n' + prefixFragment;
  47077. }
  47078. const vertexGlsl = versionString + prefixVertex + vertexShader;
  47079. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  47080. // log( '*VERTEX*', vertexGlsl );
  47081. // log( '*FRAGMENT*', fragmentGlsl );
  47082. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  47083. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  47084. gl.attachShader( program, glVertexShader );
  47085. gl.attachShader( program, glFragmentShader );
  47086. // Force a particular attribute to index 0.
  47087. if ( parameters.index0AttributeName !== undefined ) {
  47088. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  47089. } else if ( parameters.morphTargets === true ) {
  47090. // programs with morphTargets displace position out of attribute 0
  47091. gl.bindAttribLocation( program, 0, 'position' );
  47092. }
  47093. gl.linkProgram( program );
  47094. function onFirstUse( self ) {
  47095. // check for link errors
  47096. if ( renderer.debug.checkShaderErrors ) {
  47097. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  47098. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  47099. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  47100. const programLog = programInfoLog.trim();
  47101. const vertexLog = vertexShaderInfoLog.trim();
  47102. const fragmentLog = fragmentShaderInfoLog.trim();
  47103. let runnable = true;
  47104. let haveDiagnostics = true;
  47105. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  47106. runnable = false;
  47107. if ( typeof renderer.debug.onShaderError === 'function' ) {
  47108. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  47109. } else {
  47110. // default error reporting
  47111. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  47112. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  47113. error(
  47114. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47115. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  47116. 'Material Name: ' + self.name + '\n' +
  47117. 'Material Type: ' + self.type + '\n\n' +
  47118. 'Program Info Log: ' + programLog + '\n' +
  47119. vertexErrors + '\n' +
  47120. fragmentErrors
  47121. );
  47122. }
  47123. } else if ( programLog !== '' ) {
  47124. warn( 'WebGLProgram: Program Info Log:', programLog );
  47125. } else if ( vertexLog === '' || fragmentLog === '' ) {
  47126. haveDiagnostics = false;
  47127. }
  47128. if ( haveDiagnostics ) {
  47129. self.diagnostics = {
  47130. runnable: runnable,
  47131. programLog: programLog,
  47132. vertexShader: {
  47133. log: vertexLog,
  47134. prefix: prefixVertex
  47135. },
  47136. fragmentShader: {
  47137. log: fragmentLog,
  47138. prefix: prefixFragment
  47139. }
  47140. };
  47141. }
  47142. }
  47143. // Clean up
  47144. // Crashes in iOS9 and iOS10. #18402
  47145. // gl.detachShader( program, glVertexShader );
  47146. // gl.detachShader( program, glFragmentShader );
  47147. gl.deleteShader( glVertexShader );
  47148. gl.deleteShader( glFragmentShader );
  47149. cachedUniforms = new WebGLUniforms( gl, program );
  47150. cachedAttributes = fetchAttributeLocations( gl, program );
  47151. }
  47152. // set up caching for uniform locations
  47153. let cachedUniforms;
  47154. this.getUniforms = function () {
  47155. if ( cachedUniforms === undefined ) {
  47156. // Populates cachedUniforms and cachedAttributes
  47157. onFirstUse( this );
  47158. }
  47159. return cachedUniforms;
  47160. };
  47161. // set up caching for attribute locations
  47162. let cachedAttributes;
  47163. this.getAttributes = function () {
  47164. if ( cachedAttributes === undefined ) {
  47165. // Populates cachedAttributes and cachedUniforms
  47166. onFirstUse( this );
  47167. }
  47168. return cachedAttributes;
  47169. };
  47170. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  47171. // flag the program as ready immediately. It may cause a stall when it's first used.
  47172. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  47173. this.isReady = function () {
  47174. if ( programReady === false ) {
  47175. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  47176. }
  47177. return programReady;
  47178. };
  47179. // free resource
  47180. this.destroy = function () {
  47181. bindingStates.releaseStatesOfProgram( this );
  47182. gl.deleteProgram( program );
  47183. this.program = undefined;
  47184. };
  47185. //
  47186. this.type = parameters.shaderType;
  47187. this.name = parameters.shaderName;
  47188. this.id = programIdCount ++;
  47189. this.cacheKey = cacheKey;
  47190. this.usedTimes = 1;
  47191. this.program = program;
  47192. this.vertexShader = glVertexShader;
  47193. this.fragmentShader = glFragmentShader;
  47194. return this;
  47195. }
  47196. let _id = 0;
  47197. class WebGLShaderCache {
  47198. constructor() {
  47199. this.shaderCache = new Map();
  47200. this.materialCache = new Map();
  47201. }
  47202. update( material ) {
  47203. const vertexShader = material.vertexShader;
  47204. const fragmentShader = material.fragmentShader;
  47205. const vertexShaderStage = this._getShaderStage( vertexShader );
  47206. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47207. const materialShaders = this._getShaderCacheForMaterial( material );
  47208. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47209. materialShaders.add( vertexShaderStage );
  47210. vertexShaderStage.usedTimes ++;
  47211. }
  47212. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47213. materialShaders.add( fragmentShaderStage );
  47214. fragmentShaderStage.usedTimes ++;
  47215. }
  47216. return this;
  47217. }
  47218. remove( material ) {
  47219. const materialShaders = this.materialCache.get( material );
  47220. for ( const shaderStage of materialShaders ) {
  47221. shaderStage.usedTimes --;
  47222. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47223. }
  47224. this.materialCache.delete( material );
  47225. return this;
  47226. }
  47227. getVertexShaderID( material ) {
  47228. return this._getShaderStage( material.vertexShader ).id;
  47229. }
  47230. getFragmentShaderID( material ) {
  47231. return this._getShaderStage( material.fragmentShader ).id;
  47232. }
  47233. dispose() {
  47234. this.shaderCache.clear();
  47235. this.materialCache.clear();
  47236. }
  47237. _getShaderCacheForMaterial( material ) {
  47238. const cache = this.materialCache;
  47239. let set = cache.get( material );
  47240. if ( set === undefined ) {
  47241. set = new Set();
  47242. cache.set( material, set );
  47243. }
  47244. return set;
  47245. }
  47246. _getShaderStage( code ) {
  47247. const cache = this.shaderCache;
  47248. let stage = cache.get( code );
  47249. if ( stage === undefined ) {
  47250. stage = new WebGLShaderStage( code );
  47251. cache.set( code, stage );
  47252. }
  47253. return stage;
  47254. }
  47255. }
  47256. class WebGLShaderStage {
  47257. constructor( code ) {
  47258. this.id = _id ++;
  47259. this.code = code;
  47260. this.usedTimes = 0;
  47261. }
  47262. }
  47263. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  47264. const _programLayers = new Layers();
  47265. const _customShaders = new WebGLShaderCache();
  47266. const _activeChannels = new Set();
  47267. const programs = [];
  47268. const programsMap = new Map();
  47269. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47270. let precision = capabilities.precision;
  47271. const shaderIDs = {
  47272. MeshDepthMaterial: 'depth',
  47273. MeshDistanceMaterial: 'distance',
  47274. MeshNormalMaterial: 'normal',
  47275. MeshBasicMaterial: 'basic',
  47276. MeshLambertMaterial: 'lambert',
  47277. MeshPhongMaterial: 'phong',
  47278. MeshToonMaterial: 'toon',
  47279. MeshStandardMaterial: 'physical',
  47280. MeshPhysicalMaterial: 'physical',
  47281. MeshMatcapMaterial: 'matcap',
  47282. LineBasicMaterial: 'basic',
  47283. LineDashedMaterial: 'dashed',
  47284. PointsMaterial: 'points',
  47285. ShadowMaterial: 'shadow',
  47286. SpriteMaterial: 'sprite'
  47287. };
  47288. function getChannel( value ) {
  47289. _activeChannels.add( value );
  47290. if ( value === 0 ) return 'uv';
  47291. return `uv${ value }`;
  47292. }
  47293. function getParameters( material, lights, shadows, scene, object ) {
  47294. const fog = scene.fog;
  47295. const geometry = object.geometry;
  47296. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  47297. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  47298. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47299. const shaderID = shaderIDs[ material.type ];
  47300. // heuristics to create shader parameters according to lights in the scene
  47301. // (not to blow over maxLights budget)
  47302. if ( material.precision !== null ) {
  47303. precision = capabilities.getMaxPrecision( material.precision );
  47304. if ( precision !== material.precision ) {
  47305. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47306. }
  47307. }
  47308. //
  47309. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47310. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47311. let morphTextureStride = 0;
  47312. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47313. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47314. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47315. //
  47316. let vertexShader, fragmentShader;
  47317. let customVertexShaderID, customFragmentShaderID;
  47318. if ( shaderID ) {
  47319. const shader = ShaderLib[ shaderID ];
  47320. vertexShader = shader.vertexShader;
  47321. fragmentShader = shader.fragmentShader;
  47322. } else {
  47323. vertexShader = material.vertexShader;
  47324. fragmentShader = material.fragmentShader;
  47325. _customShaders.update( material );
  47326. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47327. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47328. }
  47329. const currentRenderTarget = renderer.getRenderTarget();
  47330. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47331. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47332. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47333. const HAS_MAP = !! material.map;
  47334. const HAS_MATCAP = !! material.matcap;
  47335. const HAS_ENVMAP = !! envMap;
  47336. const HAS_AOMAP = !! material.aoMap;
  47337. const HAS_LIGHTMAP = !! material.lightMap;
  47338. const HAS_BUMPMAP = !! material.bumpMap;
  47339. const HAS_NORMALMAP = !! material.normalMap;
  47340. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47341. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47342. const HAS_METALNESSMAP = !! material.metalnessMap;
  47343. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47344. const HAS_ANISOTROPY = material.anisotropy > 0;
  47345. const HAS_CLEARCOAT = material.clearcoat > 0;
  47346. const HAS_DISPERSION = material.dispersion > 0;
  47347. const HAS_IRIDESCENCE = material.iridescence > 0;
  47348. const HAS_SHEEN = material.sheen > 0;
  47349. const HAS_TRANSMISSION = material.transmission > 0;
  47350. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47351. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47352. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47353. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47354. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47355. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47356. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47357. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47358. const HAS_SPECULARMAP = !! material.specularMap;
  47359. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47360. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47361. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47362. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47363. const HAS_GRADIENTMAP = !! material.gradientMap;
  47364. const HAS_ALPHAMAP = !! material.alphaMap;
  47365. const HAS_ALPHATEST = material.alphaTest > 0;
  47366. const HAS_ALPHAHASH = !! material.alphaHash;
  47367. const HAS_EXTENSIONS = !! material.extensions;
  47368. let toneMapping = NoToneMapping;
  47369. if ( material.toneMapped ) {
  47370. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47371. toneMapping = renderer.toneMapping;
  47372. }
  47373. }
  47374. const parameters = {
  47375. shaderID: shaderID,
  47376. shaderType: material.type,
  47377. shaderName: material.name,
  47378. vertexShader: vertexShader,
  47379. fragmentShader: fragmentShader,
  47380. defines: material.defines,
  47381. customVertexShaderID: customVertexShaderID,
  47382. customFragmentShaderID: customFragmentShaderID,
  47383. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47384. glslVersion: material.glslVersion,
  47385. precision: precision,
  47386. batching: IS_BATCHEDMESH,
  47387. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47388. instancing: IS_INSTANCEDMESH,
  47389. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47390. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47391. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47392. alphaToCoverage: !! material.alphaToCoverage,
  47393. map: HAS_MAP,
  47394. matcap: HAS_MATCAP,
  47395. envMap: HAS_ENVMAP,
  47396. envMapMode: HAS_ENVMAP && envMap.mapping,
  47397. envMapCubeUVHeight: envMapCubeUVHeight,
  47398. aoMap: HAS_AOMAP,
  47399. lightMap: HAS_LIGHTMAP,
  47400. bumpMap: HAS_BUMPMAP,
  47401. normalMap: HAS_NORMALMAP,
  47402. displacementMap: HAS_DISPLACEMENTMAP,
  47403. emissiveMap: HAS_EMISSIVEMAP,
  47404. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47405. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47406. metalnessMap: HAS_METALNESSMAP,
  47407. roughnessMap: HAS_ROUGHNESSMAP,
  47408. anisotropy: HAS_ANISOTROPY,
  47409. anisotropyMap: HAS_ANISOTROPYMAP,
  47410. clearcoat: HAS_CLEARCOAT,
  47411. clearcoatMap: HAS_CLEARCOATMAP,
  47412. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47413. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47414. dispersion: HAS_DISPERSION,
  47415. iridescence: HAS_IRIDESCENCE,
  47416. iridescenceMap: HAS_IRIDESCENCEMAP,
  47417. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47418. sheen: HAS_SHEEN,
  47419. sheenColorMap: HAS_SHEEN_COLORMAP,
  47420. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47421. specularMap: HAS_SPECULARMAP,
  47422. specularColorMap: HAS_SPECULAR_COLORMAP,
  47423. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47424. transmission: HAS_TRANSMISSION,
  47425. transmissionMap: HAS_TRANSMISSIONMAP,
  47426. thicknessMap: HAS_THICKNESSMAP,
  47427. gradientMap: HAS_GRADIENTMAP,
  47428. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47429. alphaMap: HAS_ALPHAMAP,
  47430. alphaTest: HAS_ALPHATEST,
  47431. alphaHash: HAS_ALPHAHASH,
  47432. combine: material.combine,
  47433. //
  47434. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47435. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47436. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47437. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47438. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47439. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47440. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47441. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47442. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47443. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47444. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47445. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47446. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47447. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47448. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47449. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47450. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47451. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47452. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47453. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47454. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47455. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47456. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47457. //
  47458. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47459. vertexColors: material.vertexColors,
  47460. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47461. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47462. fog: !! fog,
  47463. useFog: material.fog === true,
  47464. fogExp2: ( !! fog && fog.isFogExp2 ),
  47465. flatShading: ( material.flatShading === true && material.wireframe === false ),
  47466. sizeAttenuation: material.sizeAttenuation === true,
  47467. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47468. reversedDepthBuffer: reversedDepthBuffer,
  47469. skinning: object.isSkinnedMesh === true,
  47470. morphTargets: geometry.morphAttributes.position !== undefined,
  47471. morphNormals: geometry.morphAttributes.normal !== undefined,
  47472. morphColors: geometry.morphAttributes.color !== undefined,
  47473. morphTargetsCount: morphTargetsCount,
  47474. morphTextureStride: morphTextureStride,
  47475. numDirLights: lights.directional.length,
  47476. numPointLights: lights.point.length,
  47477. numSpotLights: lights.spot.length,
  47478. numSpotLightMaps: lights.spotLightMap.length,
  47479. numRectAreaLights: lights.rectArea.length,
  47480. numHemiLights: lights.hemi.length,
  47481. numDirLightShadows: lights.directionalShadowMap.length,
  47482. numPointLightShadows: lights.pointShadowMap.length,
  47483. numSpotLightShadows: lights.spotShadowMap.length,
  47484. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47485. numLightProbes: lights.numLightProbes,
  47486. numClippingPlanes: clipping.numPlanes,
  47487. numClipIntersection: clipping.numIntersection,
  47488. dithering: material.dithering,
  47489. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47490. shadowMapType: renderer.shadowMap.type,
  47491. toneMapping: toneMapping,
  47492. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47493. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47494. premultipliedAlpha: material.premultipliedAlpha,
  47495. doubleSided: material.side === DoubleSide,
  47496. flipSided: material.side === BackSide,
  47497. useDepthPacking: material.depthPacking >= 0,
  47498. depthPacking: material.depthPacking || 0,
  47499. index0AttributeName: material.index0AttributeName,
  47500. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47501. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47502. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47503. customProgramCacheKey: material.customProgramCacheKey()
  47504. };
  47505. // the usage of getChannel() determines the active texture channels for this shader
  47506. parameters.vertexUv1s = _activeChannels.has( 1 );
  47507. parameters.vertexUv2s = _activeChannels.has( 2 );
  47508. parameters.vertexUv3s = _activeChannels.has( 3 );
  47509. _activeChannels.clear();
  47510. return parameters;
  47511. }
  47512. function getProgramCacheKey( parameters ) {
  47513. const array = [];
  47514. if ( parameters.shaderID ) {
  47515. array.push( parameters.shaderID );
  47516. } else {
  47517. array.push( parameters.customVertexShaderID );
  47518. array.push( parameters.customFragmentShaderID );
  47519. }
  47520. if ( parameters.defines !== undefined ) {
  47521. for ( const name in parameters.defines ) {
  47522. array.push( name );
  47523. array.push( parameters.defines[ name ] );
  47524. }
  47525. }
  47526. if ( parameters.isRawShaderMaterial === false ) {
  47527. getProgramCacheKeyParameters( array, parameters );
  47528. getProgramCacheKeyBooleans( array, parameters );
  47529. array.push( renderer.outputColorSpace );
  47530. }
  47531. array.push( parameters.customProgramCacheKey );
  47532. return array.join();
  47533. }
  47534. function getProgramCacheKeyParameters( array, parameters ) {
  47535. array.push( parameters.precision );
  47536. array.push( parameters.outputColorSpace );
  47537. array.push( parameters.envMapMode );
  47538. array.push( parameters.envMapCubeUVHeight );
  47539. array.push( parameters.mapUv );
  47540. array.push( parameters.alphaMapUv );
  47541. array.push( parameters.lightMapUv );
  47542. array.push( parameters.aoMapUv );
  47543. array.push( parameters.bumpMapUv );
  47544. array.push( parameters.normalMapUv );
  47545. array.push( parameters.displacementMapUv );
  47546. array.push( parameters.emissiveMapUv );
  47547. array.push( parameters.metalnessMapUv );
  47548. array.push( parameters.roughnessMapUv );
  47549. array.push( parameters.anisotropyMapUv );
  47550. array.push( parameters.clearcoatMapUv );
  47551. array.push( parameters.clearcoatNormalMapUv );
  47552. array.push( parameters.clearcoatRoughnessMapUv );
  47553. array.push( parameters.iridescenceMapUv );
  47554. array.push( parameters.iridescenceThicknessMapUv );
  47555. array.push( parameters.sheenColorMapUv );
  47556. array.push( parameters.sheenRoughnessMapUv );
  47557. array.push( parameters.specularMapUv );
  47558. array.push( parameters.specularColorMapUv );
  47559. array.push( parameters.specularIntensityMapUv );
  47560. array.push( parameters.transmissionMapUv );
  47561. array.push( parameters.thicknessMapUv );
  47562. array.push( parameters.combine );
  47563. array.push( parameters.fogExp2 );
  47564. array.push( parameters.sizeAttenuation );
  47565. array.push( parameters.morphTargetsCount );
  47566. array.push( parameters.morphAttributeCount );
  47567. array.push( parameters.numDirLights );
  47568. array.push( parameters.numPointLights );
  47569. array.push( parameters.numSpotLights );
  47570. array.push( parameters.numSpotLightMaps );
  47571. array.push( parameters.numHemiLights );
  47572. array.push( parameters.numRectAreaLights );
  47573. array.push( parameters.numDirLightShadows );
  47574. array.push( parameters.numPointLightShadows );
  47575. array.push( parameters.numSpotLightShadows );
  47576. array.push( parameters.numSpotLightShadowsWithMaps );
  47577. array.push( parameters.numLightProbes );
  47578. array.push( parameters.shadowMapType );
  47579. array.push( parameters.toneMapping );
  47580. array.push( parameters.numClippingPlanes );
  47581. array.push( parameters.numClipIntersection );
  47582. array.push( parameters.depthPacking );
  47583. }
  47584. function getProgramCacheKeyBooleans( array, parameters ) {
  47585. _programLayers.disableAll();
  47586. if ( parameters.instancing )
  47587. _programLayers.enable( 0 );
  47588. if ( parameters.instancingColor )
  47589. _programLayers.enable( 1 );
  47590. if ( parameters.instancingMorph )
  47591. _programLayers.enable( 2 );
  47592. if ( parameters.matcap )
  47593. _programLayers.enable( 3 );
  47594. if ( parameters.envMap )
  47595. _programLayers.enable( 4 );
  47596. if ( parameters.normalMapObjectSpace )
  47597. _programLayers.enable( 5 );
  47598. if ( parameters.normalMapTangentSpace )
  47599. _programLayers.enable( 6 );
  47600. if ( parameters.clearcoat )
  47601. _programLayers.enable( 7 );
  47602. if ( parameters.iridescence )
  47603. _programLayers.enable( 8 );
  47604. if ( parameters.alphaTest )
  47605. _programLayers.enable( 9 );
  47606. if ( parameters.vertexColors )
  47607. _programLayers.enable( 10 );
  47608. if ( parameters.vertexAlphas )
  47609. _programLayers.enable( 11 );
  47610. if ( parameters.vertexUv1s )
  47611. _programLayers.enable( 12 );
  47612. if ( parameters.vertexUv2s )
  47613. _programLayers.enable( 13 );
  47614. if ( parameters.vertexUv3s )
  47615. _programLayers.enable( 14 );
  47616. if ( parameters.vertexTangents )
  47617. _programLayers.enable( 15 );
  47618. if ( parameters.anisotropy )
  47619. _programLayers.enable( 16 );
  47620. if ( parameters.alphaHash )
  47621. _programLayers.enable( 17 );
  47622. if ( parameters.batching )
  47623. _programLayers.enable( 18 );
  47624. if ( parameters.dispersion )
  47625. _programLayers.enable( 19 );
  47626. if ( parameters.batchingColor )
  47627. _programLayers.enable( 20 );
  47628. if ( parameters.gradientMap )
  47629. _programLayers.enable( 21 );
  47630. array.push( _programLayers.mask );
  47631. _programLayers.disableAll();
  47632. if ( parameters.fog )
  47633. _programLayers.enable( 0 );
  47634. if ( parameters.useFog )
  47635. _programLayers.enable( 1 );
  47636. if ( parameters.flatShading )
  47637. _programLayers.enable( 2 );
  47638. if ( parameters.logarithmicDepthBuffer )
  47639. _programLayers.enable( 3 );
  47640. if ( parameters.reversedDepthBuffer )
  47641. _programLayers.enable( 4 );
  47642. if ( parameters.skinning )
  47643. _programLayers.enable( 5 );
  47644. if ( parameters.morphTargets )
  47645. _programLayers.enable( 6 );
  47646. if ( parameters.morphNormals )
  47647. _programLayers.enable( 7 );
  47648. if ( parameters.morphColors )
  47649. _programLayers.enable( 8 );
  47650. if ( parameters.premultipliedAlpha )
  47651. _programLayers.enable( 9 );
  47652. if ( parameters.shadowMapEnabled )
  47653. _programLayers.enable( 10 );
  47654. if ( parameters.doubleSided )
  47655. _programLayers.enable( 11 );
  47656. if ( parameters.flipSided )
  47657. _programLayers.enable( 12 );
  47658. if ( parameters.useDepthPacking )
  47659. _programLayers.enable( 13 );
  47660. if ( parameters.dithering )
  47661. _programLayers.enable( 14 );
  47662. if ( parameters.transmission )
  47663. _programLayers.enable( 15 );
  47664. if ( parameters.sheen )
  47665. _programLayers.enable( 16 );
  47666. if ( parameters.opaque )
  47667. _programLayers.enable( 17 );
  47668. if ( parameters.pointsUvs )
  47669. _programLayers.enable( 18 );
  47670. if ( parameters.decodeVideoTexture )
  47671. _programLayers.enable( 19 );
  47672. if ( parameters.decodeVideoTextureEmissive )
  47673. _programLayers.enable( 20 );
  47674. if ( parameters.alphaToCoverage )
  47675. _programLayers.enable( 21 );
  47676. array.push( _programLayers.mask );
  47677. }
  47678. function getUniforms( material ) {
  47679. const shaderID = shaderIDs[ material.type ];
  47680. let uniforms;
  47681. if ( shaderID ) {
  47682. const shader = ShaderLib[ shaderID ];
  47683. uniforms = UniformsUtils.clone( shader.uniforms );
  47684. } else {
  47685. uniforms = material.uniforms;
  47686. }
  47687. return uniforms;
  47688. }
  47689. function acquireProgram( parameters, cacheKey ) {
  47690. let program = programsMap.get( cacheKey );
  47691. if ( program !== undefined ) {
  47692. ++ program.usedTimes;
  47693. } else {
  47694. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47695. programs.push( program );
  47696. programsMap.set( cacheKey, program );
  47697. }
  47698. return program;
  47699. }
  47700. function releaseProgram( program ) {
  47701. if ( -- program.usedTimes === 0 ) {
  47702. // Remove from unordered set
  47703. const i = programs.indexOf( program );
  47704. programs[ i ] = programs[ programs.length - 1 ];
  47705. programs.pop();
  47706. // Remove from map
  47707. programsMap.delete( program.cacheKey );
  47708. // Free WebGL resources
  47709. program.destroy();
  47710. }
  47711. }
  47712. function releaseShaderCache( material ) {
  47713. _customShaders.remove( material );
  47714. }
  47715. function dispose() {
  47716. _customShaders.dispose();
  47717. }
  47718. return {
  47719. getParameters: getParameters,
  47720. getProgramCacheKey: getProgramCacheKey,
  47721. getUniforms: getUniforms,
  47722. acquireProgram: acquireProgram,
  47723. releaseProgram: releaseProgram,
  47724. releaseShaderCache: releaseShaderCache,
  47725. // Exposed for resource monitoring & error feedback via renderer.info:
  47726. programs: programs,
  47727. dispose: dispose
  47728. };
  47729. }
  47730. function WebGLProperties() {
  47731. let properties = new WeakMap();
  47732. function has( object ) {
  47733. return properties.has( object );
  47734. }
  47735. function get( object ) {
  47736. let map = properties.get( object );
  47737. if ( map === undefined ) {
  47738. map = {};
  47739. properties.set( object, map );
  47740. }
  47741. return map;
  47742. }
  47743. function remove( object ) {
  47744. properties.delete( object );
  47745. }
  47746. function update( object, key, value ) {
  47747. properties.get( object )[ key ] = value;
  47748. }
  47749. function dispose() {
  47750. properties = new WeakMap();
  47751. }
  47752. return {
  47753. has: has,
  47754. get: get,
  47755. remove: remove,
  47756. update: update,
  47757. dispose: dispose
  47758. };
  47759. }
  47760. function painterSortStable( a, b ) {
  47761. if ( a.groupOrder !== b.groupOrder ) {
  47762. return a.groupOrder - b.groupOrder;
  47763. } else if ( a.renderOrder !== b.renderOrder ) {
  47764. return a.renderOrder - b.renderOrder;
  47765. } else if ( a.material.id !== b.material.id ) {
  47766. return a.material.id - b.material.id;
  47767. } else if ( a.materialVariant !== b.materialVariant ) {
  47768. return a.materialVariant - b.materialVariant;
  47769. } else if ( a.z !== b.z ) {
  47770. return a.z - b.z;
  47771. } else {
  47772. return a.id - b.id;
  47773. }
  47774. }
  47775. function reversePainterSortStable( a, b ) {
  47776. if ( a.groupOrder !== b.groupOrder ) {
  47777. return a.groupOrder - b.groupOrder;
  47778. } else if ( a.renderOrder !== b.renderOrder ) {
  47779. return a.renderOrder - b.renderOrder;
  47780. } else if ( a.z !== b.z ) {
  47781. return b.z - a.z;
  47782. } else {
  47783. return a.id - b.id;
  47784. }
  47785. }
  47786. function WebGLRenderList() {
  47787. const renderItems = [];
  47788. let renderItemsIndex = 0;
  47789. const opaque = [];
  47790. const transmissive = [];
  47791. const transparent = [];
  47792. function init() {
  47793. renderItemsIndex = 0;
  47794. opaque.length = 0;
  47795. transmissive.length = 0;
  47796. transparent.length = 0;
  47797. }
  47798. function materialVariant( object ) {
  47799. let variant = 0;
  47800. if ( object.isInstancedMesh ) variant += 2;
  47801. if ( object.isSkinnedMesh ) variant += 1;
  47802. return variant;
  47803. }
  47804. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47805. let renderItem = renderItems[ renderItemsIndex ];
  47806. if ( renderItem === undefined ) {
  47807. renderItem = {
  47808. id: object.id,
  47809. object: object,
  47810. geometry: geometry,
  47811. material: material,
  47812. materialVariant: materialVariant( object ),
  47813. groupOrder: groupOrder,
  47814. renderOrder: object.renderOrder,
  47815. z: z,
  47816. group: group
  47817. };
  47818. renderItems[ renderItemsIndex ] = renderItem;
  47819. } else {
  47820. renderItem.id = object.id;
  47821. renderItem.object = object;
  47822. renderItem.geometry = geometry;
  47823. renderItem.material = material;
  47824. renderItem.materialVariant = materialVariant( object );
  47825. renderItem.groupOrder = groupOrder;
  47826. renderItem.renderOrder = object.renderOrder;
  47827. renderItem.z = z;
  47828. renderItem.group = group;
  47829. }
  47830. renderItemsIndex ++;
  47831. return renderItem;
  47832. }
  47833. function push( object, geometry, material, groupOrder, z, group ) {
  47834. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47835. if ( material.transmission > 0.0 ) {
  47836. transmissive.push( renderItem );
  47837. } else if ( material.transparent === true ) {
  47838. transparent.push( renderItem );
  47839. } else {
  47840. opaque.push( renderItem );
  47841. }
  47842. }
  47843. function unshift( object, geometry, material, groupOrder, z, group ) {
  47844. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47845. if ( material.transmission > 0.0 ) {
  47846. transmissive.unshift( renderItem );
  47847. } else if ( material.transparent === true ) {
  47848. transparent.unshift( renderItem );
  47849. } else {
  47850. opaque.unshift( renderItem );
  47851. }
  47852. }
  47853. function sort( customOpaqueSort, customTransparentSort ) {
  47854. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47855. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47856. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47857. }
  47858. function finish() {
  47859. // Clear references from inactive renderItems in the list
  47860. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47861. const renderItem = renderItems[ i ];
  47862. if ( renderItem.id === null ) break;
  47863. renderItem.id = null;
  47864. renderItem.object = null;
  47865. renderItem.geometry = null;
  47866. renderItem.material = null;
  47867. renderItem.group = null;
  47868. }
  47869. }
  47870. return {
  47871. opaque: opaque,
  47872. transmissive: transmissive,
  47873. transparent: transparent,
  47874. init: init,
  47875. push: push,
  47876. unshift: unshift,
  47877. finish: finish,
  47878. sort: sort
  47879. };
  47880. }
  47881. function WebGLRenderLists() {
  47882. let lists = new WeakMap();
  47883. function get( scene, renderCallDepth ) {
  47884. const listArray = lists.get( scene );
  47885. let list;
  47886. if ( listArray === undefined ) {
  47887. list = new WebGLRenderList();
  47888. lists.set( scene, [ list ] );
  47889. } else {
  47890. if ( renderCallDepth >= listArray.length ) {
  47891. list = new WebGLRenderList();
  47892. listArray.push( list );
  47893. } else {
  47894. list = listArray[ renderCallDepth ];
  47895. }
  47896. }
  47897. return list;
  47898. }
  47899. function dispose() {
  47900. lists = new WeakMap();
  47901. }
  47902. return {
  47903. get: get,
  47904. dispose: dispose
  47905. };
  47906. }
  47907. function UniformsCache() {
  47908. const lights = {};
  47909. return {
  47910. get: function ( light ) {
  47911. if ( lights[ light.id ] !== undefined ) {
  47912. return lights[ light.id ];
  47913. }
  47914. let uniforms;
  47915. switch ( light.type ) {
  47916. case 'DirectionalLight':
  47917. uniforms = {
  47918. direction: new Vector3(),
  47919. color: new Color()
  47920. };
  47921. break;
  47922. case 'SpotLight':
  47923. uniforms = {
  47924. position: new Vector3(),
  47925. direction: new Vector3(),
  47926. color: new Color(),
  47927. distance: 0,
  47928. coneCos: 0,
  47929. penumbraCos: 0,
  47930. decay: 0
  47931. };
  47932. break;
  47933. case 'PointLight':
  47934. uniforms = {
  47935. position: new Vector3(),
  47936. color: new Color(),
  47937. distance: 0,
  47938. decay: 0
  47939. };
  47940. break;
  47941. case 'HemisphereLight':
  47942. uniforms = {
  47943. direction: new Vector3(),
  47944. skyColor: new Color(),
  47945. groundColor: new Color()
  47946. };
  47947. break;
  47948. case 'RectAreaLight':
  47949. uniforms = {
  47950. color: new Color(),
  47951. position: new Vector3(),
  47952. halfWidth: new Vector3(),
  47953. halfHeight: new Vector3()
  47954. };
  47955. break;
  47956. }
  47957. lights[ light.id ] = uniforms;
  47958. return uniforms;
  47959. }
  47960. };
  47961. }
  47962. function ShadowUniformsCache() {
  47963. const lights = {};
  47964. return {
  47965. get: function ( light ) {
  47966. if ( lights[ light.id ] !== undefined ) {
  47967. return lights[ light.id ];
  47968. }
  47969. let uniforms;
  47970. switch ( light.type ) {
  47971. case 'DirectionalLight':
  47972. uniforms = {
  47973. shadowIntensity: 1,
  47974. shadowBias: 0,
  47975. shadowNormalBias: 0,
  47976. shadowRadius: 1,
  47977. shadowMapSize: new Vector2()
  47978. };
  47979. break;
  47980. case 'SpotLight':
  47981. uniforms = {
  47982. shadowIntensity: 1,
  47983. shadowBias: 0,
  47984. shadowNormalBias: 0,
  47985. shadowRadius: 1,
  47986. shadowMapSize: new Vector2()
  47987. };
  47988. break;
  47989. case 'PointLight':
  47990. uniforms = {
  47991. shadowIntensity: 1,
  47992. shadowBias: 0,
  47993. shadowNormalBias: 0,
  47994. shadowRadius: 1,
  47995. shadowMapSize: new Vector2(),
  47996. shadowCameraNear: 1,
  47997. shadowCameraFar: 1000
  47998. };
  47999. break;
  48000. // TODO (abelnation): set RectAreaLight shadow uniforms
  48001. }
  48002. lights[ light.id ] = uniforms;
  48003. return uniforms;
  48004. }
  48005. };
  48006. }
  48007. let nextVersion = 0;
  48008. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  48009. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  48010. }
  48011. function WebGLLights( extensions ) {
  48012. const cache = new UniformsCache();
  48013. const shadowCache = ShadowUniformsCache();
  48014. const state = {
  48015. version: 0,
  48016. hash: {
  48017. directionalLength: -1,
  48018. pointLength: -1,
  48019. spotLength: -1,
  48020. rectAreaLength: -1,
  48021. hemiLength: -1,
  48022. numDirectionalShadows: -1,
  48023. numPointShadows: -1,
  48024. numSpotShadows: -1,
  48025. numSpotMaps: -1,
  48026. numLightProbes: -1
  48027. },
  48028. ambient: [ 0, 0, 0 ],
  48029. probe: [],
  48030. directional: [],
  48031. directionalShadow: [],
  48032. directionalShadowMap: [],
  48033. directionalShadowMatrix: [],
  48034. spot: [],
  48035. spotLightMap: [],
  48036. spotShadow: [],
  48037. spotShadowMap: [],
  48038. spotLightMatrix: [],
  48039. rectArea: [],
  48040. rectAreaLTC1: null,
  48041. rectAreaLTC2: null,
  48042. point: [],
  48043. pointShadow: [],
  48044. pointShadowMap: [],
  48045. pointShadowMatrix: [],
  48046. hemi: [],
  48047. numSpotLightShadowsWithMaps: 0,
  48048. numLightProbes: 0
  48049. };
  48050. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  48051. const vector3 = new Vector3();
  48052. const matrix4 = new Matrix4();
  48053. const matrix42 = new Matrix4();
  48054. function setup( lights ) {
  48055. let r = 0, g = 0, b = 0;
  48056. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  48057. let directionalLength = 0;
  48058. let pointLength = 0;
  48059. let spotLength = 0;
  48060. let rectAreaLength = 0;
  48061. let hemiLength = 0;
  48062. let numDirectionalShadows = 0;
  48063. let numPointShadows = 0;
  48064. let numSpotShadows = 0;
  48065. let numSpotMaps = 0;
  48066. let numSpotShadowsWithMaps = 0;
  48067. let numLightProbes = 0;
  48068. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  48069. lights.sort( shadowCastingAndTexturingLightsFirst );
  48070. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48071. const light = lights[ i ];
  48072. const color = light.color;
  48073. const intensity = light.intensity;
  48074. const distance = light.distance;
  48075. let shadowMap = null;
  48076. if ( light.shadow && light.shadow.map ) {
  48077. if ( light.shadow.map.texture.format === RGFormat ) {
  48078. // VSM uses color texture with blurred mean/std_dev
  48079. shadowMap = light.shadow.map.texture;
  48080. } else {
  48081. // Other types use depth texture
  48082. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  48083. }
  48084. }
  48085. if ( light.isAmbientLight ) {
  48086. r += color.r * intensity;
  48087. g += color.g * intensity;
  48088. b += color.b * intensity;
  48089. } else if ( light.isLightProbe ) {
  48090. for ( let j = 0; j < 9; j ++ ) {
  48091. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  48092. }
  48093. numLightProbes ++;
  48094. } else if ( light.isDirectionalLight ) {
  48095. const uniforms = cache.get( light );
  48096. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48097. if ( light.castShadow ) {
  48098. const shadow = light.shadow;
  48099. const shadowUniforms = shadowCache.get( light );
  48100. shadowUniforms.shadowIntensity = shadow.intensity;
  48101. shadowUniforms.shadowBias = shadow.bias;
  48102. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48103. shadowUniforms.shadowRadius = shadow.radius;
  48104. shadowUniforms.shadowMapSize = shadow.mapSize;
  48105. state.directionalShadow[ directionalLength ] = shadowUniforms;
  48106. state.directionalShadowMap[ directionalLength ] = shadowMap;
  48107. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  48108. numDirectionalShadows ++;
  48109. }
  48110. state.directional[ directionalLength ] = uniforms;
  48111. directionalLength ++;
  48112. } else if ( light.isSpotLight ) {
  48113. const uniforms = cache.get( light );
  48114. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48115. uniforms.color.copy( color ).multiplyScalar( intensity );
  48116. uniforms.distance = distance;
  48117. uniforms.coneCos = Math.cos( light.angle );
  48118. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  48119. uniforms.decay = light.decay;
  48120. state.spot[ spotLength ] = uniforms;
  48121. const shadow = light.shadow;
  48122. if ( light.map ) {
  48123. state.spotLightMap[ numSpotMaps ] = light.map;
  48124. numSpotMaps ++;
  48125. // make sure the lightMatrix is up to date
  48126. // TODO : do it if required only
  48127. shadow.updateMatrices( light );
  48128. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  48129. }
  48130. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  48131. if ( light.castShadow ) {
  48132. const shadowUniforms = shadowCache.get( light );
  48133. shadowUniforms.shadowIntensity = shadow.intensity;
  48134. shadowUniforms.shadowBias = shadow.bias;
  48135. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48136. shadowUniforms.shadowRadius = shadow.radius;
  48137. shadowUniforms.shadowMapSize = shadow.mapSize;
  48138. state.spotShadow[ spotLength ] = shadowUniforms;
  48139. state.spotShadowMap[ spotLength ] = shadowMap;
  48140. numSpotShadows ++;
  48141. }
  48142. spotLength ++;
  48143. } else if ( light.isRectAreaLight ) {
  48144. const uniforms = cache.get( light );
  48145. uniforms.color.copy( color ).multiplyScalar( intensity );
  48146. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48147. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48148. state.rectArea[ rectAreaLength ] = uniforms;
  48149. rectAreaLength ++;
  48150. } else if ( light.isPointLight ) {
  48151. const uniforms = cache.get( light );
  48152. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48153. uniforms.distance = light.distance;
  48154. uniforms.decay = light.decay;
  48155. if ( light.castShadow ) {
  48156. const shadow = light.shadow;
  48157. const shadowUniforms = shadowCache.get( light );
  48158. shadowUniforms.shadowIntensity = shadow.intensity;
  48159. shadowUniforms.shadowBias = shadow.bias;
  48160. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48161. shadowUniforms.shadowRadius = shadow.radius;
  48162. shadowUniforms.shadowMapSize = shadow.mapSize;
  48163. shadowUniforms.shadowCameraNear = shadow.camera.near;
  48164. shadowUniforms.shadowCameraFar = shadow.camera.far;
  48165. state.pointShadow[ pointLength ] = shadowUniforms;
  48166. state.pointShadowMap[ pointLength ] = shadowMap;
  48167. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  48168. numPointShadows ++;
  48169. }
  48170. state.point[ pointLength ] = uniforms;
  48171. pointLength ++;
  48172. } else if ( light.isHemisphereLight ) {
  48173. const uniforms = cache.get( light );
  48174. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  48175. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  48176. state.hemi[ hemiLength ] = uniforms;
  48177. hemiLength ++;
  48178. }
  48179. }
  48180. if ( rectAreaLength > 0 ) {
  48181. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  48182. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  48183. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  48184. } else {
  48185. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  48186. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  48187. }
  48188. }
  48189. state.ambient[ 0 ] = r;
  48190. state.ambient[ 1 ] = g;
  48191. state.ambient[ 2 ] = b;
  48192. const hash = state.hash;
  48193. if ( hash.directionalLength !== directionalLength ||
  48194. hash.pointLength !== pointLength ||
  48195. hash.spotLength !== spotLength ||
  48196. hash.rectAreaLength !== rectAreaLength ||
  48197. hash.hemiLength !== hemiLength ||
  48198. hash.numDirectionalShadows !== numDirectionalShadows ||
  48199. hash.numPointShadows !== numPointShadows ||
  48200. hash.numSpotShadows !== numSpotShadows ||
  48201. hash.numSpotMaps !== numSpotMaps ||
  48202. hash.numLightProbes !== numLightProbes ) {
  48203. state.directional.length = directionalLength;
  48204. state.spot.length = spotLength;
  48205. state.rectArea.length = rectAreaLength;
  48206. state.point.length = pointLength;
  48207. state.hemi.length = hemiLength;
  48208. state.directionalShadow.length = numDirectionalShadows;
  48209. state.directionalShadowMap.length = numDirectionalShadows;
  48210. state.pointShadow.length = numPointShadows;
  48211. state.pointShadowMap.length = numPointShadows;
  48212. state.spotShadow.length = numSpotShadows;
  48213. state.spotShadowMap.length = numSpotShadows;
  48214. state.directionalShadowMatrix.length = numDirectionalShadows;
  48215. state.pointShadowMatrix.length = numPointShadows;
  48216. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48217. state.spotLightMap.length = numSpotMaps;
  48218. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48219. state.numLightProbes = numLightProbes;
  48220. hash.directionalLength = directionalLength;
  48221. hash.pointLength = pointLength;
  48222. hash.spotLength = spotLength;
  48223. hash.rectAreaLength = rectAreaLength;
  48224. hash.hemiLength = hemiLength;
  48225. hash.numDirectionalShadows = numDirectionalShadows;
  48226. hash.numPointShadows = numPointShadows;
  48227. hash.numSpotShadows = numSpotShadows;
  48228. hash.numSpotMaps = numSpotMaps;
  48229. hash.numLightProbes = numLightProbes;
  48230. state.version = nextVersion ++;
  48231. }
  48232. }
  48233. function setupView( lights, camera ) {
  48234. let directionalLength = 0;
  48235. let pointLength = 0;
  48236. let spotLength = 0;
  48237. let rectAreaLength = 0;
  48238. let hemiLength = 0;
  48239. const viewMatrix = camera.matrixWorldInverse;
  48240. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48241. const light = lights[ i ];
  48242. if ( light.isDirectionalLight ) {
  48243. const uniforms = state.directional[ directionalLength ];
  48244. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48245. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48246. uniforms.direction.sub( vector3 );
  48247. uniforms.direction.transformDirection( viewMatrix );
  48248. directionalLength ++;
  48249. } else if ( light.isSpotLight ) {
  48250. const uniforms = state.spot[ spotLength ];
  48251. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48252. uniforms.position.applyMatrix4( viewMatrix );
  48253. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48254. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48255. uniforms.direction.sub( vector3 );
  48256. uniforms.direction.transformDirection( viewMatrix );
  48257. spotLength ++;
  48258. } else if ( light.isRectAreaLight ) {
  48259. const uniforms = state.rectArea[ rectAreaLength ];
  48260. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48261. uniforms.position.applyMatrix4( viewMatrix );
  48262. // extract local rotation of light to derive width/height half vectors
  48263. matrix42.identity();
  48264. matrix4.copy( light.matrixWorld );
  48265. matrix4.premultiply( viewMatrix );
  48266. matrix42.extractRotation( matrix4 );
  48267. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48268. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48269. uniforms.halfWidth.applyMatrix4( matrix42 );
  48270. uniforms.halfHeight.applyMatrix4( matrix42 );
  48271. rectAreaLength ++;
  48272. } else if ( light.isPointLight ) {
  48273. const uniforms = state.point[ pointLength ];
  48274. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48275. uniforms.position.applyMatrix4( viewMatrix );
  48276. pointLength ++;
  48277. } else if ( light.isHemisphereLight ) {
  48278. const uniforms = state.hemi[ hemiLength ];
  48279. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48280. uniforms.direction.transformDirection( viewMatrix );
  48281. hemiLength ++;
  48282. }
  48283. }
  48284. }
  48285. return {
  48286. setup: setup,
  48287. setupView: setupView,
  48288. state: state
  48289. };
  48290. }
  48291. function WebGLRenderState( extensions ) {
  48292. const lights = new WebGLLights( extensions );
  48293. const lightsArray = [];
  48294. const shadowsArray = [];
  48295. function init( camera ) {
  48296. state.camera = camera;
  48297. lightsArray.length = 0;
  48298. shadowsArray.length = 0;
  48299. }
  48300. function pushLight( light ) {
  48301. lightsArray.push( light );
  48302. }
  48303. function pushShadow( shadowLight ) {
  48304. shadowsArray.push( shadowLight );
  48305. }
  48306. function setupLights() {
  48307. lights.setup( lightsArray );
  48308. }
  48309. function setupLightsView( camera ) {
  48310. lights.setupView( lightsArray, camera );
  48311. }
  48312. const state = {
  48313. lightsArray: lightsArray,
  48314. shadowsArray: shadowsArray,
  48315. camera: null,
  48316. lights: lights,
  48317. transmissionRenderTarget: {}
  48318. };
  48319. return {
  48320. init: init,
  48321. state: state,
  48322. setupLights: setupLights,
  48323. setupLightsView: setupLightsView,
  48324. pushLight: pushLight,
  48325. pushShadow: pushShadow
  48326. };
  48327. }
  48328. function WebGLRenderStates( extensions ) {
  48329. let renderStates = new WeakMap();
  48330. function get( scene, renderCallDepth = 0 ) {
  48331. const renderStateArray = renderStates.get( scene );
  48332. let renderState;
  48333. if ( renderStateArray === undefined ) {
  48334. renderState = new WebGLRenderState( extensions );
  48335. renderStates.set( scene, [ renderState ] );
  48336. } else {
  48337. if ( renderCallDepth >= renderStateArray.length ) {
  48338. renderState = new WebGLRenderState( extensions );
  48339. renderStateArray.push( renderState );
  48340. } else {
  48341. renderState = renderStateArray[ renderCallDepth ];
  48342. }
  48343. }
  48344. return renderState;
  48345. }
  48346. function dispose() {
  48347. renderStates = new WeakMap();
  48348. }
  48349. return {
  48350. get: get,
  48351. dispose: dispose
  48352. };
  48353. }
  48354. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48355. 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}";
  48356. const _cubeDirections = [
  48357. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  48358. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  48359. ];
  48360. const _cubeUps = [
  48361. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  48362. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  48363. ];
  48364. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  48365. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  48366. const _lookTarget = /*@__PURE__*/ new Vector3();
  48367. function WebGLShadowMap( renderer, objects, capabilities ) {
  48368. let _frustum = new Frustum();
  48369. const _shadowMapSize = new Vector2(),
  48370. _viewportSize = new Vector2(),
  48371. _viewport = new Vector4(),
  48372. _depthMaterial = new MeshDepthMaterial(),
  48373. _distanceMaterial = new MeshDistanceMaterial(),
  48374. _materialCache = {},
  48375. _maxTextureSize = capabilities.maxTextureSize;
  48376. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48377. const shadowMaterialVertical = new ShaderMaterial( {
  48378. defines: {
  48379. VSM_SAMPLES: 8
  48380. },
  48381. uniforms: {
  48382. shadow_pass: { value: null },
  48383. resolution: { value: new Vector2() },
  48384. radius: { value: 4.0 }
  48385. },
  48386. vertexShader: vertex,
  48387. fragmentShader: fragment
  48388. } );
  48389. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48390. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48391. const fullScreenTri = new BufferGeometry();
  48392. fullScreenTri.setAttribute(
  48393. 'position',
  48394. new BufferAttribute(
  48395. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48396. 3
  48397. )
  48398. );
  48399. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48400. const scope = this;
  48401. this.enabled = false;
  48402. this.autoUpdate = true;
  48403. this.needsUpdate = false;
  48404. this.type = PCFShadowMap;
  48405. let _previousType = this.type;
  48406. this.render = function ( lights, scene, camera ) {
  48407. if ( scope.enabled === false ) return;
  48408. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48409. if ( lights.length === 0 ) return;
  48410. if ( this.type === PCFSoftShadowMap ) {
  48411. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48412. this.type = PCFShadowMap;
  48413. }
  48414. const currentRenderTarget = renderer.getRenderTarget();
  48415. const activeCubeFace = renderer.getActiveCubeFace();
  48416. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48417. const _state = renderer.state;
  48418. // Set GL state for depth map.
  48419. _state.setBlending( NoBlending );
  48420. if ( _state.buffers.depth.getReversed() === true ) {
  48421. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48422. } else {
  48423. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48424. }
  48425. _state.buffers.depth.setTest( true );
  48426. _state.setScissorTest( false );
  48427. // check for shadow map type changes
  48428. const typeChanged = _previousType !== this.type;
  48429. // When shadow map type changes, materials need recompilation because sampler types change
  48430. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48431. if ( typeChanged ) {
  48432. scene.traverse( function ( object ) {
  48433. if ( object.material ) {
  48434. if ( Array.isArray( object.material ) ) {
  48435. object.material.forEach( mat => mat.needsUpdate = true );
  48436. } else {
  48437. object.material.needsUpdate = true;
  48438. }
  48439. }
  48440. } );
  48441. }
  48442. // render depth map
  48443. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48444. const light = lights[ i ];
  48445. const shadow = light.shadow;
  48446. if ( shadow === undefined ) {
  48447. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48448. continue;
  48449. }
  48450. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48451. _shadowMapSize.copy( shadow.mapSize );
  48452. const shadowFrameExtents = shadow.getFrameExtents();
  48453. _shadowMapSize.multiply( shadowFrameExtents );
  48454. _viewportSize.copy( shadow.mapSize );
  48455. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48456. if ( _shadowMapSize.x > _maxTextureSize ) {
  48457. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48458. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48459. shadow.mapSize.x = _viewportSize.x;
  48460. }
  48461. if ( _shadowMapSize.y > _maxTextureSize ) {
  48462. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48463. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48464. shadow.mapSize.y = _viewportSize.y;
  48465. }
  48466. }
  48467. if ( shadow.map === null || typeChanged === true ) {
  48468. if ( shadow.map !== null ) {
  48469. if ( shadow.map.depthTexture !== null ) {
  48470. shadow.map.depthTexture.dispose();
  48471. shadow.map.depthTexture = null;
  48472. }
  48473. shadow.map.dispose();
  48474. }
  48475. if ( this.type === VSMShadowMap ) {
  48476. if ( light.isPointLight ) {
  48477. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48478. continue;
  48479. }
  48480. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48481. format: RGFormat,
  48482. type: HalfFloatType,
  48483. minFilter: LinearFilter,
  48484. magFilter: LinearFilter,
  48485. generateMipmaps: false
  48486. } );
  48487. shadow.map.texture.name = light.name + '.shadowMap';
  48488. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  48489. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  48490. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  48491. shadow.map.depthTexture.format = DepthFormat;
  48492. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  48493. shadow.map.depthTexture.minFilter = NearestFilter;
  48494. shadow.map.depthTexture.magFilter = NearestFilter;
  48495. } else {
  48496. if ( light.isPointLight ) {
  48497. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48498. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48499. } else {
  48500. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48501. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48502. }
  48503. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48504. shadow.map.depthTexture.format = DepthFormat;
  48505. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48506. if ( this.type === PCFShadowMap ) {
  48507. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48508. shadow.map.depthTexture.minFilter = LinearFilter;
  48509. shadow.map.depthTexture.magFilter = LinearFilter;
  48510. } else {
  48511. shadow.map.depthTexture.compareFunction = null;
  48512. shadow.map.depthTexture.minFilter = NearestFilter;
  48513. shadow.map.depthTexture.magFilter = NearestFilter;
  48514. }
  48515. }
  48516. shadow.camera.updateProjectionMatrix();
  48517. }
  48518. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48519. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48520. for ( let face = 0; face < faceCount; face ++ ) {
  48521. // For cube render targets, render to each face separately
  48522. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48523. renderer.setRenderTarget( shadow.map, face );
  48524. renderer.clear();
  48525. } else {
  48526. // For 2D render targets, use viewports
  48527. if ( face === 0 ) {
  48528. renderer.setRenderTarget( shadow.map );
  48529. renderer.clear();
  48530. }
  48531. const viewport = shadow.getViewport( face );
  48532. _viewport.set(
  48533. _viewportSize.x * viewport.x,
  48534. _viewportSize.y * viewport.y,
  48535. _viewportSize.x * viewport.z,
  48536. _viewportSize.y * viewport.w
  48537. );
  48538. _state.viewport( _viewport );
  48539. }
  48540. if ( light.isPointLight ) {
  48541. const camera = shadow.camera;
  48542. const shadowMatrix = shadow.matrix;
  48543. const far = light.distance || camera.far;
  48544. if ( far !== camera.far ) {
  48545. camera.far = far;
  48546. camera.updateProjectionMatrix();
  48547. }
  48548. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  48549. camera.position.copy( _lightPositionWorld );
  48550. _lookTarget.copy( camera.position );
  48551. _lookTarget.add( _cubeDirections[ face ] );
  48552. camera.up.copy( _cubeUps[ face ] );
  48553. camera.lookAt( _lookTarget );
  48554. camera.updateMatrixWorld();
  48555. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  48556. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  48557. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  48558. } else {
  48559. shadow.updateMatrices( light );
  48560. }
  48561. _frustum = shadow.getFrustum();
  48562. renderObject( scene, camera, shadow.camera, light, this.type );
  48563. }
  48564. // do blur pass for VSM
  48565. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  48566. VSMPass( shadow, camera );
  48567. }
  48568. shadow.needsUpdate = false;
  48569. }
  48570. _previousType = this.type;
  48571. scope.needsUpdate = false;
  48572. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  48573. };
  48574. function VSMPass( shadow, camera ) {
  48575. const geometry = objects.update( fullScreenMesh );
  48576. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  48577. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  48578. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  48579. shadowMaterialVertical.needsUpdate = true;
  48580. shadowMaterialHorizontal.needsUpdate = true;
  48581. }
  48582. if ( shadow.mapPass === null ) {
  48583. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48584. format: RGFormat,
  48585. type: HalfFloatType
  48586. } );
  48587. }
  48588. // vertical pass - read from native depth texture
  48589. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  48590. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  48591. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  48592. renderer.setRenderTarget( shadow.mapPass );
  48593. renderer.clear();
  48594. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  48595. // horizontal pass
  48596. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  48597. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  48598. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  48599. renderer.setRenderTarget( shadow.map );
  48600. renderer.clear();
  48601. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  48602. }
  48603. function getDepthMaterial( object, material, light, type ) {
  48604. let result = null;
  48605. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  48606. if ( customMaterial !== undefined ) {
  48607. result = customMaterial;
  48608. } else {
  48609. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  48610. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  48611. ( material.displacementMap && material.displacementScale !== 0 ) ||
  48612. ( material.alphaMap && material.alphaTest > 0 ) ||
  48613. ( material.map && material.alphaTest > 0 ) ||
  48614. ( material.alphaToCoverage === true ) ) {
  48615. // in this case we need a unique material instance reflecting the
  48616. // appropriate state
  48617. const keyA = result.uuid, keyB = material.uuid;
  48618. let materialsForVariant = _materialCache[ keyA ];
  48619. if ( materialsForVariant === undefined ) {
  48620. materialsForVariant = {};
  48621. _materialCache[ keyA ] = materialsForVariant;
  48622. }
  48623. let cachedMaterial = materialsForVariant[ keyB ];
  48624. if ( cachedMaterial === undefined ) {
  48625. cachedMaterial = result.clone();
  48626. materialsForVariant[ keyB ] = cachedMaterial;
  48627. material.addEventListener( 'dispose', onMaterialDispose );
  48628. }
  48629. result = cachedMaterial;
  48630. }
  48631. }
  48632. result.visible = material.visible;
  48633. result.wireframe = material.wireframe;
  48634. if ( type === VSMShadowMap ) {
  48635. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  48636. } else {
  48637. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  48638. }
  48639. result.alphaMap = material.alphaMap;
  48640. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  48641. result.map = material.map;
  48642. result.clipShadows = material.clipShadows;
  48643. result.clippingPlanes = material.clippingPlanes;
  48644. result.clipIntersection = material.clipIntersection;
  48645. result.displacementMap = material.displacementMap;
  48646. result.displacementScale = material.displacementScale;
  48647. result.displacementBias = material.displacementBias;
  48648. result.wireframeLinewidth = material.wireframeLinewidth;
  48649. result.linewidth = material.linewidth;
  48650. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  48651. const materialProperties = renderer.properties.get( result );
  48652. materialProperties.light = light;
  48653. }
  48654. return result;
  48655. }
  48656. function renderObject( object, camera, shadowCamera, light, type ) {
  48657. if ( object.visible === false ) return;
  48658. const visible = object.layers.test( camera.layers );
  48659. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  48660. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  48661. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  48662. const geometry = objects.update( object );
  48663. const material = object.material;
  48664. if ( Array.isArray( material ) ) {
  48665. const groups = geometry.groups;
  48666. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48667. const group = groups[ k ];
  48668. const groupMaterial = material[ group.materialIndex ];
  48669. if ( groupMaterial && groupMaterial.visible ) {
  48670. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48671. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48672. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48673. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48674. }
  48675. }
  48676. } else if ( material.visible ) {
  48677. const depthMaterial = getDepthMaterial( object, material, light, type );
  48678. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48679. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48680. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48681. }
  48682. }
  48683. }
  48684. const children = object.children;
  48685. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48686. renderObject( children[ i ], camera, shadowCamera, light, type );
  48687. }
  48688. }
  48689. function onMaterialDispose( event ) {
  48690. const material = event.target;
  48691. material.removeEventListener( 'dispose', onMaterialDispose );
  48692. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48693. for ( const id in _materialCache ) {
  48694. const cache = _materialCache[ id ];
  48695. const uuid = event.target.uuid;
  48696. if ( uuid in cache ) {
  48697. const shadowMaterial = cache[ uuid ];
  48698. shadowMaterial.dispose();
  48699. delete cache[ uuid ];
  48700. }
  48701. }
  48702. }
  48703. }
  48704. const reversedFuncs = {
  48705. [ NeverDepth ]: AlwaysDepth,
  48706. [ LessDepth ]: GreaterDepth,
  48707. [ EqualDepth ]: NotEqualDepth,
  48708. [ LessEqualDepth ]: GreaterEqualDepth,
  48709. [ AlwaysDepth ]: NeverDepth,
  48710. [ GreaterDepth ]: LessDepth,
  48711. [ NotEqualDepth ]: EqualDepth,
  48712. [ GreaterEqualDepth ]: LessEqualDepth,
  48713. };
  48714. function WebGLState( gl, extensions ) {
  48715. function ColorBuffer() {
  48716. let locked = false;
  48717. const color = new Vector4();
  48718. let currentColorMask = null;
  48719. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48720. return {
  48721. setMask: function ( colorMask ) {
  48722. if ( currentColorMask !== colorMask && ! locked ) {
  48723. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48724. currentColorMask = colorMask;
  48725. }
  48726. },
  48727. setLocked: function ( lock ) {
  48728. locked = lock;
  48729. },
  48730. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48731. if ( premultipliedAlpha === true ) {
  48732. r *= a; g *= a; b *= a;
  48733. }
  48734. color.set( r, g, b, a );
  48735. if ( currentColorClear.equals( color ) === false ) {
  48736. gl.clearColor( r, g, b, a );
  48737. currentColorClear.copy( color );
  48738. }
  48739. },
  48740. reset: function () {
  48741. locked = false;
  48742. currentColorMask = null;
  48743. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48744. }
  48745. };
  48746. }
  48747. function DepthBuffer() {
  48748. let locked = false;
  48749. let currentReversed = false;
  48750. let currentDepthMask = null;
  48751. let currentDepthFunc = null;
  48752. let currentDepthClear = null;
  48753. return {
  48754. setReversed: function ( reversed ) {
  48755. if ( currentReversed !== reversed ) {
  48756. const ext = extensions.get( 'EXT_clip_control' );
  48757. if ( reversed ) {
  48758. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48759. } else {
  48760. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48761. }
  48762. currentReversed = reversed;
  48763. const oldDepth = currentDepthClear;
  48764. currentDepthClear = null;
  48765. this.setClear( oldDepth );
  48766. }
  48767. },
  48768. getReversed: function () {
  48769. return currentReversed;
  48770. },
  48771. setTest: function ( depthTest ) {
  48772. if ( depthTest ) {
  48773. enable( gl.DEPTH_TEST );
  48774. } else {
  48775. disable( gl.DEPTH_TEST );
  48776. }
  48777. },
  48778. setMask: function ( depthMask ) {
  48779. if ( currentDepthMask !== depthMask && ! locked ) {
  48780. gl.depthMask( depthMask );
  48781. currentDepthMask = depthMask;
  48782. }
  48783. },
  48784. setFunc: function ( depthFunc ) {
  48785. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48786. if ( currentDepthFunc !== depthFunc ) {
  48787. switch ( depthFunc ) {
  48788. case NeverDepth:
  48789. gl.depthFunc( gl.NEVER );
  48790. break;
  48791. case AlwaysDepth:
  48792. gl.depthFunc( gl.ALWAYS );
  48793. break;
  48794. case LessDepth:
  48795. gl.depthFunc( gl.LESS );
  48796. break;
  48797. case LessEqualDepth:
  48798. gl.depthFunc( gl.LEQUAL );
  48799. break;
  48800. case EqualDepth:
  48801. gl.depthFunc( gl.EQUAL );
  48802. break;
  48803. case GreaterEqualDepth:
  48804. gl.depthFunc( gl.GEQUAL );
  48805. break;
  48806. case GreaterDepth:
  48807. gl.depthFunc( gl.GREATER );
  48808. break;
  48809. case NotEqualDepth:
  48810. gl.depthFunc( gl.NOTEQUAL );
  48811. break;
  48812. default:
  48813. gl.depthFunc( gl.LEQUAL );
  48814. }
  48815. currentDepthFunc = depthFunc;
  48816. }
  48817. },
  48818. setLocked: function ( lock ) {
  48819. locked = lock;
  48820. },
  48821. setClear: function ( depth ) {
  48822. if ( currentDepthClear !== depth ) {
  48823. if ( currentReversed ) {
  48824. depth = 1 - depth;
  48825. }
  48826. gl.clearDepth( depth );
  48827. currentDepthClear = depth;
  48828. }
  48829. },
  48830. reset: function () {
  48831. locked = false;
  48832. currentDepthMask = null;
  48833. currentDepthFunc = null;
  48834. currentDepthClear = null;
  48835. currentReversed = false;
  48836. }
  48837. };
  48838. }
  48839. function StencilBuffer() {
  48840. let locked = false;
  48841. let currentStencilMask = null;
  48842. let currentStencilFunc = null;
  48843. let currentStencilRef = null;
  48844. let currentStencilFuncMask = null;
  48845. let currentStencilFail = null;
  48846. let currentStencilZFail = null;
  48847. let currentStencilZPass = null;
  48848. let currentStencilClear = null;
  48849. return {
  48850. setTest: function ( stencilTest ) {
  48851. if ( ! locked ) {
  48852. if ( stencilTest ) {
  48853. enable( gl.STENCIL_TEST );
  48854. } else {
  48855. disable( gl.STENCIL_TEST );
  48856. }
  48857. }
  48858. },
  48859. setMask: function ( stencilMask ) {
  48860. if ( currentStencilMask !== stencilMask && ! locked ) {
  48861. gl.stencilMask( stencilMask );
  48862. currentStencilMask = stencilMask;
  48863. }
  48864. },
  48865. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48866. if ( currentStencilFunc !== stencilFunc ||
  48867. currentStencilRef !== stencilRef ||
  48868. currentStencilFuncMask !== stencilMask ) {
  48869. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48870. currentStencilFunc = stencilFunc;
  48871. currentStencilRef = stencilRef;
  48872. currentStencilFuncMask = stencilMask;
  48873. }
  48874. },
  48875. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48876. if ( currentStencilFail !== stencilFail ||
  48877. currentStencilZFail !== stencilZFail ||
  48878. currentStencilZPass !== stencilZPass ) {
  48879. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48880. currentStencilFail = stencilFail;
  48881. currentStencilZFail = stencilZFail;
  48882. currentStencilZPass = stencilZPass;
  48883. }
  48884. },
  48885. setLocked: function ( lock ) {
  48886. locked = lock;
  48887. },
  48888. setClear: function ( stencil ) {
  48889. if ( currentStencilClear !== stencil ) {
  48890. gl.clearStencil( stencil );
  48891. currentStencilClear = stencil;
  48892. }
  48893. },
  48894. reset: function () {
  48895. locked = false;
  48896. currentStencilMask = null;
  48897. currentStencilFunc = null;
  48898. currentStencilRef = null;
  48899. currentStencilFuncMask = null;
  48900. currentStencilFail = null;
  48901. currentStencilZFail = null;
  48902. currentStencilZPass = null;
  48903. currentStencilClear = null;
  48904. }
  48905. };
  48906. }
  48907. //
  48908. const colorBuffer = new ColorBuffer();
  48909. const depthBuffer = new DepthBuffer();
  48910. const stencilBuffer = new StencilBuffer();
  48911. const uboBindings = new WeakMap();
  48912. const uboProgramMap = new WeakMap();
  48913. let enabledCapabilities = {};
  48914. let currentBoundFramebuffers = {};
  48915. let currentDrawbuffers = new WeakMap();
  48916. let defaultDrawbuffers = [];
  48917. let currentProgram = null;
  48918. let currentBlendingEnabled = false;
  48919. let currentBlending = null;
  48920. let currentBlendEquation = null;
  48921. let currentBlendSrc = null;
  48922. let currentBlendDst = null;
  48923. let currentBlendEquationAlpha = null;
  48924. let currentBlendSrcAlpha = null;
  48925. let currentBlendDstAlpha = null;
  48926. let currentBlendColor = new Color( 0, 0, 0 );
  48927. let currentBlendAlpha = 0;
  48928. let currentPremultipledAlpha = false;
  48929. let currentFlipSided = null;
  48930. let currentCullFace = null;
  48931. let currentLineWidth = null;
  48932. let currentPolygonOffsetFactor = null;
  48933. let currentPolygonOffsetUnits = null;
  48934. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48935. let lineWidthAvailable = false;
  48936. let version = 0;
  48937. const glVersion = gl.getParameter( gl.VERSION );
  48938. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48939. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48940. lineWidthAvailable = ( version >= 1.0 );
  48941. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48942. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48943. lineWidthAvailable = ( version >= 2.0 );
  48944. }
  48945. let currentTextureSlot = null;
  48946. let currentBoundTextures = {};
  48947. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48948. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48949. const currentScissor = new Vector4().fromArray( scissorParam );
  48950. const currentViewport = new Vector4().fromArray( viewportParam );
  48951. function createTexture( type, target, count, dimensions ) {
  48952. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48953. const texture = gl.createTexture();
  48954. gl.bindTexture( type, texture );
  48955. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48956. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48957. for ( let i = 0; i < count; i ++ ) {
  48958. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48959. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48960. } else {
  48961. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48962. }
  48963. }
  48964. return texture;
  48965. }
  48966. const emptyTextures = {};
  48967. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48968. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48969. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48970. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48971. // init
  48972. colorBuffer.setClear( 0, 0, 0, 1 );
  48973. depthBuffer.setClear( 1 );
  48974. stencilBuffer.setClear( 0 );
  48975. enable( gl.DEPTH_TEST );
  48976. depthBuffer.setFunc( LessEqualDepth );
  48977. setFlipSided( false );
  48978. setCullFace( CullFaceBack );
  48979. enable( gl.CULL_FACE );
  48980. setBlending( NoBlending );
  48981. //
  48982. function enable( id ) {
  48983. if ( enabledCapabilities[ id ] !== true ) {
  48984. gl.enable( id );
  48985. enabledCapabilities[ id ] = true;
  48986. }
  48987. }
  48988. function disable( id ) {
  48989. if ( enabledCapabilities[ id ] !== false ) {
  48990. gl.disable( id );
  48991. enabledCapabilities[ id ] = false;
  48992. }
  48993. }
  48994. function bindFramebuffer( target, framebuffer ) {
  48995. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48996. gl.bindFramebuffer( target, framebuffer );
  48997. currentBoundFramebuffers[ target ] = framebuffer;
  48998. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48999. if ( target === gl.DRAW_FRAMEBUFFER ) {
  49000. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  49001. }
  49002. if ( target === gl.FRAMEBUFFER ) {
  49003. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  49004. }
  49005. return true;
  49006. }
  49007. return false;
  49008. }
  49009. function drawBuffers( renderTarget, framebuffer ) {
  49010. let drawBuffers = defaultDrawbuffers;
  49011. let needsUpdate = false;
  49012. if ( renderTarget ) {
  49013. drawBuffers = currentDrawbuffers.get( framebuffer );
  49014. if ( drawBuffers === undefined ) {
  49015. drawBuffers = [];
  49016. currentDrawbuffers.set( framebuffer, drawBuffers );
  49017. }
  49018. const textures = renderTarget.textures;
  49019. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  49020. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49021. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  49022. }
  49023. drawBuffers.length = textures.length;
  49024. needsUpdate = true;
  49025. }
  49026. } else {
  49027. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  49028. drawBuffers[ 0 ] = gl.BACK;
  49029. needsUpdate = true;
  49030. }
  49031. }
  49032. if ( needsUpdate ) {
  49033. gl.drawBuffers( drawBuffers );
  49034. }
  49035. }
  49036. function useProgram( program ) {
  49037. if ( currentProgram !== program ) {
  49038. gl.useProgram( program );
  49039. currentProgram = program;
  49040. return true;
  49041. }
  49042. return false;
  49043. }
  49044. const equationToGL = {
  49045. [ AddEquation ]: gl.FUNC_ADD,
  49046. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  49047. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  49048. };
  49049. equationToGL[ MinEquation ] = gl.MIN;
  49050. equationToGL[ MaxEquation ] = gl.MAX;
  49051. const factorToGL = {
  49052. [ ZeroFactor ]: gl.ZERO,
  49053. [ OneFactor ]: gl.ONE,
  49054. [ SrcColorFactor ]: gl.SRC_COLOR,
  49055. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  49056. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  49057. [ DstColorFactor ]: gl.DST_COLOR,
  49058. [ DstAlphaFactor ]: gl.DST_ALPHA,
  49059. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  49060. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  49061. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  49062. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  49063. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  49064. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  49065. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  49066. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  49067. };
  49068. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  49069. if ( blending === NoBlending ) {
  49070. if ( currentBlendingEnabled === true ) {
  49071. disable( gl.BLEND );
  49072. currentBlendingEnabled = false;
  49073. }
  49074. return;
  49075. }
  49076. if ( currentBlendingEnabled === false ) {
  49077. enable( gl.BLEND );
  49078. currentBlendingEnabled = true;
  49079. }
  49080. if ( blending !== CustomBlending ) {
  49081. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  49082. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  49083. gl.blendEquation( gl.FUNC_ADD );
  49084. currentBlendEquation = AddEquation;
  49085. currentBlendEquationAlpha = AddEquation;
  49086. }
  49087. if ( premultipliedAlpha ) {
  49088. switch ( blending ) {
  49089. case NormalBlending:
  49090. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49091. break;
  49092. case AdditiveBlending:
  49093. gl.blendFunc( gl.ONE, gl.ONE );
  49094. break;
  49095. case SubtractiveBlending:
  49096. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  49097. break;
  49098. case MultiplyBlending:
  49099. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  49100. break;
  49101. default:
  49102. error( 'WebGLState: Invalid blending: ', blending );
  49103. break;
  49104. }
  49105. } else {
  49106. switch ( blending ) {
  49107. case NormalBlending:
  49108. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49109. break;
  49110. case AdditiveBlending:
  49111. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  49112. break;
  49113. case SubtractiveBlending:
  49114. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49115. break;
  49116. case MultiplyBlending:
  49117. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  49118. break;
  49119. default:
  49120. error( 'WebGLState: Invalid blending: ', blending );
  49121. break;
  49122. }
  49123. }
  49124. currentBlendSrc = null;
  49125. currentBlendDst = null;
  49126. currentBlendSrcAlpha = null;
  49127. currentBlendDstAlpha = null;
  49128. currentBlendColor.set( 0, 0, 0 );
  49129. currentBlendAlpha = 0;
  49130. currentBlending = blending;
  49131. currentPremultipledAlpha = premultipliedAlpha;
  49132. }
  49133. return;
  49134. }
  49135. // custom blending
  49136. blendEquationAlpha = blendEquationAlpha || blendEquation;
  49137. blendSrcAlpha = blendSrcAlpha || blendSrc;
  49138. blendDstAlpha = blendDstAlpha || blendDst;
  49139. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  49140. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  49141. currentBlendEquation = blendEquation;
  49142. currentBlendEquationAlpha = blendEquationAlpha;
  49143. }
  49144. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  49145. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  49146. currentBlendSrc = blendSrc;
  49147. currentBlendDst = blendDst;
  49148. currentBlendSrcAlpha = blendSrcAlpha;
  49149. currentBlendDstAlpha = blendDstAlpha;
  49150. }
  49151. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  49152. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  49153. currentBlendColor.copy( blendColor );
  49154. currentBlendAlpha = blendAlpha;
  49155. }
  49156. currentBlending = blending;
  49157. currentPremultipledAlpha = false;
  49158. }
  49159. function setMaterial( material, frontFaceCW ) {
  49160. material.side === DoubleSide
  49161. ? disable( gl.CULL_FACE )
  49162. : enable( gl.CULL_FACE );
  49163. let flipSided = ( material.side === BackSide );
  49164. if ( frontFaceCW ) flipSided = ! flipSided;
  49165. setFlipSided( flipSided );
  49166. ( material.blending === NormalBlending && material.transparent === false )
  49167. ? setBlending( NoBlending )
  49168. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  49169. depthBuffer.setFunc( material.depthFunc );
  49170. depthBuffer.setTest( material.depthTest );
  49171. depthBuffer.setMask( material.depthWrite );
  49172. colorBuffer.setMask( material.colorWrite );
  49173. const stencilWrite = material.stencilWrite;
  49174. stencilBuffer.setTest( stencilWrite );
  49175. if ( stencilWrite ) {
  49176. stencilBuffer.setMask( material.stencilWriteMask );
  49177. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  49178. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  49179. }
  49180. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  49181. material.alphaToCoverage === true
  49182. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  49183. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49184. }
  49185. //
  49186. function setFlipSided( flipSided ) {
  49187. if ( currentFlipSided !== flipSided ) {
  49188. if ( flipSided ) {
  49189. gl.frontFace( gl.CW );
  49190. } else {
  49191. gl.frontFace( gl.CCW );
  49192. }
  49193. currentFlipSided = flipSided;
  49194. }
  49195. }
  49196. function setCullFace( cullFace ) {
  49197. if ( cullFace !== CullFaceNone ) {
  49198. enable( gl.CULL_FACE );
  49199. if ( cullFace !== currentCullFace ) {
  49200. if ( cullFace === CullFaceBack ) {
  49201. gl.cullFace( gl.BACK );
  49202. } else if ( cullFace === CullFaceFront ) {
  49203. gl.cullFace( gl.FRONT );
  49204. } else {
  49205. gl.cullFace( gl.FRONT_AND_BACK );
  49206. }
  49207. }
  49208. } else {
  49209. disable( gl.CULL_FACE );
  49210. }
  49211. currentCullFace = cullFace;
  49212. }
  49213. function setLineWidth( width ) {
  49214. if ( width !== currentLineWidth ) {
  49215. if ( lineWidthAvailable ) gl.lineWidth( width );
  49216. currentLineWidth = width;
  49217. }
  49218. }
  49219. function setPolygonOffset( polygonOffset, factor, units ) {
  49220. if ( polygonOffset ) {
  49221. enable( gl.POLYGON_OFFSET_FILL );
  49222. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  49223. gl.polygonOffset( factor, units );
  49224. currentPolygonOffsetFactor = factor;
  49225. currentPolygonOffsetUnits = units;
  49226. }
  49227. } else {
  49228. disable( gl.POLYGON_OFFSET_FILL );
  49229. }
  49230. }
  49231. function setScissorTest( scissorTest ) {
  49232. if ( scissorTest ) {
  49233. enable( gl.SCISSOR_TEST );
  49234. } else {
  49235. disable( gl.SCISSOR_TEST );
  49236. }
  49237. }
  49238. // texture
  49239. function activeTexture( webglSlot ) {
  49240. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49241. if ( currentTextureSlot !== webglSlot ) {
  49242. gl.activeTexture( webglSlot );
  49243. currentTextureSlot = webglSlot;
  49244. }
  49245. }
  49246. function bindTexture( webglType, webglTexture, webglSlot ) {
  49247. if ( webglSlot === undefined ) {
  49248. if ( currentTextureSlot === null ) {
  49249. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49250. } else {
  49251. webglSlot = currentTextureSlot;
  49252. }
  49253. }
  49254. let boundTexture = currentBoundTextures[ webglSlot ];
  49255. if ( boundTexture === undefined ) {
  49256. boundTexture = { type: undefined, texture: undefined };
  49257. currentBoundTextures[ webglSlot ] = boundTexture;
  49258. }
  49259. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49260. if ( currentTextureSlot !== webglSlot ) {
  49261. gl.activeTexture( webglSlot );
  49262. currentTextureSlot = webglSlot;
  49263. }
  49264. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49265. boundTexture.type = webglType;
  49266. boundTexture.texture = webglTexture;
  49267. }
  49268. }
  49269. function unbindTexture() {
  49270. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49271. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49272. gl.bindTexture( boundTexture.type, null );
  49273. boundTexture.type = undefined;
  49274. boundTexture.texture = undefined;
  49275. }
  49276. }
  49277. function compressedTexImage2D() {
  49278. try {
  49279. gl.compressedTexImage2D( ...arguments );
  49280. } catch ( e ) {
  49281. error( 'WebGLState:', e );
  49282. }
  49283. }
  49284. function compressedTexImage3D() {
  49285. try {
  49286. gl.compressedTexImage3D( ...arguments );
  49287. } catch ( e ) {
  49288. error( 'WebGLState:', e );
  49289. }
  49290. }
  49291. function texSubImage2D() {
  49292. try {
  49293. gl.texSubImage2D( ...arguments );
  49294. } catch ( e ) {
  49295. error( 'WebGLState:', e );
  49296. }
  49297. }
  49298. function texSubImage3D() {
  49299. try {
  49300. gl.texSubImage3D( ...arguments );
  49301. } catch ( e ) {
  49302. error( 'WebGLState:', e );
  49303. }
  49304. }
  49305. function compressedTexSubImage2D() {
  49306. try {
  49307. gl.compressedTexSubImage2D( ...arguments );
  49308. } catch ( e ) {
  49309. error( 'WebGLState:', e );
  49310. }
  49311. }
  49312. function compressedTexSubImage3D() {
  49313. try {
  49314. gl.compressedTexSubImage3D( ...arguments );
  49315. } catch ( e ) {
  49316. error( 'WebGLState:', e );
  49317. }
  49318. }
  49319. function texStorage2D() {
  49320. try {
  49321. gl.texStorage2D( ...arguments );
  49322. } catch ( e ) {
  49323. error( 'WebGLState:', e );
  49324. }
  49325. }
  49326. function texStorage3D() {
  49327. try {
  49328. gl.texStorage3D( ...arguments );
  49329. } catch ( e ) {
  49330. error( 'WebGLState:', e );
  49331. }
  49332. }
  49333. function texImage2D() {
  49334. try {
  49335. gl.texImage2D( ...arguments );
  49336. } catch ( e ) {
  49337. error( 'WebGLState:', e );
  49338. }
  49339. }
  49340. function texImage3D() {
  49341. try {
  49342. gl.texImage3D( ...arguments );
  49343. } catch ( e ) {
  49344. error( 'WebGLState:', e );
  49345. }
  49346. }
  49347. //
  49348. function scissor( scissor ) {
  49349. if ( currentScissor.equals( scissor ) === false ) {
  49350. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49351. currentScissor.copy( scissor );
  49352. }
  49353. }
  49354. function viewport( viewport ) {
  49355. if ( currentViewport.equals( viewport ) === false ) {
  49356. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49357. currentViewport.copy( viewport );
  49358. }
  49359. }
  49360. function updateUBOMapping( uniformsGroup, program ) {
  49361. let mapping = uboProgramMap.get( program );
  49362. if ( mapping === undefined ) {
  49363. mapping = new WeakMap();
  49364. uboProgramMap.set( program, mapping );
  49365. }
  49366. let blockIndex = mapping.get( uniformsGroup );
  49367. if ( blockIndex === undefined ) {
  49368. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49369. mapping.set( uniformsGroup, blockIndex );
  49370. }
  49371. }
  49372. function uniformBlockBinding( uniformsGroup, program ) {
  49373. const mapping = uboProgramMap.get( program );
  49374. const blockIndex = mapping.get( uniformsGroup );
  49375. if ( uboBindings.get( program ) !== blockIndex ) {
  49376. // bind shader specific block index to global block point
  49377. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49378. uboBindings.set( program, blockIndex );
  49379. }
  49380. }
  49381. //
  49382. function reset() {
  49383. // reset state
  49384. gl.disable( gl.BLEND );
  49385. gl.disable( gl.CULL_FACE );
  49386. gl.disable( gl.DEPTH_TEST );
  49387. gl.disable( gl.POLYGON_OFFSET_FILL );
  49388. gl.disable( gl.SCISSOR_TEST );
  49389. gl.disable( gl.STENCIL_TEST );
  49390. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49391. gl.blendEquation( gl.FUNC_ADD );
  49392. gl.blendFunc( gl.ONE, gl.ZERO );
  49393. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49394. gl.blendColor( 0, 0, 0, 0 );
  49395. gl.colorMask( true, true, true, true );
  49396. gl.clearColor( 0, 0, 0, 0 );
  49397. gl.depthMask( true );
  49398. gl.depthFunc( gl.LESS );
  49399. depthBuffer.setReversed( false );
  49400. gl.clearDepth( 1 );
  49401. gl.stencilMask( 0xffffffff );
  49402. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49403. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49404. gl.clearStencil( 0 );
  49405. gl.cullFace( gl.BACK );
  49406. gl.frontFace( gl.CCW );
  49407. gl.polygonOffset( 0, 0 );
  49408. gl.activeTexture( gl.TEXTURE0 );
  49409. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49410. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49411. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49412. gl.useProgram( null );
  49413. gl.lineWidth( 1 );
  49414. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49415. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49416. // reset internals
  49417. enabledCapabilities = {};
  49418. currentTextureSlot = null;
  49419. currentBoundTextures = {};
  49420. currentBoundFramebuffers = {};
  49421. currentDrawbuffers = new WeakMap();
  49422. defaultDrawbuffers = [];
  49423. currentProgram = null;
  49424. currentBlendingEnabled = false;
  49425. currentBlending = null;
  49426. currentBlendEquation = null;
  49427. currentBlendSrc = null;
  49428. currentBlendDst = null;
  49429. currentBlendEquationAlpha = null;
  49430. currentBlendSrcAlpha = null;
  49431. currentBlendDstAlpha = null;
  49432. currentBlendColor = new Color( 0, 0, 0 );
  49433. currentBlendAlpha = 0;
  49434. currentPremultipledAlpha = false;
  49435. currentFlipSided = null;
  49436. currentCullFace = null;
  49437. currentLineWidth = null;
  49438. currentPolygonOffsetFactor = null;
  49439. currentPolygonOffsetUnits = null;
  49440. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49441. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49442. colorBuffer.reset();
  49443. depthBuffer.reset();
  49444. stencilBuffer.reset();
  49445. }
  49446. return {
  49447. buffers: {
  49448. color: colorBuffer,
  49449. depth: depthBuffer,
  49450. stencil: stencilBuffer
  49451. },
  49452. enable: enable,
  49453. disable: disable,
  49454. bindFramebuffer: bindFramebuffer,
  49455. drawBuffers: drawBuffers,
  49456. useProgram: useProgram,
  49457. setBlending: setBlending,
  49458. setMaterial: setMaterial,
  49459. setFlipSided: setFlipSided,
  49460. setCullFace: setCullFace,
  49461. setLineWidth: setLineWidth,
  49462. setPolygonOffset: setPolygonOffset,
  49463. setScissorTest: setScissorTest,
  49464. activeTexture: activeTexture,
  49465. bindTexture: bindTexture,
  49466. unbindTexture: unbindTexture,
  49467. compressedTexImage2D: compressedTexImage2D,
  49468. compressedTexImage3D: compressedTexImage3D,
  49469. texImage2D: texImage2D,
  49470. texImage3D: texImage3D,
  49471. updateUBOMapping: updateUBOMapping,
  49472. uniformBlockBinding: uniformBlockBinding,
  49473. texStorage2D: texStorage2D,
  49474. texStorage3D: texStorage3D,
  49475. texSubImage2D: texSubImage2D,
  49476. texSubImage3D: texSubImage3D,
  49477. compressedTexSubImage2D: compressedTexSubImage2D,
  49478. compressedTexSubImage3D: compressedTexSubImage3D,
  49479. scissor: scissor,
  49480. viewport: viewport,
  49481. reset: reset
  49482. };
  49483. }
  49484. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49485. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49486. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49487. const _imageDimensions = new Vector2();
  49488. const _videoTextures = new WeakMap();
  49489. let _canvas;
  49490. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49491. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49492. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49493. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49494. let useOffscreenCanvas = false;
  49495. try {
  49496. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49497. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49498. } catch ( err ) {
  49499. // Ignore any errors
  49500. }
  49501. function createCanvas( width, height ) {
  49502. // Use OffscreenCanvas when available. Specially needed in web workers
  49503. return useOffscreenCanvas ?
  49504. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49505. }
  49506. function resizeImage( image, needsNewCanvas, maxSize ) {
  49507. let scale = 1;
  49508. const dimensions = getDimensions( image );
  49509. // handle case if texture exceeds max size
  49510. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49511. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49512. }
  49513. // only perform resize if necessary
  49514. if ( scale < 1 ) {
  49515. // only perform resize for certain image types
  49516. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49517. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49518. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49519. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49520. const width = Math.floor( scale * dimensions.width );
  49521. const height = Math.floor( scale * dimensions.height );
  49522. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49523. // cube textures can't reuse the same canvas
  49524. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49525. canvas.width = width;
  49526. canvas.height = height;
  49527. const context = canvas.getContext( '2d' );
  49528. context.drawImage( image, 0, 0, width, height );
  49529. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49530. return canvas;
  49531. } else {
  49532. if ( 'data' in image ) {
  49533. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49534. }
  49535. return image;
  49536. }
  49537. }
  49538. return image;
  49539. }
  49540. function textureNeedsGenerateMipmaps( texture ) {
  49541. return texture.generateMipmaps;
  49542. }
  49543. function generateMipmap( target ) {
  49544. _gl.generateMipmap( target );
  49545. }
  49546. function getTargetType( texture ) {
  49547. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49548. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49549. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49550. return _gl.TEXTURE_2D;
  49551. }
  49552. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49553. if ( internalFormatName !== null ) {
  49554. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49555. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49556. }
  49557. let internalFormat = glFormat;
  49558. if ( glFormat === _gl.RED ) {
  49559. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49560. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49561. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49562. }
  49563. if ( glFormat === _gl.RED_INTEGER ) {
  49564. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49565. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  49566. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  49567. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  49568. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  49569. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  49570. }
  49571. if ( glFormat === _gl.RG ) {
  49572. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  49573. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  49574. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  49575. }
  49576. if ( glFormat === _gl.RG_INTEGER ) {
  49577. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  49578. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  49579. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  49580. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  49581. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  49582. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  49583. }
  49584. if ( glFormat === _gl.RGB_INTEGER ) {
  49585. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  49586. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  49587. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  49588. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  49589. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  49590. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  49591. }
  49592. if ( glFormat === _gl.RGBA_INTEGER ) {
  49593. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  49594. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  49595. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  49596. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  49597. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  49598. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  49599. }
  49600. if ( glFormat === _gl.RGB ) {
  49601. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  49602. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  49603. }
  49604. if ( glFormat === _gl.RGBA ) {
  49605. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49606. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  49607. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  49608. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  49609. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  49610. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  49611. }
  49612. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  49613. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  49614. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  49615. extensions.get( 'EXT_color_buffer_float' );
  49616. }
  49617. return internalFormat;
  49618. }
  49619. function getInternalDepthFormat( useStencil, depthType ) {
  49620. let glInternalFormat;
  49621. if ( useStencil ) {
  49622. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49623. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49624. } else if ( depthType === FloatType ) {
  49625. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  49626. } else if ( depthType === UnsignedShortType ) {
  49627. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49628. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49629. }
  49630. } else {
  49631. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49632. glInternalFormat = _gl.DEPTH_COMPONENT24;
  49633. } else if ( depthType === FloatType ) {
  49634. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  49635. } else if ( depthType === UnsignedShortType ) {
  49636. glInternalFormat = _gl.DEPTH_COMPONENT16;
  49637. }
  49638. }
  49639. return glInternalFormat;
  49640. }
  49641. function getMipLevels( texture, image ) {
  49642. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  49643. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  49644. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  49645. // user-defined mipmaps
  49646. return texture.mipmaps.length;
  49647. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  49648. return image.mipmaps.length;
  49649. } else {
  49650. // texture without mipmaps (only base level)
  49651. return 1;
  49652. }
  49653. }
  49654. //
  49655. function onTextureDispose( event ) {
  49656. const texture = event.target;
  49657. texture.removeEventListener( 'dispose', onTextureDispose );
  49658. deallocateTexture( texture );
  49659. if ( texture.isVideoTexture ) {
  49660. _videoTextures.delete( texture );
  49661. }
  49662. }
  49663. function onRenderTargetDispose( event ) {
  49664. const renderTarget = event.target;
  49665. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49666. deallocateRenderTarget( renderTarget );
  49667. }
  49668. //
  49669. function deallocateTexture( texture ) {
  49670. const textureProperties = properties.get( texture );
  49671. if ( textureProperties.__webglInit === undefined ) return;
  49672. // check if it's necessary to remove the WebGLTexture object
  49673. const source = texture.source;
  49674. const webglTextures = _sources.get( source );
  49675. if ( webglTextures ) {
  49676. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49677. webglTexture.usedTimes --;
  49678. // the WebGLTexture object is not used anymore, remove it
  49679. if ( webglTexture.usedTimes === 0 ) {
  49680. deleteTexture( texture );
  49681. }
  49682. // remove the weak map entry if no WebGLTexture uses the source anymore
  49683. if ( Object.keys( webglTextures ).length === 0 ) {
  49684. _sources.delete( source );
  49685. }
  49686. }
  49687. properties.remove( texture );
  49688. }
  49689. function deleteTexture( texture ) {
  49690. const textureProperties = properties.get( texture );
  49691. _gl.deleteTexture( textureProperties.__webglTexture );
  49692. const source = texture.source;
  49693. const webglTextures = _sources.get( source );
  49694. delete webglTextures[ textureProperties.__cacheKey ];
  49695. info.memory.textures --;
  49696. }
  49697. function deallocateRenderTarget( renderTarget ) {
  49698. const renderTargetProperties = properties.get( renderTarget );
  49699. if ( renderTarget.depthTexture ) {
  49700. renderTarget.depthTexture.dispose();
  49701. properties.remove( renderTarget.depthTexture );
  49702. }
  49703. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49704. for ( let i = 0; i < 6; i ++ ) {
  49705. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49706. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49707. } else {
  49708. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49709. }
  49710. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49711. }
  49712. } else {
  49713. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49714. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49715. } else {
  49716. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49717. }
  49718. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49719. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49720. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49721. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49722. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49723. }
  49724. }
  49725. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49726. }
  49727. const textures = renderTarget.textures;
  49728. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49729. const attachmentProperties = properties.get( textures[ i ] );
  49730. if ( attachmentProperties.__webglTexture ) {
  49731. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49732. info.memory.textures --;
  49733. }
  49734. properties.remove( textures[ i ] );
  49735. }
  49736. properties.remove( renderTarget );
  49737. }
  49738. //
  49739. let textureUnits = 0;
  49740. function resetTextureUnits() {
  49741. textureUnits = 0;
  49742. }
  49743. function allocateTextureUnit() {
  49744. const textureUnit = textureUnits;
  49745. if ( textureUnit >= capabilities.maxTextures ) {
  49746. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49747. }
  49748. textureUnits += 1;
  49749. return textureUnit;
  49750. }
  49751. function getTextureCacheKey( texture ) {
  49752. const array = [];
  49753. array.push( texture.wrapS );
  49754. array.push( texture.wrapT );
  49755. array.push( texture.wrapR || 0 );
  49756. array.push( texture.magFilter );
  49757. array.push( texture.minFilter );
  49758. array.push( texture.anisotropy );
  49759. array.push( texture.internalFormat );
  49760. array.push( texture.format );
  49761. array.push( texture.type );
  49762. array.push( texture.generateMipmaps );
  49763. array.push( texture.premultiplyAlpha );
  49764. array.push( texture.flipY );
  49765. array.push( texture.unpackAlignment );
  49766. array.push( texture.colorSpace );
  49767. return array.join();
  49768. }
  49769. //
  49770. function setTexture2D( texture, slot ) {
  49771. const textureProperties = properties.get( texture );
  49772. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49773. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49774. const image = texture.image;
  49775. if ( image === null ) {
  49776. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  49777. } else if ( image.complete === false ) {
  49778. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  49779. } else {
  49780. uploadTexture( textureProperties, texture, slot );
  49781. return;
  49782. }
  49783. } else if ( texture.isExternalTexture ) {
  49784. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49785. }
  49786. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49787. }
  49788. function setTexture2DArray( texture, slot ) {
  49789. const textureProperties = properties.get( texture );
  49790. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49791. uploadTexture( textureProperties, texture, slot );
  49792. return;
  49793. } else if ( texture.isExternalTexture ) {
  49794. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49795. }
  49796. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49797. }
  49798. function setTexture3D( texture, slot ) {
  49799. const textureProperties = properties.get( texture );
  49800. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49801. uploadTexture( textureProperties, texture, slot );
  49802. return;
  49803. }
  49804. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49805. }
  49806. function setTextureCube( texture, slot ) {
  49807. const textureProperties = properties.get( texture );
  49808. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49809. uploadCubeTexture( textureProperties, texture, slot );
  49810. return;
  49811. }
  49812. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49813. }
  49814. const wrappingToGL = {
  49815. [ RepeatWrapping ]: _gl.REPEAT,
  49816. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49817. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49818. };
  49819. const filterToGL = {
  49820. [ NearestFilter ]: _gl.NEAREST,
  49821. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49822. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49823. [ LinearFilter ]: _gl.LINEAR,
  49824. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49825. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49826. };
  49827. const compareToGL = {
  49828. [ NeverCompare ]: _gl.NEVER,
  49829. [ AlwaysCompare ]: _gl.ALWAYS,
  49830. [ LessCompare ]: _gl.LESS,
  49831. [ LessEqualCompare ]: _gl.LEQUAL,
  49832. [ EqualCompare ]: _gl.EQUAL,
  49833. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49834. [ GreaterCompare ]: _gl.GREATER,
  49835. [ NotEqualCompare ]: _gl.NOTEQUAL
  49836. };
  49837. function setTextureParameters( textureType, texture ) {
  49838. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49839. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49840. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49841. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49842. }
  49843. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49844. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49845. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49846. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49847. }
  49848. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49849. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49850. if ( texture.compareFunction ) {
  49851. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49852. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49853. }
  49854. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49855. if ( texture.magFilter === NearestFilter ) return;
  49856. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49857. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49858. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49859. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49860. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49861. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49862. }
  49863. }
  49864. }
  49865. function initTexture( textureProperties, texture ) {
  49866. let forceUpload = false;
  49867. if ( textureProperties.__webglInit === undefined ) {
  49868. textureProperties.__webglInit = true;
  49869. texture.addEventListener( 'dispose', onTextureDispose );
  49870. }
  49871. // create Source <-> WebGLTextures mapping if necessary
  49872. const source = texture.source;
  49873. let webglTextures = _sources.get( source );
  49874. if ( webglTextures === undefined ) {
  49875. webglTextures = {};
  49876. _sources.set( source, webglTextures );
  49877. }
  49878. // check if there is already a WebGLTexture object for the given texture parameters
  49879. const textureCacheKey = getTextureCacheKey( texture );
  49880. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49881. // if not, create a new instance of WebGLTexture
  49882. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49883. // create new entry
  49884. webglTextures[ textureCacheKey ] = {
  49885. texture: _gl.createTexture(),
  49886. usedTimes: 0
  49887. };
  49888. info.memory.textures ++;
  49889. // when a new instance of WebGLTexture was created, a texture upload is required
  49890. // even if the image contents are identical
  49891. forceUpload = true;
  49892. }
  49893. webglTextures[ textureCacheKey ].usedTimes ++;
  49894. // every time the texture cache key changes, it's necessary to check if an instance of
  49895. // WebGLTexture can be deleted in order to avoid a memory leak.
  49896. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49897. if ( webglTexture !== undefined ) {
  49898. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49899. if ( webglTexture.usedTimes === 0 ) {
  49900. deleteTexture( texture );
  49901. }
  49902. }
  49903. // store references to cache key and WebGLTexture object
  49904. textureProperties.__cacheKey = textureCacheKey;
  49905. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49906. }
  49907. return forceUpload;
  49908. }
  49909. function getRow( index, rowLength, componentStride ) {
  49910. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49911. }
  49912. function updateTexture( texture, image, glFormat, glType ) {
  49913. const componentStride = 4; // only RGBA supported
  49914. const updateRanges = texture.updateRanges;
  49915. if ( updateRanges.length === 0 ) {
  49916. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49917. } else {
  49918. // Before applying update ranges, we merge any adjacent / overlapping
  49919. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49920. // to performance improvements for applications which make heavy use of
  49921. // update ranges. Likely due to GPU command overhead.
  49922. //
  49923. // Note that to reduce garbage collection between frames, we merge the
  49924. // update ranges in-place. This is safe because this method will clear the
  49925. // update ranges once updated.
  49926. updateRanges.sort( ( a, b ) => a.start - b.start );
  49927. // To merge the update ranges in-place, we work from left to right in the
  49928. // existing updateRanges array, merging ranges. This may result in a final
  49929. // array which is smaller than the original. This index tracks the last
  49930. // index representing a merged range, any data after this index can be
  49931. // trimmed once the merge algorithm is completed.
  49932. let mergeIndex = 0;
  49933. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49934. const previousRange = updateRanges[ mergeIndex ];
  49935. const range = updateRanges[ i ];
  49936. // Only merge if in the same row and overlapping/adjacent
  49937. const previousEnd = previousRange.start + previousRange.count;
  49938. const currentRow = getRow( range.start, image.width, componentStride );
  49939. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49940. // We add one here to merge adjacent ranges. This is safe because ranges
  49941. // operate over positive integers.
  49942. if (
  49943. range.start <= previousEnd + 1 &&
  49944. currentRow === previousRow &&
  49945. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49946. ) {
  49947. previousRange.count = Math.max(
  49948. previousRange.count,
  49949. range.start + range.count - previousRange.start
  49950. );
  49951. } else {
  49952. ++ mergeIndex;
  49953. updateRanges[ mergeIndex ] = range;
  49954. }
  49955. }
  49956. // Trim the array to only contain the merged ranges.
  49957. updateRanges.length = mergeIndex + 1;
  49958. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49959. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49960. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49961. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49962. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49963. const range = updateRanges[ i ];
  49964. const pixelStart = Math.floor( range.start / componentStride );
  49965. const pixelCount = Math.ceil( range.count / componentStride );
  49966. const x = pixelStart % image.width;
  49967. const y = Math.floor( pixelStart / image.width );
  49968. // Assumes update ranges refer to contiguous memory
  49969. const width = pixelCount;
  49970. const height = 1;
  49971. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49972. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49973. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49974. }
  49975. texture.clearUpdateRanges();
  49976. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49977. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49978. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49979. }
  49980. }
  49981. function uploadTexture( textureProperties, texture, slot ) {
  49982. let textureType = _gl.TEXTURE_2D;
  49983. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49984. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49985. const forceUpload = initTexture( textureProperties, texture );
  49986. const source = texture.source;
  49987. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49988. const sourceProperties = properties.get( source );
  49989. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49990. state.activeTexture( _gl.TEXTURE0 + slot );
  49991. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49992. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49993. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49994. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49995. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49996. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49997. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49998. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49999. image = verifyColorSpace( texture, image );
  50000. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50001. const glType = utils.convert( texture.type );
  50002. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  50003. setTextureParameters( textureType, texture );
  50004. let mipmap;
  50005. const mipmaps = texture.mipmaps;
  50006. const useTexStorage = ( texture.isVideoTexture !== true );
  50007. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50008. const dataReady = source.dataReady;
  50009. const levels = getMipLevels( texture, image );
  50010. if ( texture.isDepthTexture ) {
  50011. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  50012. //
  50013. if ( allocateMemory ) {
  50014. if ( useTexStorage ) {
  50015. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  50016. } else {
  50017. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  50018. }
  50019. }
  50020. } else if ( texture.isDataTexture ) {
  50021. // use manually created mipmaps if available
  50022. // if there are no manual mipmaps
  50023. // set 0 level mipmap and then use GL to generate other mipmap levels
  50024. if ( mipmaps.length > 0 ) {
  50025. if ( useTexStorage && allocateMemory ) {
  50026. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50027. }
  50028. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50029. mipmap = mipmaps[ i ];
  50030. if ( useTexStorage ) {
  50031. if ( dataReady ) {
  50032. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50033. }
  50034. } else {
  50035. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50036. }
  50037. }
  50038. texture.generateMipmaps = false;
  50039. } else {
  50040. if ( useTexStorage ) {
  50041. if ( allocateMemory ) {
  50042. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50043. }
  50044. if ( dataReady ) {
  50045. updateTexture( texture, image, glFormat, glType );
  50046. }
  50047. } else {
  50048. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  50049. }
  50050. }
  50051. } else if ( texture.isCompressedTexture ) {
  50052. if ( texture.isCompressedArrayTexture ) {
  50053. if ( useTexStorage && allocateMemory ) {
  50054. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  50055. }
  50056. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50057. mipmap = mipmaps[ i ];
  50058. if ( texture.format !== RGBAFormat ) {
  50059. if ( glFormat !== null ) {
  50060. if ( useTexStorage ) {
  50061. if ( dataReady ) {
  50062. if ( texture.layerUpdates.size > 0 ) {
  50063. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  50064. for ( const layerIndex of texture.layerUpdates ) {
  50065. const layerData = mipmap.data.subarray(
  50066. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  50067. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  50068. );
  50069. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  50070. }
  50071. texture.clearLayerUpdates();
  50072. } else {
  50073. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  50074. }
  50075. }
  50076. } else {
  50077. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  50078. }
  50079. } else {
  50080. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50081. }
  50082. } else {
  50083. if ( useTexStorage ) {
  50084. if ( dataReady ) {
  50085. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  50086. }
  50087. } else {
  50088. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  50089. }
  50090. }
  50091. }
  50092. } else {
  50093. if ( useTexStorage && allocateMemory ) {
  50094. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50095. }
  50096. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50097. mipmap = mipmaps[ i ];
  50098. if ( texture.format !== RGBAFormat ) {
  50099. if ( glFormat !== null ) {
  50100. if ( useTexStorage ) {
  50101. if ( dataReady ) {
  50102. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50103. }
  50104. } else {
  50105. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50106. }
  50107. } else {
  50108. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50109. }
  50110. } else {
  50111. if ( useTexStorage ) {
  50112. if ( dataReady ) {
  50113. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50114. }
  50115. } else {
  50116. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50117. }
  50118. }
  50119. }
  50120. }
  50121. } else if ( texture.isDataArrayTexture ) {
  50122. if ( useTexStorage ) {
  50123. if ( allocateMemory ) {
  50124. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  50125. }
  50126. if ( dataReady ) {
  50127. if ( texture.layerUpdates.size > 0 ) {
  50128. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  50129. for ( const layerIndex of texture.layerUpdates ) {
  50130. const layerData = image.data.subarray(
  50131. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  50132. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  50133. );
  50134. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  50135. }
  50136. texture.clearLayerUpdates();
  50137. } else {
  50138. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50139. }
  50140. }
  50141. } else {
  50142. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50143. }
  50144. } else if ( texture.isData3DTexture ) {
  50145. if ( useTexStorage ) {
  50146. if ( allocateMemory ) {
  50147. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  50148. }
  50149. if ( dataReady ) {
  50150. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50151. }
  50152. } else {
  50153. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50154. }
  50155. } else if ( texture.isFramebufferTexture ) {
  50156. if ( allocateMemory ) {
  50157. if ( useTexStorage ) {
  50158. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50159. } else {
  50160. let width = image.width, height = image.height;
  50161. for ( let i = 0; i < levels; i ++ ) {
  50162. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  50163. width >>= 1;
  50164. height >>= 1;
  50165. }
  50166. }
  50167. }
  50168. } else {
  50169. // regular Texture (image, video, canvas)
  50170. // use manually created mipmaps if available
  50171. // if there are no manual mipmaps
  50172. // set 0 level mipmap and then use GL to generate other mipmap levels
  50173. if ( mipmaps.length > 0 ) {
  50174. if ( useTexStorage && allocateMemory ) {
  50175. const dimensions = getDimensions( mipmaps[ 0 ] );
  50176. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50177. }
  50178. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50179. mipmap = mipmaps[ i ];
  50180. if ( useTexStorage ) {
  50181. if ( dataReady ) {
  50182. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  50183. }
  50184. } else {
  50185. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  50186. }
  50187. }
  50188. texture.generateMipmaps = false;
  50189. } else {
  50190. if ( useTexStorage ) {
  50191. if ( allocateMemory ) {
  50192. const dimensions = getDimensions( image );
  50193. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50194. }
  50195. if ( dataReady ) {
  50196. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  50197. }
  50198. } else {
  50199. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  50200. }
  50201. }
  50202. }
  50203. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50204. generateMipmap( textureType );
  50205. }
  50206. sourceProperties.__version = source.version;
  50207. if ( texture.onUpdate ) texture.onUpdate( texture );
  50208. }
  50209. textureProperties.__version = texture.version;
  50210. }
  50211. function uploadCubeTexture( textureProperties, texture, slot ) {
  50212. if ( texture.image.length !== 6 ) return;
  50213. const forceUpload = initTexture( textureProperties, texture );
  50214. const source = texture.source;
  50215. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50216. const sourceProperties = properties.get( source );
  50217. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50218. state.activeTexture( _gl.TEXTURE0 + slot );
  50219. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50220. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50221. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50222. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50223. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50224. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50225. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50226. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  50227. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  50228. const cubeImage = [];
  50229. for ( let i = 0; i < 6; i ++ ) {
  50230. if ( ! isCompressed && ! isDataTexture ) {
  50231. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50232. } else {
  50233. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50234. }
  50235. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50236. }
  50237. const image = cubeImage[ 0 ],
  50238. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50239. glType = utils.convert( texture.type ),
  50240. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50241. const useTexStorage = ( texture.isVideoTexture !== true );
  50242. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50243. const dataReady = source.dataReady;
  50244. let levels = getMipLevels( texture, image );
  50245. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50246. let mipmaps;
  50247. if ( isCompressed ) {
  50248. if ( useTexStorage && allocateMemory ) {
  50249. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50250. }
  50251. for ( let i = 0; i < 6; i ++ ) {
  50252. mipmaps = cubeImage[ i ].mipmaps;
  50253. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50254. const mipmap = mipmaps[ j ];
  50255. if ( texture.format !== RGBAFormat ) {
  50256. if ( glFormat !== null ) {
  50257. if ( useTexStorage ) {
  50258. if ( dataReady ) {
  50259. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50260. }
  50261. } else {
  50262. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50263. }
  50264. } else {
  50265. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50266. }
  50267. } else {
  50268. if ( useTexStorage ) {
  50269. if ( dataReady ) {
  50270. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50271. }
  50272. } else {
  50273. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50274. }
  50275. }
  50276. }
  50277. }
  50278. } else {
  50279. mipmaps = texture.mipmaps;
  50280. if ( useTexStorage && allocateMemory ) {
  50281. // TODO: Uniformly handle mipmap definitions
  50282. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50283. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50284. if ( mipmaps.length > 0 ) levels ++;
  50285. const dimensions = getDimensions( cubeImage[ 0 ] );
  50286. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50287. }
  50288. for ( let i = 0; i < 6; i ++ ) {
  50289. if ( isDataTexture ) {
  50290. if ( useTexStorage ) {
  50291. if ( dataReady ) {
  50292. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50293. }
  50294. } else {
  50295. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50296. }
  50297. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50298. const mipmap = mipmaps[ j ];
  50299. const mipmapImage = mipmap.image[ i ].image;
  50300. if ( useTexStorage ) {
  50301. if ( dataReady ) {
  50302. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50303. }
  50304. } else {
  50305. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50306. }
  50307. }
  50308. } else {
  50309. if ( useTexStorage ) {
  50310. if ( dataReady ) {
  50311. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50312. }
  50313. } else {
  50314. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50315. }
  50316. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50317. const mipmap = mipmaps[ j ];
  50318. if ( useTexStorage ) {
  50319. if ( dataReady ) {
  50320. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50321. }
  50322. } else {
  50323. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50324. }
  50325. }
  50326. }
  50327. }
  50328. }
  50329. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50330. // We assume images for cube map have the same size.
  50331. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50332. }
  50333. sourceProperties.__version = source.version;
  50334. if ( texture.onUpdate ) texture.onUpdate( texture );
  50335. }
  50336. textureProperties.__version = texture.version;
  50337. }
  50338. // Render targets
  50339. // Setup storage for target texture and bind it to correct framebuffer
  50340. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50341. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50342. const glType = utils.convert( texture.type );
  50343. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50344. const renderTargetProperties = properties.get( renderTarget );
  50345. const textureProperties = properties.get( texture );
  50346. textureProperties.__renderTarget = renderTarget;
  50347. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50348. const width = Math.max( 1, renderTarget.width >> level );
  50349. const height = Math.max( 1, renderTarget.height >> level );
  50350. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50351. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50352. } else {
  50353. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50354. }
  50355. }
  50356. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50357. if ( useMultisampledRTT( renderTarget ) ) {
  50358. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50359. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50360. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50361. }
  50362. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50363. }
  50364. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50365. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  50366. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50367. if ( renderTarget.depthBuffer ) {
  50368. // retrieve the depth attachment types
  50369. const depthTexture = renderTarget.depthTexture;
  50370. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50371. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50372. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50373. // set up the attachment
  50374. if ( useMultisampledRTT( renderTarget ) ) {
  50375. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50376. } else if ( useMultisample ) {
  50377. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50378. } else {
  50379. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50380. }
  50381. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50382. } else {
  50383. const textures = renderTarget.textures;
  50384. for ( let i = 0; i < textures.length; i ++ ) {
  50385. const texture = textures[ i ];
  50386. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50387. const glType = utils.convert( texture.type );
  50388. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50389. if ( useMultisampledRTT( renderTarget ) ) {
  50390. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50391. } else if ( useMultisample ) {
  50392. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50393. } else {
  50394. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50395. }
  50396. }
  50397. }
  50398. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50399. }
  50400. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50401. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50402. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50403. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50404. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50405. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50406. }
  50407. const textureProperties = properties.get( renderTarget.depthTexture );
  50408. textureProperties.__renderTarget = renderTarget;
  50409. // upload an empty depth texture with framebuffer size
  50410. if ( ! textureProperties.__webglTexture ||
  50411. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50412. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50413. renderTarget.depthTexture.image.width = renderTarget.width;
  50414. renderTarget.depthTexture.image.height = renderTarget.height;
  50415. renderTarget.depthTexture.needsUpdate = true;
  50416. }
  50417. if ( isCube ) {
  50418. // For cube depth textures, initialize and bind without uploading image data
  50419. if ( textureProperties.__webglInit === undefined ) {
  50420. textureProperties.__webglInit = true;
  50421. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50422. }
  50423. // Only create and allocate storage once
  50424. if ( textureProperties.__webglTexture === undefined ) {
  50425. textureProperties.__webglTexture = _gl.createTexture();
  50426. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50427. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50428. // Allocate storage for all 6 faces with correct depth texture format
  50429. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50430. const glType = utils.convert( renderTarget.depthTexture.type );
  50431. // Use proper internal format for depth textures
  50432. let glInternalFormat;
  50433. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50434. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50435. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50436. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50437. }
  50438. for ( let i = 0; i < 6; i ++ ) {
  50439. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50440. }
  50441. }
  50442. } else {
  50443. setTexture2D( renderTarget.depthTexture, 0 );
  50444. }
  50445. const webglDepthTexture = textureProperties.__webglTexture;
  50446. const samples = getRenderTargetSamples( renderTarget );
  50447. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50448. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50449. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50450. if ( useMultisampledRTT( renderTarget ) ) {
  50451. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50452. } else {
  50453. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50454. }
  50455. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50456. if ( useMultisampledRTT( renderTarget ) ) {
  50457. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50458. } else {
  50459. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50460. }
  50461. } else {
  50462. throw new Error( 'Unknown depthTexture format' );
  50463. }
  50464. }
  50465. // Setup GL resources for a non-texture depth buffer
  50466. function setupDepthRenderbuffer( renderTarget ) {
  50467. const renderTargetProperties = properties.get( renderTarget );
  50468. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50469. // if the bound depth texture has changed
  50470. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50471. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50472. const depthTexture = renderTarget.depthTexture;
  50473. if ( renderTargetProperties.__depthDisposeCallback ) {
  50474. renderTargetProperties.__depthDisposeCallback();
  50475. }
  50476. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50477. if ( depthTexture ) {
  50478. const disposeEvent = () => {
  50479. delete renderTargetProperties.__boundDepthTexture;
  50480. delete renderTargetProperties.__depthDisposeCallback;
  50481. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50482. };
  50483. depthTexture.addEventListener( 'dispose', disposeEvent );
  50484. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50485. }
  50486. renderTargetProperties.__boundDepthTexture = depthTexture;
  50487. }
  50488. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50489. if ( isCube ) {
  50490. // For cube render targets with depth texture, setup each face
  50491. for ( let i = 0; i < 6; i ++ ) {
  50492. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50493. }
  50494. } else {
  50495. const mipmaps = renderTarget.texture.mipmaps;
  50496. if ( mipmaps && mipmaps.length > 0 ) {
  50497. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50498. } else {
  50499. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50500. }
  50501. }
  50502. } else {
  50503. if ( isCube ) {
  50504. renderTargetProperties.__webglDepthbuffer = [];
  50505. for ( let i = 0; i < 6; i ++ ) {
  50506. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50507. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50508. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50509. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50510. } else {
  50511. // attach buffer if it's been created already
  50512. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50513. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50514. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50515. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50516. }
  50517. }
  50518. } else {
  50519. const mipmaps = renderTarget.texture.mipmaps;
  50520. if ( mipmaps && mipmaps.length > 0 ) {
  50521. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50522. } else {
  50523. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50524. }
  50525. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50526. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50527. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50528. } else {
  50529. // attach buffer if it's been created already
  50530. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50531. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50532. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50533. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50534. }
  50535. }
  50536. }
  50537. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50538. }
  50539. // rebind framebuffer with external textures
  50540. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50541. const renderTargetProperties = properties.get( renderTarget );
  50542. if ( colorTexture !== undefined ) {
  50543. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50544. }
  50545. if ( depthTexture !== undefined ) {
  50546. setupDepthRenderbuffer( renderTarget );
  50547. }
  50548. }
  50549. // Set up GL resources for the render target
  50550. function setupRenderTarget( renderTarget ) {
  50551. const texture = renderTarget.texture;
  50552. const renderTargetProperties = properties.get( renderTarget );
  50553. const textureProperties = properties.get( texture );
  50554. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50555. const textures = renderTarget.textures;
  50556. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50557. const isMultipleRenderTargets = ( textures.length > 1 );
  50558. if ( ! isMultipleRenderTargets ) {
  50559. if ( textureProperties.__webglTexture === undefined ) {
  50560. textureProperties.__webglTexture = _gl.createTexture();
  50561. }
  50562. textureProperties.__version = texture.version;
  50563. info.memory.textures ++;
  50564. }
  50565. // Setup framebuffer
  50566. if ( isCube ) {
  50567. renderTargetProperties.__webglFramebuffer = [];
  50568. for ( let i = 0; i < 6; i ++ ) {
  50569. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50570. renderTargetProperties.__webglFramebuffer[ i ] = [];
  50571. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50572. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  50573. }
  50574. } else {
  50575. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  50576. }
  50577. }
  50578. } else {
  50579. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50580. renderTargetProperties.__webglFramebuffer = [];
  50581. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50582. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  50583. }
  50584. } else {
  50585. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  50586. }
  50587. if ( isMultipleRenderTargets ) {
  50588. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50589. const attachmentProperties = properties.get( textures[ i ] );
  50590. if ( attachmentProperties.__webglTexture === undefined ) {
  50591. attachmentProperties.__webglTexture = _gl.createTexture();
  50592. info.memory.textures ++;
  50593. }
  50594. }
  50595. }
  50596. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  50597. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  50598. renderTargetProperties.__webglColorRenderbuffer = [];
  50599. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50600. for ( let i = 0; i < textures.length; i ++ ) {
  50601. const texture = textures[ i ];
  50602. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  50603. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50604. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50605. const glType = utils.convert( texture.type );
  50606. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  50607. const samples = getRenderTargetSamples( renderTarget );
  50608. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50609. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50610. }
  50611. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50612. if ( renderTarget.depthBuffer ) {
  50613. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  50614. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  50615. }
  50616. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50617. }
  50618. }
  50619. // Setup color buffer
  50620. if ( isCube ) {
  50621. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50622. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50623. for ( let i = 0; i < 6; i ++ ) {
  50624. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50625. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50626. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  50627. }
  50628. } else {
  50629. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  50630. }
  50631. }
  50632. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50633. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50634. }
  50635. state.unbindTexture();
  50636. } else if ( isMultipleRenderTargets ) {
  50637. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50638. const attachment = textures[ i ];
  50639. const attachmentProperties = properties.get( attachment );
  50640. let glTextureType = _gl.TEXTURE_2D;
  50641. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50642. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50643. }
  50644. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  50645. setTextureParameters( glTextureType, attachment );
  50646. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  50647. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  50648. generateMipmap( glTextureType );
  50649. }
  50650. }
  50651. state.unbindTexture();
  50652. } else {
  50653. let glTextureType = _gl.TEXTURE_2D;
  50654. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50655. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50656. }
  50657. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  50658. setTextureParameters( glTextureType, texture );
  50659. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50660. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50661. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  50662. }
  50663. } else {
  50664. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  50665. }
  50666. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50667. generateMipmap( glTextureType );
  50668. }
  50669. state.unbindTexture();
  50670. }
  50671. // Setup depth and stencil buffers
  50672. if ( renderTarget.depthBuffer ) {
  50673. setupDepthRenderbuffer( renderTarget );
  50674. }
  50675. }
  50676. function updateRenderTargetMipmap( renderTarget ) {
  50677. const textures = renderTarget.textures;
  50678. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50679. const texture = textures[ i ];
  50680. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50681. const targetType = getTargetType( renderTarget );
  50682. const webglTexture = properties.get( texture ).__webglTexture;
  50683. state.bindTexture( targetType, webglTexture );
  50684. generateMipmap( targetType );
  50685. state.unbindTexture();
  50686. }
  50687. }
  50688. }
  50689. const invalidationArrayRead = [];
  50690. const invalidationArrayDraw = [];
  50691. function updateMultisampleRenderTarget( renderTarget ) {
  50692. if ( renderTarget.samples > 0 ) {
  50693. if ( useMultisampledRTT( renderTarget ) === false ) {
  50694. const textures = renderTarget.textures;
  50695. const width = renderTarget.width;
  50696. const height = renderTarget.height;
  50697. let mask = _gl.COLOR_BUFFER_BIT;
  50698. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50699. const renderTargetProperties = properties.get( renderTarget );
  50700. const isMultipleRenderTargets = ( textures.length > 1 );
  50701. // If MRT we need to remove FBO attachments
  50702. if ( isMultipleRenderTargets ) {
  50703. for ( let i = 0; i < textures.length; i ++ ) {
  50704. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50705. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50706. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50707. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50708. }
  50709. }
  50710. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50711. const mipmaps = renderTarget.texture.mipmaps;
  50712. if ( mipmaps && mipmaps.length > 0 ) {
  50713. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50714. } else {
  50715. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50716. }
  50717. for ( let i = 0; i < textures.length; i ++ ) {
  50718. if ( renderTarget.resolveDepthBuffer ) {
  50719. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50720. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50721. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50722. }
  50723. if ( isMultipleRenderTargets ) {
  50724. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50725. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50726. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50727. }
  50728. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50729. if ( supportsInvalidateFramebuffer === true ) {
  50730. invalidationArrayRead.length = 0;
  50731. invalidationArrayDraw.length = 0;
  50732. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50733. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50734. invalidationArrayRead.push( depthStyle );
  50735. invalidationArrayDraw.push( depthStyle );
  50736. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50737. }
  50738. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50739. }
  50740. }
  50741. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50742. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50743. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50744. if ( isMultipleRenderTargets ) {
  50745. for ( let i = 0; i < textures.length; i ++ ) {
  50746. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50747. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50748. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50749. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50750. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50751. }
  50752. }
  50753. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50754. } else {
  50755. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50756. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50757. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50758. }
  50759. }
  50760. }
  50761. }
  50762. function getRenderTargetSamples( renderTarget ) {
  50763. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50764. }
  50765. function useMultisampledRTT( renderTarget ) {
  50766. const renderTargetProperties = properties.get( renderTarget );
  50767. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50768. }
  50769. function updateVideoTexture( texture ) {
  50770. const frame = info.render.frame;
  50771. // Check the last frame we updated the VideoTexture
  50772. if ( _videoTextures.get( texture ) !== frame ) {
  50773. _videoTextures.set( texture, frame );
  50774. texture.update();
  50775. }
  50776. }
  50777. function verifyColorSpace( texture, image ) {
  50778. const colorSpace = texture.colorSpace;
  50779. const format = texture.format;
  50780. const type = texture.type;
  50781. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50782. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50783. // sRGB
  50784. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50785. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50786. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50787. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50788. }
  50789. } else {
  50790. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  50791. }
  50792. }
  50793. return image;
  50794. }
  50795. function getDimensions( image ) {
  50796. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50797. // if intrinsic data are not available, fallback to width/height
  50798. _imageDimensions.width = image.naturalWidth || image.width;
  50799. _imageDimensions.height = image.naturalHeight || image.height;
  50800. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50801. _imageDimensions.width = image.displayWidth;
  50802. _imageDimensions.height = image.displayHeight;
  50803. } else {
  50804. _imageDimensions.width = image.width;
  50805. _imageDimensions.height = image.height;
  50806. }
  50807. return _imageDimensions;
  50808. }
  50809. //
  50810. this.allocateTextureUnit = allocateTextureUnit;
  50811. this.resetTextureUnits = resetTextureUnits;
  50812. this.setTexture2D = setTexture2D;
  50813. this.setTexture2DArray = setTexture2DArray;
  50814. this.setTexture3D = setTexture3D;
  50815. this.setTextureCube = setTextureCube;
  50816. this.rebindTextures = rebindTextures;
  50817. this.setupRenderTarget = setupRenderTarget;
  50818. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50819. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50820. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50821. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50822. this.useMultisampledRTT = useMultisampledRTT;
  50823. this.isReversedDepthBuffer = function () {
  50824. return state.buffers.depth.getReversed();
  50825. };
  50826. }
  50827. function WebGLUtils( gl, extensions ) {
  50828. function convert( p, colorSpace = NoColorSpace ) {
  50829. let extension;
  50830. const transfer = ColorManagement.getTransfer( colorSpace );
  50831. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50832. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50833. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50834. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50835. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  50836. if ( p === ByteType ) return gl.BYTE;
  50837. if ( p === ShortType ) return gl.SHORT;
  50838. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50839. if ( p === IntType ) return gl.INT;
  50840. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50841. if ( p === FloatType ) return gl.FLOAT;
  50842. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50843. if ( p === AlphaFormat ) return gl.ALPHA;
  50844. if ( p === RGBFormat ) return gl.RGB;
  50845. if ( p === RGBAFormat ) return gl.RGBA;
  50846. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50847. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50848. // WebGL2 formats.
  50849. if ( p === RedFormat ) return gl.RED;
  50850. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50851. if ( p === RGFormat ) return gl.RG;
  50852. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50853. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50854. // S3TC
  50855. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50856. if ( transfer === SRGBTransfer ) {
  50857. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50858. if ( extension !== null ) {
  50859. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50860. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50861. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50862. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50863. } else {
  50864. return null;
  50865. }
  50866. } else {
  50867. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50868. if ( extension !== null ) {
  50869. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50870. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50871. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50872. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50873. } else {
  50874. return null;
  50875. }
  50876. }
  50877. }
  50878. // PVRTC
  50879. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50880. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50881. if ( extension !== null ) {
  50882. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50883. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50884. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50885. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50886. } else {
  50887. return null;
  50888. }
  50889. }
  50890. // ETC
  50891. 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 ) {
  50892. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50893. if ( extension !== null ) {
  50894. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50895. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50896. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  50897. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  50898. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  50899. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  50900. } else {
  50901. return null;
  50902. }
  50903. }
  50904. // ASTC
  50905. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50906. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50907. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50908. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50909. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50910. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50911. if ( extension !== null ) {
  50912. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50913. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50914. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50915. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50916. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50917. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50918. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50919. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50920. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50921. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50922. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50923. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50924. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50925. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50926. } else {
  50927. return null;
  50928. }
  50929. }
  50930. // BPTC
  50931. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50932. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50933. if ( extension !== null ) {
  50934. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50935. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50936. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50937. } else {
  50938. return null;
  50939. }
  50940. }
  50941. // RGTC
  50942. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50943. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50944. if ( extension !== null ) {
  50945. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50946. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50947. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50948. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50949. } else {
  50950. return null;
  50951. }
  50952. }
  50953. //
  50954. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50955. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50956. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50957. }
  50958. return { convert: convert };
  50959. }
  50960. const _occlusion_vertex = `
  50961. void main() {
  50962. gl_Position = vec4( position, 1.0 );
  50963. }`;
  50964. const _occlusion_fragment = `
  50965. uniform sampler2DArray depthColor;
  50966. uniform float depthWidth;
  50967. uniform float depthHeight;
  50968. void main() {
  50969. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50970. if ( coord.x >= 1.0 ) {
  50971. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50972. } else {
  50973. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50974. }
  50975. }`;
  50976. /**
  50977. * A XR module that manages the access to the Depth Sensing API.
  50978. */
  50979. class WebXRDepthSensing {
  50980. /**
  50981. * Constructs a new depth sensing module.
  50982. */
  50983. constructor() {
  50984. /**
  50985. * An opaque texture representing the depth of the user's environment.
  50986. *
  50987. * @type {?ExternalTexture}
  50988. */
  50989. this.texture = null;
  50990. /**
  50991. * A plane mesh for visualizing the depth texture.
  50992. *
  50993. * @type {?Mesh}
  50994. */
  50995. this.mesh = null;
  50996. /**
  50997. * The depth near value.
  50998. *
  50999. * @type {number}
  51000. */
  51001. this.depthNear = 0;
  51002. /**
  51003. * The depth near far.
  51004. *
  51005. * @type {number}
  51006. */
  51007. this.depthFar = 0;
  51008. }
  51009. /**
  51010. * Inits the depth sensing module
  51011. *
  51012. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  51013. * @param {XRRenderState} renderState - The XR render state.
  51014. */
  51015. init( depthData, renderState ) {
  51016. if ( this.texture === null ) {
  51017. const texture = new ExternalTexture( depthData.texture );
  51018. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  51019. this.depthNear = depthData.depthNear;
  51020. this.depthFar = depthData.depthFar;
  51021. }
  51022. this.texture = texture;
  51023. }
  51024. }
  51025. /**
  51026. * Returns a plane mesh that visualizes the depth texture.
  51027. *
  51028. * @param {ArrayCamera} cameraXR - The XR camera.
  51029. * @return {?Mesh} The plane mesh.
  51030. */
  51031. getMesh( cameraXR ) {
  51032. if ( this.texture !== null ) {
  51033. if ( this.mesh === null ) {
  51034. const viewport = cameraXR.cameras[ 0 ].viewport;
  51035. const material = new ShaderMaterial( {
  51036. vertexShader: _occlusion_vertex,
  51037. fragmentShader: _occlusion_fragment,
  51038. uniforms: {
  51039. depthColor: { value: this.texture },
  51040. depthWidth: { value: viewport.z },
  51041. depthHeight: { value: viewport.w }
  51042. }
  51043. } );
  51044. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  51045. }
  51046. }
  51047. return this.mesh;
  51048. }
  51049. /**
  51050. * Resets the module
  51051. */
  51052. reset() {
  51053. this.texture = null;
  51054. this.mesh = null;
  51055. }
  51056. /**
  51057. * Returns a texture representing the depth of the user's environment.
  51058. *
  51059. * @return {?ExternalTexture} The depth texture.
  51060. */
  51061. getDepthTexture() {
  51062. return this.texture;
  51063. }
  51064. }
  51065. /**
  51066. * This class represents an abstraction of the WebXR Device API and is
  51067. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  51068. * interface that allows users to enable/disable XR and perform XR related
  51069. * tasks like for instance retrieving controllers.
  51070. *
  51071. * @augments EventDispatcher
  51072. * @hideconstructor
  51073. */
  51074. class WebXRManager extends EventDispatcher {
  51075. /**
  51076. * Constructs a new WebGL renderer.
  51077. *
  51078. * @param {WebGLRenderer} renderer - The renderer.
  51079. * @param {WebGL2RenderingContext} gl - The rendering context.
  51080. */
  51081. constructor( renderer, gl ) {
  51082. super();
  51083. const scope = this;
  51084. let session = null;
  51085. let framebufferScaleFactor = 1.0;
  51086. let referenceSpace = null;
  51087. let referenceSpaceType = 'local-floor';
  51088. // Set default foveation to maximum.
  51089. let foveation = 1.0;
  51090. let customReferenceSpace = null;
  51091. let pose = null;
  51092. let glBinding = null;
  51093. let glProjLayer = null;
  51094. let glBaseLayer = null;
  51095. let xrFrame = null;
  51096. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  51097. const depthSensing = new WebXRDepthSensing();
  51098. const cameraAccessTextures = {};
  51099. const attributes = gl.getContextAttributes();
  51100. let initialRenderTarget = null;
  51101. let newRenderTarget = null;
  51102. const controllers = [];
  51103. const controllerInputSources = [];
  51104. const currentSize = new Vector2();
  51105. let currentPixelRatio = null;
  51106. //
  51107. const cameraL = new PerspectiveCamera();
  51108. cameraL.viewport = new Vector4();
  51109. const cameraR = new PerspectiveCamera();
  51110. cameraR.viewport = new Vector4();
  51111. const cameras = [ cameraL, cameraR ];
  51112. const cameraXR = new ArrayCamera();
  51113. let _currentDepthNear = null;
  51114. let _currentDepthFar = null;
  51115. //
  51116. /**
  51117. * Whether the manager's XR camera should be automatically updated or not.
  51118. *
  51119. * @type {boolean}
  51120. * @default true
  51121. */
  51122. this.cameraAutoUpdate = true;
  51123. /**
  51124. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  51125. * if you are going to use XR in your app.
  51126. *
  51127. * @type {boolean}
  51128. * @default false
  51129. */
  51130. this.enabled = false;
  51131. /**
  51132. * Whether XR presentation is active or not.
  51133. *
  51134. * @type {boolean}
  51135. * @readonly
  51136. * @default false
  51137. */
  51138. this.isPresenting = false;
  51139. /**
  51140. * Returns a group representing the `target ray` space of the XR controller.
  51141. * Use this space for visualizing 3D objects that support the user in pointing
  51142. * tasks like UI interaction.
  51143. *
  51144. * @param {number} index - The index of the controller.
  51145. * @return {Group} A group representing the `target ray` space.
  51146. */
  51147. this.getController = function ( index ) {
  51148. let controller = controllers[ index ];
  51149. if ( controller === undefined ) {
  51150. controller = new WebXRController();
  51151. controllers[ index ] = controller;
  51152. }
  51153. return controller.getTargetRaySpace();
  51154. };
  51155. /**
  51156. * Returns a group representing the `grip` space of the XR controller.
  51157. * Use this space for visualizing 3D objects that support the user in pointing
  51158. * tasks like UI interaction.
  51159. *
  51160. * Note: If you want to show something in the user's hand AND offer a
  51161. * pointing ray at the same time, you'll want to attached the handheld object
  51162. * to the group returned by `getControllerGrip()` and the ray to the
  51163. * group returned by `getController()`. The idea is to have two
  51164. * different groups in two different coordinate spaces for the same WebXR
  51165. * controller.
  51166. *
  51167. * @param {number} index - The index of the controller.
  51168. * @return {Group} A group representing the `grip` space.
  51169. */
  51170. this.getControllerGrip = function ( index ) {
  51171. let controller = controllers[ index ];
  51172. if ( controller === undefined ) {
  51173. controller = new WebXRController();
  51174. controllers[ index ] = controller;
  51175. }
  51176. return controller.getGripSpace();
  51177. };
  51178. /**
  51179. * Returns a group representing the `hand` space of the XR controller.
  51180. * Use this space for visualizing 3D objects that support the user in pointing
  51181. * tasks like UI interaction.
  51182. *
  51183. * @param {number} index - The index of the controller.
  51184. * @return {Group} A group representing the `hand` space.
  51185. */
  51186. this.getHand = function ( index ) {
  51187. let controller = controllers[ index ];
  51188. if ( controller === undefined ) {
  51189. controller = new WebXRController();
  51190. controllers[ index ] = controller;
  51191. }
  51192. return controller.getHandSpace();
  51193. };
  51194. //
  51195. function onSessionEvent( event ) {
  51196. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  51197. if ( controllerIndex === -1 ) {
  51198. return;
  51199. }
  51200. const controller = controllers[ controllerIndex ];
  51201. if ( controller !== undefined ) {
  51202. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  51203. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  51204. }
  51205. }
  51206. function onSessionEnd() {
  51207. session.removeEventListener( 'select', onSessionEvent );
  51208. session.removeEventListener( 'selectstart', onSessionEvent );
  51209. session.removeEventListener( 'selectend', onSessionEvent );
  51210. session.removeEventListener( 'squeeze', onSessionEvent );
  51211. session.removeEventListener( 'squeezestart', onSessionEvent );
  51212. session.removeEventListener( 'squeezeend', onSessionEvent );
  51213. session.removeEventListener( 'end', onSessionEnd );
  51214. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  51215. for ( let i = 0; i < controllers.length; i ++ ) {
  51216. const inputSource = controllerInputSources[ i ];
  51217. if ( inputSource === null ) continue;
  51218. controllerInputSources[ i ] = null;
  51219. controllers[ i ].disconnect( inputSource );
  51220. }
  51221. _currentDepthNear = null;
  51222. _currentDepthFar = null;
  51223. depthSensing.reset();
  51224. for ( const key in cameraAccessTextures ) {
  51225. delete cameraAccessTextures[ key ];
  51226. }
  51227. // restore framebuffer/rendering state
  51228. renderer.setRenderTarget( initialRenderTarget );
  51229. glBaseLayer = null;
  51230. glProjLayer = null;
  51231. glBinding = null;
  51232. session = null;
  51233. newRenderTarget = null;
  51234. //
  51235. animation.stop();
  51236. scope.isPresenting = false;
  51237. renderer.setPixelRatio( currentPixelRatio );
  51238. renderer.setSize( currentSize.width, currentSize.height, false );
  51239. scope.dispatchEvent( { type: 'sessionend' } );
  51240. }
  51241. /**
  51242. * Sets the framebuffer scale factor.
  51243. *
  51244. * This method can not be used during a XR session.
  51245. *
  51246. * @param {number} value - The framebuffer scale factor.
  51247. */
  51248. this.setFramebufferScaleFactor = function ( value ) {
  51249. framebufferScaleFactor = value;
  51250. if ( scope.isPresenting === true ) {
  51251. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51252. }
  51253. };
  51254. /**
  51255. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51256. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51257. * improve tracking. Default is `local-floor`. Valid values can be found here
  51258. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51259. *
  51260. * This method can not be used during a XR session.
  51261. *
  51262. * @param {string} value - The reference space type.
  51263. */
  51264. this.setReferenceSpaceType = function ( value ) {
  51265. referenceSpaceType = value;
  51266. if ( scope.isPresenting === true ) {
  51267. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51268. }
  51269. };
  51270. /**
  51271. * Returns the XR reference space.
  51272. *
  51273. * @return {XRReferenceSpace} The XR reference space.
  51274. */
  51275. this.getReferenceSpace = function () {
  51276. return customReferenceSpace || referenceSpace;
  51277. };
  51278. /**
  51279. * Sets a custom XR reference space.
  51280. *
  51281. * @param {XRReferenceSpace} space - The XR reference space.
  51282. */
  51283. this.setReferenceSpace = function ( space ) {
  51284. customReferenceSpace = space;
  51285. };
  51286. /**
  51287. * Returns the current base layer.
  51288. *
  51289. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51290. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51291. *
  51292. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51293. */
  51294. this.getBaseLayer = function () {
  51295. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51296. };
  51297. /**
  51298. * Returns the current XR binding.
  51299. *
  51300. * Creates a new binding if needed and the browser is
  51301. * capable of doing so.
  51302. *
  51303. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51304. */
  51305. this.getBinding = function () {
  51306. if ( glBinding === null && supportsGlBinding ) {
  51307. glBinding = new XRWebGLBinding( session, gl );
  51308. }
  51309. return glBinding;
  51310. };
  51311. /**
  51312. * Returns the current XR frame.
  51313. *
  51314. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51315. */
  51316. this.getFrame = function () {
  51317. return xrFrame;
  51318. };
  51319. /**
  51320. * Returns the current XR session.
  51321. *
  51322. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51323. */
  51324. this.getSession = function () {
  51325. return session;
  51326. };
  51327. /**
  51328. * After a XR session has been requested usually with one of the `*Button` modules, it
  51329. * is injected into the renderer with this method. This method triggers the start of
  51330. * the actual XR rendering.
  51331. *
  51332. * @async
  51333. * @param {XRSession} value - The XR session to set.
  51334. * @return {Promise} A Promise that resolves when the session has been set.
  51335. */
  51336. this.setSession = async function ( value ) {
  51337. session = value;
  51338. if ( session !== null ) {
  51339. initialRenderTarget = renderer.getRenderTarget();
  51340. session.addEventListener( 'select', onSessionEvent );
  51341. session.addEventListener( 'selectstart', onSessionEvent );
  51342. session.addEventListener( 'selectend', onSessionEvent );
  51343. session.addEventListener( 'squeeze', onSessionEvent );
  51344. session.addEventListener( 'squeezestart', onSessionEvent );
  51345. session.addEventListener( 'squeezeend', onSessionEvent );
  51346. session.addEventListener( 'end', onSessionEnd );
  51347. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51348. if ( attributes.xrCompatible !== true ) {
  51349. await gl.makeXRCompatible();
  51350. }
  51351. currentPixelRatio = renderer.getPixelRatio();
  51352. renderer.getSize( currentSize );
  51353. // Check that the browser implements the necessary APIs to use an
  51354. // XRProjectionLayer rather than an XRWebGLLayer
  51355. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51356. if ( ! supportsLayers ) {
  51357. const layerInit = {
  51358. antialias: attributes.antialias,
  51359. alpha: true,
  51360. depth: attributes.depth,
  51361. stencil: attributes.stencil,
  51362. framebufferScaleFactor: framebufferScaleFactor
  51363. };
  51364. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51365. session.updateRenderState( { baseLayer: glBaseLayer } );
  51366. renderer.setPixelRatio( 1 );
  51367. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51368. newRenderTarget = new WebGLRenderTarget(
  51369. glBaseLayer.framebufferWidth,
  51370. glBaseLayer.framebufferHeight,
  51371. {
  51372. format: RGBAFormat,
  51373. type: UnsignedByteType,
  51374. colorSpace: renderer.outputColorSpace,
  51375. stencilBuffer: attributes.stencil,
  51376. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51377. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51378. }
  51379. );
  51380. } else {
  51381. let depthFormat = null;
  51382. let depthType = null;
  51383. let glDepthFormat = null;
  51384. if ( attributes.depth ) {
  51385. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51386. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51387. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51388. }
  51389. const projectionlayerInit = {
  51390. colorFormat: gl.RGBA8,
  51391. depthFormat: glDepthFormat,
  51392. scaleFactor: framebufferScaleFactor
  51393. };
  51394. glBinding = this.getBinding();
  51395. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51396. session.updateRenderState( { layers: [ glProjLayer ] } );
  51397. renderer.setPixelRatio( 1 );
  51398. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51399. newRenderTarget = new WebGLRenderTarget(
  51400. glProjLayer.textureWidth,
  51401. glProjLayer.textureHeight,
  51402. {
  51403. format: RGBAFormat,
  51404. type: UnsignedByteType,
  51405. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51406. stencilBuffer: attributes.stencil,
  51407. colorSpace: renderer.outputColorSpace,
  51408. samples: attributes.antialias ? 4 : 0,
  51409. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51410. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51411. } );
  51412. }
  51413. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51414. this.setFoveation( foveation );
  51415. customReferenceSpace = null;
  51416. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51417. animation.setContext( session );
  51418. animation.start();
  51419. scope.isPresenting = true;
  51420. scope.dispatchEvent( { type: 'sessionstart' } );
  51421. }
  51422. };
  51423. /**
  51424. * Returns the environment blend mode from the current XR session.
  51425. *
  51426. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51427. */
  51428. this.getEnvironmentBlendMode = function () {
  51429. if ( session !== null ) {
  51430. return session.environmentBlendMode;
  51431. }
  51432. };
  51433. /**
  51434. * Returns the current depth texture computed via depth sensing.
  51435. *
  51436. * See {@link WebXRDepthSensing#getDepthTexture}.
  51437. *
  51438. * @return {?Texture} The depth texture.
  51439. */
  51440. this.getDepthTexture = function () {
  51441. return depthSensing.getDepthTexture();
  51442. };
  51443. function onInputSourcesChange( event ) {
  51444. // Notify disconnected
  51445. for ( let i = 0; i < event.removed.length; i ++ ) {
  51446. const inputSource = event.removed[ i ];
  51447. const index = controllerInputSources.indexOf( inputSource );
  51448. if ( index >= 0 ) {
  51449. controllerInputSources[ index ] = null;
  51450. controllers[ index ].disconnect( inputSource );
  51451. }
  51452. }
  51453. // Notify connected
  51454. for ( let i = 0; i < event.added.length; i ++ ) {
  51455. const inputSource = event.added[ i ];
  51456. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51457. if ( controllerIndex === -1 ) {
  51458. // Assign input source a controller that currently has no input source
  51459. for ( let i = 0; i < controllers.length; i ++ ) {
  51460. if ( i >= controllerInputSources.length ) {
  51461. controllerInputSources.push( inputSource );
  51462. controllerIndex = i;
  51463. break;
  51464. } else if ( controllerInputSources[ i ] === null ) {
  51465. controllerInputSources[ i ] = inputSource;
  51466. controllerIndex = i;
  51467. break;
  51468. }
  51469. }
  51470. // If all controllers do currently receive input we ignore new ones
  51471. if ( controllerIndex === -1 ) break;
  51472. }
  51473. const controller = controllers[ controllerIndex ];
  51474. if ( controller ) {
  51475. controller.connect( inputSource );
  51476. }
  51477. }
  51478. }
  51479. //
  51480. const cameraLPos = new Vector3();
  51481. const cameraRPos = new Vector3();
  51482. /**
  51483. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51484. * the cameras' projection and world matrices have already been set.
  51485. * And that near and far planes are identical for both cameras.
  51486. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51487. *
  51488. * @param {ArrayCamera} camera - The camera to update.
  51489. * @param {PerspectiveCamera} cameraL - The left camera.
  51490. * @param {PerspectiveCamera} cameraR - The right camera.
  51491. */
  51492. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51493. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51494. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51495. const ipd = cameraLPos.distanceTo( cameraRPos );
  51496. const projL = cameraL.projectionMatrix.elements;
  51497. const projR = cameraR.projectionMatrix.elements;
  51498. // VR systems will have identical far and near planes, and
  51499. // most likely identical top and bottom frustum extents.
  51500. // Use the left camera for these values.
  51501. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51502. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51503. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51504. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51505. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51506. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51507. const left = near * leftFov;
  51508. const right = near * rightFov;
  51509. // Calculate the new camera's position offset from the
  51510. // left camera. xOffset should be roughly half `ipd`.
  51511. const zOffset = ipd / ( - leftFov + rightFov );
  51512. const xOffset = zOffset * - leftFov;
  51513. // TODO: Better way to apply this offset?
  51514. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51515. camera.translateX( xOffset );
  51516. camera.translateZ( zOffset );
  51517. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51518. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51519. // Check if the projection uses an infinite far plane.
  51520. if ( projL[ 10 ] === -1 ) {
  51521. // Use the projection matrix from the left eye.
  51522. // The camera offset is sufficient to include the view volumes
  51523. // of both eyes (assuming symmetric projections).
  51524. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51525. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51526. } else {
  51527. // Find the union of the frustum values of the cameras and scale
  51528. // the values so that the near plane's position does not change in world space,
  51529. // although must now be relative to the new union camera.
  51530. const near2 = near + zOffset;
  51531. const far2 = far + zOffset;
  51532. const left2 = left - xOffset;
  51533. const right2 = right + ( ipd - xOffset );
  51534. const top2 = topFov * far / far2 * near2;
  51535. const bottom2 = bottomFov * far / far2 * near2;
  51536. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51537. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51538. }
  51539. }
  51540. function updateCamera( camera, parent ) {
  51541. if ( parent === null ) {
  51542. camera.matrixWorld.copy( camera.matrix );
  51543. } else {
  51544. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51545. }
  51546. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51547. }
  51548. /**
  51549. * Updates the state of the XR camera. Use this method on app level if you
  51550. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51551. * camera of the scene as a parameter. The passed in camera's transformation
  51552. * is automatically adjusted to the position of the XR camera when calling
  51553. * this method.
  51554. *
  51555. * @param {Camera} camera - The camera.
  51556. */
  51557. this.updateCamera = function ( camera ) {
  51558. if ( session === null ) return;
  51559. let depthNear = camera.near;
  51560. let depthFar = camera.far;
  51561. if ( depthSensing.texture !== null ) {
  51562. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51563. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51564. }
  51565. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  51566. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  51567. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  51568. // Note that the new renderState won't apply until the next frame. See #18320
  51569. session.updateRenderState( {
  51570. depthNear: cameraXR.near,
  51571. depthFar: cameraXR.far
  51572. } );
  51573. _currentDepthNear = cameraXR.near;
  51574. _currentDepthFar = cameraXR.far;
  51575. }
  51576. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  51577. cameraXR.layers.mask = camera.layers.mask | 0b110;
  51578. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  51579. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  51580. const parent = camera.parent;
  51581. const cameras = cameraXR.cameras;
  51582. updateCamera( cameraXR, parent );
  51583. for ( let i = 0; i < cameras.length; i ++ ) {
  51584. updateCamera( cameras[ i ], parent );
  51585. }
  51586. // update projection matrix for proper view frustum culling
  51587. if ( cameras.length === 2 ) {
  51588. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  51589. } else {
  51590. // assume single camera setup (AR)
  51591. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  51592. }
  51593. // update user camera and its children
  51594. updateUserCamera( camera, cameraXR, parent );
  51595. };
  51596. function updateUserCamera( camera, cameraXR, parent ) {
  51597. if ( parent === null ) {
  51598. camera.matrix.copy( cameraXR.matrixWorld );
  51599. } else {
  51600. camera.matrix.copy( parent.matrixWorld );
  51601. camera.matrix.invert();
  51602. camera.matrix.multiply( cameraXR.matrixWorld );
  51603. }
  51604. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51605. camera.updateMatrixWorld( true );
  51606. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  51607. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  51608. if ( camera.isPerspectiveCamera ) {
  51609. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  51610. camera.zoom = 1;
  51611. }
  51612. }
  51613. /**
  51614. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  51615. * of the active XR session. For each view it holds a separate camera object.
  51616. *
  51617. * The camera's `fov` is currently not used and does not reflect the fov of
  51618. * the XR camera. If you need the fov on app level, you have to compute in
  51619. * manually from the XR camera's projection matrices.
  51620. *
  51621. * @return {ArrayCamera} The XR camera.
  51622. */
  51623. this.getCamera = function () {
  51624. return cameraXR;
  51625. };
  51626. /**
  51627. * Returns the amount of foveation used by the XR compositor for the projection layer.
  51628. *
  51629. * @return {number|undefined} The amount of foveation.
  51630. */
  51631. this.getFoveation = function () {
  51632. if ( glProjLayer === null && glBaseLayer === null ) {
  51633. return undefined;
  51634. }
  51635. return foveation;
  51636. };
  51637. /**
  51638. * Sets the foveation value.
  51639. *
  51640. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  51641. * and `1` means maximum foveation (the edges render at lower resolution).
  51642. */
  51643. this.setFoveation = function ( value ) {
  51644. // 0 = no foveation = full resolution
  51645. // 1 = maximum foveation = the edges render at lower resolution
  51646. foveation = value;
  51647. if ( glProjLayer !== null ) {
  51648. glProjLayer.fixedFoveation = value;
  51649. }
  51650. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  51651. glBaseLayer.fixedFoveation = value;
  51652. }
  51653. };
  51654. /**
  51655. * Returns `true` if depth sensing is supported.
  51656. *
  51657. * @return {boolean} Whether depth sensing is supported or not.
  51658. */
  51659. this.hasDepthSensing = function () {
  51660. return depthSensing.texture !== null;
  51661. };
  51662. /**
  51663. * Returns the depth sensing mesh.
  51664. *
  51665. * See {@link WebXRDepthSensing#getMesh}.
  51666. *
  51667. * @return {Mesh} The depth sensing mesh.
  51668. */
  51669. this.getDepthSensingMesh = function () {
  51670. return depthSensing.getMesh( cameraXR );
  51671. };
  51672. /**
  51673. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  51674. * Only available during the current animation loop.
  51675. *
  51676. * @param {XRCamera} xrCamera - The camera to query.
  51677. * @return {?Texture} An opaque texture representing the current raw camera frame.
  51678. */
  51679. this.getCameraTexture = function ( xrCamera ) {
  51680. return cameraAccessTextures[ xrCamera ];
  51681. };
  51682. // Animation Loop
  51683. let onAnimationFrameCallback = null;
  51684. function onAnimationFrame( time, frame ) {
  51685. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  51686. xrFrame = frame;
  51687. if ( pose !== null ) {
  51688. const views = pose.views;
  51689. if ( glBaseLayer !== null ) {
  51690. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  51691. renderer.setRenderTarget( newRenderTarget );
  51692. }
  51693. let cameraXRNeedsUpdate = false;
  51694. // check if it's necessary to rebuild cameraXR's camera list
  51695. if ( views.length !== cameraXR.cameras.length ) {
  51696. cameraXR.cameras.length = 0;
  51697. cameraXRNeedsUpdate = true;
  51698. }
  51699. for ( let i = 0; i < views.length; i ++ ) {
  51700. const view = views[ i ];
  51701. let viewport = null;
  51702. if ( glBaseLayer !== null ) {
  51703. viewport = glBaseLayer.getViewport( view );
  51704. } else {
  51705. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51706. viewport = glSubImage.viewport;
  51707. // For side-by-side projection, we only produce a single texture for both eyes.
  51708. if ( i === 0 ) {
  51709. renderer.setRenderTargetTextures(
  51710. newRenderTarget,
  51711. glSubImage.colorTexture,
  51712. glSubImage.depthStencilTexture );
  51713. renderer.setRenderTarget( newRenderTarget );
  51714. }
  51715. }
  51716. let camera = cameras[ i ];
  51717. if ( camera === undefined ) {
  51718. camera = new PerspectiveCamera();
  51719. camera.layers.enable( i );
  51720. camera.viewport = new Vector4();
  51721. cameras[ i ] = camera;
  51722. }
  51723. camera.matrix.fromArray( view.transform.matrix );
  51724. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51725. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51726. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51727. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51728. if ( i === 0 ) {
  51729. cameraXR.matrix.copy( camera.matrix );
  51730. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51731. }
  51732. if ( cameraXRNeedsUpdate === true ) {
  51733. cameraXR.cameras.push( camera );
  51734. }
  51735. }
  51736. //
  51737. const enabledFeatures = session.enabledFeatures;
  51738. const gpuDepthSensingEnabled = enabledFeatures &&
  51739. enabledFeatures.includes( 'depth-sensing' ) &&
  51740. session.depthUsage == 'gpu-optimized';
  51741. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51742. glBinding = scope.getBinding();
  51743. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51744. if ( depthData && depthData.isValid && depthData.texture ) {
  51745. depthSensing.init( depthData, session.renderState );
  51746. }
  51747. }
  51748. const cameraAccessEnabled = enabledFeatures &&
  51749. enabledFeatures.includes( 'camera-access' );
  51750. if ( cameraAccessEnabled && supportsGlBinding ) {
  51751. renderer.state.unbindTexture();
  51752. glBinding = scope.getBinding();
  51753. for ( let i = 0; i < views.length; i ++ ) {
  51754. const camera = views[ i ].camera;
  51755. if ( camera ) {
  51756. let cameraTex = cameraAccessTextures[ camera ];
  51757. if ( ! cameraTex ) {
  51758. cameraTex = new ExternalTexture();
  51759. cameraAccessTextures[ camera ] = cameraTex;
  51760. }
  51761. const glTexture = glBinding.getCameraImage( camera );
  51762. cameraTex.sourceTexture = glTexture;
  51763. }
  51764. }
  51765. }
  51766. }
  51767. //
  51768. for ( let i = 0; i < controllers.length; i ++ ) {
  51769. const inputSource = controllerInputSources[ i ];
  51770. const controller = controllers[ i ];
  51771. if ( inputSource !== null && controller !== undefined ) {
  51772. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51773. }
  51774. }
  51775. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51776. if ( frame.detectedPlanes ) {
  51777. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51778. }
  51779. xrFrame = null;
  51780. }
  51781. const animation = new WebGLAnimation();
  51782. animation.setAnimationLoop( onAnimationFrame );
  51783. this.setAnimationLoop = function ( callback ) {
  51784. onAnimationFrameCallback = callback;
  51785. };
  51786. this.dispose = function () {};
  51787. }
  51788. }
  51789. const _e1 = /*@__PURE__*/ new Euler();
  51790. const _m1 = /*@__PURE__*/ new Matrix4();
  51791. function WebGLMaterials( renderer, properties ) {
  51792. function refreshTransformUniform( map, uniform ) {
  51793. if ( map.matrixAutoUpdate === true ) {
  51794. map.updateMatrix();
  51795. }
  51796. uniform.value.copy( map.matrix );
  51797. }
  51798. function refreshFogUniforms( uniforms, fog ) {
  51799. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51800. if ( fog.isFog ) {
  51801. uniforms.fogNear.value = fog.near;
  51802. uniforms.fogFar.value = fog.far;
  51803. } else if ( fog.isFogExp2 ) {
  51804. uniforms.fogDensity.value = fog.density;
  51805. }
  51806. }
  51807. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51808. if ( material.isMeshBasicMaterial ) {
  51809. refreshUniformsCommon( uniforms, material );
  51810. } else if ( material.isMeshLambertMaterial ) {
  51811. refreshUniformsCommon( uniforms, material );
  51812. } else if ( material.isMeshToonMaterial ) {
  51813. refreshUniformsCommon( uniforms, material );
  51814. refreshUniformsToon( uniforms, material );
  51815. } else if ( material.isMeshPhongMaterial ) {
  51816. refreshUniformsCommon( uniforms, material );
  51817. refreshUniformsPhong( uniforms, material );
  51818. } else if ( material.isMeshStandardMaterial ) {
  51819. refreshUniformsCommon( uniforms, material );
  51820. refreshUniformsStandard( uniforms, material );
  51821. if ( material.isMeshPhysicalMaterial ) {
  51822. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51823. }
  51824. } else if ( material.isMeshMatcapMaterial ) {
  51825. refreshUniformsCommon( uniforms, material );
  51826. refreshUniformsMatcap( uniforms, material );
  51827. } else if ( material.isMeshDepthMaterial ) {
  51828. refreshUniformsCommon( uniforms, material );
  51829. } else if ( material.isMeshDistanceMaterial ) {
  51830. refreshUniformsCommon( uniforms, material );
  51831. refreshUniformsDistance( uniforms, material );
  51832. } else if ( material.isMeshNormalMaterial ) {
  51833. refreshUniformsCommon( uniforms, material );
  51834. } else if ( material.isLineBasicMaterial ) {
  51835. refreshUniformsLine( uniforms, material );
  51836. if ( material.isLineDashedMaterial ) {
  51837. refreshUniformsDash( uniforms, material );
  51838. }
  51839. } else if ( material.isPointsMaterial ) {
  51840. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51841. } else if ( material.isSpriteMaterial ) {
  51842. refreshUniformsSprites( uniforms, material );
  51843. } else if ( material.isShadowMaterial ) {
  51844. uniforms.color.value.copy( material.color );
  51845. uniforms.opacity.value = material.opacity;
  51846. } else if ( material.isShaderMaterial ) {
  51847. material.uniformsNeedUpdate = false; // #15581
  51848. }
  51849. }
  51850. function refreshUniformsCommon( uniforms, material ) {
  51851. uniforms.opacity.value = material.opacity;
  51852. if ( material.color ) {
  51853. uniforms.diffuse.value.copy( material.color );
  51854. }
  51855. if ( material.emissive ) {
  51856. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51857. }
  51858. if ( material.map ) {
  51859. uniforms.map.value = material.map;
  51860. refreshTransformUniform( material.map, uniforms.mapTransform );
  51861. }
  51862. if ( material.alphaMap ) {
  51863. uniforms.alphaMap.value = material.alphaMap;
  51864. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51865. }
  51866. if ( material.bumpMap ) {
  51867. uniforms.bumpMap.value = material.bumpMap;
  51868. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51869. uniforms.bumpScale.value = material.bumpScale;
  51870. if ( material.side === BackSide ) {
  51871. uniforms.bumpScale.value *= -1;
  51872. }
  51873. }
  51874. if ( material.normalMap ) {
  51875. uniforms.normalMap.value = material.normalMap;
  51876. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51877. uniforms.normalScale.value.copy( material.normalScale );
  51878. if ( material.side === BackSide ) {
  51879. uniforms.normalScale.value.negate();
  51880. }
  51881. }
  51882. if ( material.displacementMap ) {
  51883. uniforms.displacementMap.value = material.displacementMap;
  51884. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51885. uniforms.displacementScale.value = material.displacementScale;
  51886. uniforms.displacementBias.value = material.displacementBias;
  51887. }
  51888. if ( material.emissiveMap ) {
  51889. uniforms.emissiveMap.value = material.emissiveMap;
  51890. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51891. }
  51892. if ( material.specularMap ) {
  51893. uniforms.specularMap.value = material.specularMap;
  51894. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51895. }
  51896. if ( material.alphaTest > 0 ) {
  51897. uniforms.alphaTest.value = material.alphaTest;
  51898. }
  51899. const materialProperties = properties.get( material );
  51900. const envMap = materialProperties.envMap;
  51901. const envMapRotation = materialProperties.envMapRotation;
  51902. if ( envMap ) {
  51903. uniforms.envMap.value = envMap;
  51904. _e1.copy( envMapRotation );
  51905. // accommodate left-handed frame
  51906. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51907. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51908. // environment maps which are not cube render targets or PMREMs follow a different convention
  51909. _e1.y *= -1;
  51910. _e1.z *= -1;
  51911. }
  51912. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51913. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51914. uniforms.reflectivity.value = material.reflectivity;
  51915. uniforms.ior.value = material.ior;
  51916. uniforms.refractionRatio.value = material.refractionRatio;
  51917. }
  51918. if ( material.lightMap ) {
  51919. uniforms.lightMap.value = material.lightMap;
  51920. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51921. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51922. }
  51923. if ( material.aoMap ) {
  51924. uniforms.aoMap.value = material.aoMap;
  51925. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51926. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51927. }
  51928. }
  51929. function refreshUniformsLine( uniforms, material ) {
  51930. uniforms.diffuse.value.copy( material.color );
  51931. uniforms.opacity.value = material.opacity;
  51932. if ( material.map ) {
  51933. uniforms.map.value = material.map;
  51934. refreshTransformUniform( material.map, uniforms.mapTransform );
  51935. }
  51936. }
  51937. function refreshUniformsDash( uniforms, material ) {
  51938. uniforms.dashSize.value = material.dashSize;
  51939. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51940. uniforms.scale.value = material.scale;
  51941. }
  51942. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51943. uniforms.diffuse.value.copy( material.color );
  51944. uniforms.opacity.value = material.opacity;
  51945. uniforms.size.value = material.size * pixelRatio;
  51946. uniforms.scale.value = height * 0.5;
  51947. if ( material.map ) {
  51948. uniforms.map.value = material.map;
  51949. refreshTransformUniform( material.map, uniforms.uvTransform );
  51950. }
  51951. if ( material.alphaMap ) {
  51952. uniforms.alphaMap.value = material.alphaMap;
  51953. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51954. }
  51955. if ( material.alphaTest > 0 ) {
  51956. uniforms.alphaTest.value = material.alphaTest;
  51957. }
  51958. }
  51959. function refreshUniformsSprites( uniforms, material ) {
  51960. uniforms.diffuse.value.copy( material.color );
  51961. uniforms.opacity.value = material.opacity;
  51962. uniforms.rotation.value = material.rotation;
  51963. if ( material.map ) {
  51964. uniforms.map.value = material.map;
  51965. refreshTransformUniform( material.map, uniforms.mapTransform );
  51966. }
  51967. if ( material.alphaMap ) {
  51968. uniforms.alphaMap.value = material.alphaMap;
  51969. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51970. }
  51971. if ( material.alphaTest > 0 ) {
  51972. uniforms.alphaTest.value = material.alphaTest;
  51973. }
  51974. }
  51975. function refreshUniformsPhong( uniforms, material ) {
  51976. uniforms.specular.value.copy( material.specular );
  51977. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51978. }
  51979. function refreshUniformsToon( uniforms, material ) {
  51980. if ( material.gradientMap ) {
  51981. uniforms.gradientMap.value = material.gradientMap;
  51982. }
  51983. }
  51984. function refreshUniformsStandard( uniforms, material ) {
  51985. uniforms.metalness.value = material.metalness;
  51986. if ( material.metalnessMap ) {
  51987. uniforms.metalnessMap.value = material.metalnessMap;
  51988. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51989. }
  51990. uniforms.roughness.value = material.roughness;
  51991. if ( material.roughnessMap ) {
  51992. uniforms.roughnessMap.value = material.roughnessMap;
  51993. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51994. }
  51995. if ( material.envMap ) {
  51996. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51997. uniforms.envMapIntensity.value = material.envMapIntensity;
  51998. }
  51999. }
  52000. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  52001. uniforms.ior.value = material.ior; // also part of uniforms common
  52002. if ( material.sheen > 0 ) {
  52003. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  52004. uniforms.sheenRoughness.value = material.sheenRoughness;
  52005. if ( material.sheenColorMap ) {
  52006. uniforms.sheenColorMap.value = material.sheenColorMap;
  52007. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  52008. }
  52009. if ( material.sheenRoughnessMap ) {
  52010. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  52011. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  52012. }
  52013. }
  52014. if ( material.clearcoat > 0 ) {
  52015. uniforms.clearcoat.value = material.clearcoat;
  52016. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  52017. if ( material.clearcoatMap ) {
  52018. uniforms.clearcoatMap.value = material.clearcoatMap;
  52019. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  52020. }
  52021. if ( material.clearcoatRoughnessMap ) {
  52022. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  52023. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  52024. }
  52025. if ( material.clearcoatNormalMap ) {
  52026. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  52027. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  52028. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  52029. if ( material.side === BackSide ) {
  52030. uniforms.clearcoatNormalScale.value.negate();
  52031. }
  52032. }
  52033. }
  52034. if ( material.dispersion > 0 ) {
  52035. uniforms.dispersion.value = material.dispersion;
  52036. }
  52037. if ( material.iridescence > 0 ) {
  52038. uniforms.iridescence.value = material.iridescence;
  52039. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  52040. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  52041. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  52042. if ( material.iridescenceMap ) {
  52043. uniforms.iridescenceMap.value = material.iridescenceMap;
  52044. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  52045. }
  52046. if ( material.iridescenceThicknessMap ) {
  52047. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  52048. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  52049. }
  52050. }
  52051. if ( material.transmission > 0 ) {
  52052. uniforms.transmission.value = material.transmission;
  52053. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  52054. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  52055. if ( material.transmissionMap ) {
  52056. uniforms.transmissionMap.value = material.transmissionMap;
  52057. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  52058. }
  52059. uniforms.thickness.value = material.thickness;
  52060. if ( material.thicknessMap ) {
  52061. uniforms.thicknessMap.value = material.thicknessMap;
  52062. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  52063. }
  52064. uniforms.attenuationDistance.value = material.attenuationDistance;
  52065. uniforms.attenuationColor.value.copy( material.attenuationColor );
  52066. }
  52067. if ( material.anisotropy > 0 ) {
  52068. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  52069. if ( material.anisotropyMap ) {
  52070. uniforms.anisotropyMap.value = material.anisotropyMap;
  52071. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  52072. }
  52073. }
  52074. uniforms.specularIntensity.value = material.specularIntensity;
  52075. uniforms.specularColor.value.copy( material.specularColor );
  52076. if ( material.specularColorMap ) {
  52077. uniforms.specularColorMap.value = material.specularColorMap;
  52078. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  52079. }
  52080. if ( material.specularIntensityMap ) {
  52081. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  52082. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  52083. }
  52084. }
  52085. function refreshUniformsMatcap( uniforms, material ) {
  52086. if ( material.matcap ) {
  52087. uniforms.matcap.value = material.matcap;
  52088. }
  52089. }
  52090. function refreshUniformsDistance( uniforms, material ) {
  52091. const light = properties.get( material ).light;
  52092. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  52093. uniforms.nearDistance.value = light.shadow.camera.near;
  52094. uniforms.farDistance.value = light.shadow.camera.far;
  52095. }
  52096. return {
  52097. refreshFogUniforms: refreshFogUniforms,
  52098. refreshMaterialUniforms: refreshMaterialUniforms
  52099. };
  52100. }
  52101. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  52102. let buffers = {};
  52103. let updateList = {};
  52104. let allocatedBindingPoints = [];
  52105. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  52106. function bind( uniformsGroup, program ) {
  52107. const webglProgram = program.program;
  52108. state.uniformBlockBinding( uniformsGroup, webglProgram );
  52109. }
  52110. function update( uniformsGroup, program ) {
  52111. let buffer = buffers[ uniformsGroup.id ];
  52112. if ( buffer === undefined ) {
  52113. prepareUniformsGroup( uniformsGroup );
  52114. buffer = createBuffer( uniformsGroup );
  52115. buffers[ uniformsGroup.id ] = buffer;
  52116. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  52117. }
  52118. // ensure to update the binding points/block indices mapping for this program
  52119. const webglProgram = program.program;
  52120. state.updateUBOMapping( uniformsGroup, webglProgram );
  52121. // update UBO once per frame
  52122. const frame = info.render.frame;
  52123. if ( updateList[ uniformsGroup.id ] !== frame ) {
  52124. updateBufferData( uniformsGroup );
  52125. updateList[ uniformsGroup.id ] = frame;
  52126. }
  52127. }
  52128. function createBuffer( uniformsGroup ) {
  52129. // the setup of an UBO is independent of a particular shader program but global
  52130. const bindingPointIndex = allocateBindingPointIndex();
  52131. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  52132. const buffer = gl.createBuffer();
  52133. const size = uniformsGroup.__size;
  52134. const usage = uniformsGroup.usage;
  52135. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52136. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  52137. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52138. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  52139. return buffer;
  52140. }
  52141. function allocateBindingPointIndex() {
  52142. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  52143. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  52144. allocatedBindingPoints.push( i );
  52145. return i;
  52146. }
  52147. }
  52148. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  52149. return 0;
  52150. }
  52151. function updateBufferData( uniformsGroup ) {
  52152. const buffer = buffers[ uniformsGroup.id ];
  52153. const uniforms = uniformsGroup.uniforms;
  52154. const cache = uniformsGroup.__cache;
  52155. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52156. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  52157. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52158. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52159. const uniform = uniformArray[ j ];
  52160. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  52161. const offset = uniform.__offset;
  52162. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52163. let arrayOffset = 0;
  52164. for ( let k = 0; k < values.length; k ++ ) {
  52165. const value = values[ k ];
  52166. const info = getUniformSize( value );
  52167. // TODO add integer and struct support
  52168. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52169. uniform.__data[ 0 ] = value;
  52170. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  52171. } else if ( value.isMatrix3 ) {
  52172. // manually converting 3x3 to 3x4
  52173. uniform.__data[ 0 ] = value.elements[ 0 ];
  52174. uniform.__data[ 1 ] = value.elements[ 1 ];
  52175. uniform.__data[ 2 ] = value.elements[ 2 ];
  52176. uniform.__data[ 3 ] = 0;
  52177. uniform.__data[ 4 ] = value.elements[ 3 ];
  52178. uniform.__data[ 5 ] = value.elements[ 4 ];
  52179. uniform.__data[ 6 ] = value.elements[ 5 ];
  52180. uniform.__data[ 7 ] = 0;
  52181. uniform.__data[ 8 ] = value.elements[ 6 ];
  52182. uniform.__data[ 9 ] = value.elements[ 7 ];
  52183. uniform.__data[ 10 ] = value.elements[ 8 ];
  52184. uniform.__data[ 11 ] = 0;
  52185. } else {
  52186. value.toArray( uniform.__data, arrayOffset );
  52187. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  52188. }
  52189. }
  52190. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  52191. }
  52192. }
  52193. }
  52194. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52195. }
  52196. function hasUniformChanged( uniform, index, indexArray, cache ) {
  52197. const value = uniform.value;
  52198. const indexString = index + '_' + indexArray;
  52199. if ( cache[ indexString ] === undefined ) {
  52200. // cache entry does not exist so far
  52201. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52202. cache[ indexString ] = value;
  52203. } else {
  52204. cache[ indexString ] = value.clone();
  52205. }
  52206. return true;
  52207. } else {
  52208. const cachedObject = cache[ indexString ];
  52209. // compare current value with cached entry
  52210. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52211. if ( cachedObject !== value ) {
  52212. cache[ indexString ] = value;
  52213. return true;
  52214. }
  52215. } else {
  52216. if ( cachedObject.equals( value ) === false ) {
  52217. cachedObject.copy( value );
  52218. return true;
  52219. }
  52220. }
  52221. }
  52222. return false;
  52223. }
  52224. function prepareUniformsGroup( uniformsGroup ) {
  52225. // determine total buffer size according to the STD140 layout
  52226. // Hint: STD140 is the only supported layout in WebGL 2
  52227. const uniforms = uniformsGroup.uniforms;
  52228. let offset = 0; // global buffer offset in bytes
  52229. const chunkSize = 16; // size of a chunk in bytes
  52230. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52231. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52232. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52233. const uniform = uniformArray[ j ];
  52234. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52235. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52236. const value = values[ k ];
  52237. const info = getUniformSize( value );
  52238. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52239. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52240. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52241. offset += chunkPadding;
  52242. // Check for chunk overflow
  52243. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52244. // Add padding and adjust offset
  52245. offset += ( chunkSize - chunkStart );
  52246. }
  52247. // the following two properties will be used for partial buffer updates
  52248. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52249. uniform.__offset = offset;
  52250. // Update the global offset
  52251. offset += info.storage;
  52252. }
  52253. }
  52254. }
  52255. // ensure correct final padding
  52256. const chunkOffset = offset % chunkSize;
  52257. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52258. //
  52259. uniformsGroup.__size = offset;
  52260. uniformsGroup.__cache = {};
  52261. return this;
  52262. }
  52263. function getUniformSize( value ) {
  52264. const info = {
  52265. boundary: 0, // bytes
  52266. storage: 0 // bytes
  52267. };
  52268. // determine sizes according to STD140
  52269. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52270. // float/int/bool
  52271. info.boundary = 4;
  52272. info.storage = 4;
  52273. } else if ( value.isVector2 ) {
  52274. // vec2
  52275. info.boundary = 8;
  52276. info.storage = 8;
  52277. } else if ( value.isVector3 || value.isColor ) {
  52278. // vec3
  52279. info.boundary = 16;
  52280. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52281. } else if ( value.isVector4 ) {
  52282. // vec4
  52283. info.boundary = 16;
  52284. info.storage = 16;
  52285. } else if ( value.isMatrix3 ) {
  52286. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52287. info.boundary = 48;
  52288. info.storage = 48;
  52289. } else if ( value.isMatrix4 ) {
  52290. // mat4
  52291. info.boundary = 64;
  52292. info.storage = 64;
  52293. } else if ( value.isTexture ) {
  52294. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52295. } else {
  52296. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52297. }
  52298. return info;
  52299. }
  52300. function onUniformsGroupsDispose( event ) {
  52301. const uniformsGroup = event.target;
  52302. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52303. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52304. allocatedBindingPoints.splice( index, 1 );
  52305. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52306. delete buffers[ uniformsGroup.id ];
  52307. delete updateList[ uniformsGroup.id ];
  52308. }
  52309. function dispose() {
  52310. for ( const id in buffers ) {
  52311. gl.deleteBuffer( buffers[ id ] );
  52312. }
  52313. allocatedBindingPoints = [];
  52314. buffers = {};
  52315. updateList = {};
  52316. }
  52317. return {
  52318. bind: bind,
  52319. update: update,
  52320. dispose: dispose
  52321. };
  52322. }
  52323. /**
  52324. * Precomputed DFG LUT for Image-Based Lighting
  52325. * Resolution: 16x16
  52326. * Samples: 4096 per texel
  52327. * Format: RG16F (2 half floats per texel: scale, bias)
  52328. */
  52329. const DATA = new Uint16Array( [
  52330. 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,
  52331. 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,
  52332. 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,
  52333. 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,
  52334. 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,
  52335. 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,
  52336. 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,
  52337. 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,
  52338. 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,
  52339. 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,
  52340. 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,
  52341. 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,
  52342. 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,
  52343. 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,
  52344. 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,
  52345. 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
  52346. ] );
  52347. let lut = null;
  52348. function getDFGLUT() {
  52349. if ( lut === null ) {
  52350. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  52351. lut.name = 'DFG_LUT';
  52352. lut.minFilter = LinearFilter;
  52353. lut.magFilter = LinearFilter;
  52354. lut.wrapS = ClampToEdgeWrapping;
  52355. lut.wrapT = ClampToEdgeWrapping;
  52356. lut.generateMipmaps = false;
  52357. lut.needsUpdate = true;
  52358. }
  52359. return lut;
  52360. }
  52361. /**
  52362. * This renderer uses WebGL 2 to display scenes.
  52363. *
  52364. * WebGL 1 is not supported since `r163`.
  52365. */
  52366. class WebGLRenderer {
  52367. /**
  52368. * Constructs a new WebGL renderer.
  52369. *
  52370. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52371. */
  52372. constructor( parameters = {} ) {
  52373. const {
  52374. canvas = createCanvasElement(),
  52375. context = null,
  52376. depth = true,
  52377. stencil = false,
  52378. alpha = false,
  52379. antialias = false,
  52380. premultipliedAlpha = true,
  52381. preserveDrawingBuffer = false,
  52382. powerPreference = 'default',
  52383. failIfMajorPerformanceCaveat = false,
  52384. reversedDepthBuffer = false,
  52385. outputBufferType = UnsignedByteType,
  52386. } = parameters;
  52387. /**
  52388. * This flag can be used for type testing.
  52389. *
  52390. * @type {boolean}
  52391. * @readonly
  52392. * @default true
  52393. */
  52394. this.isWebGLRenderer = true;
  52395. let _alpha;
  52396. if ( context !== null ) {
  52397. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52398. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52399. }
  52400. _alpha = context.getContextAttributes().alpha;
  52401. } else {
  52402. _alpha = alpha;
  52403. }
  52404. const _outputBufferType = outputBufferType;
  52405. const INTEGER_FORMATS = new Set( [
  52406. RGBAIntegerFormat,
  52407. RGIntegerFormat,
  52408. RedIntegerFormat
  52409. ] );
  52410. const UNSIGNED_TYPES = new Set( [
  52411. UnsignedByteType,
  52412. UnsignedIntType,
  52413. UnsignedShortType,
  52414. UnsignedInt248Type,
  52415. UnsignedShort4444Type,
  52416. UnsignedShort5551Type
  52417. ] );
  52418. const uintClearColor = new Uint32Array( 4 );
  52419. const intClearColor = new Int32Array( 4 );
  52420. let currentRenderList = null;
  52421. let currentRenderState = null;
  52422. // render() can be called from within a callback triggered by another render.
  52423. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52424. const renderListStack = [];
  52425. const renderStateStack = [];
  52426. // internal render target for non-UnsignedByteType color buffer
  52427. let output = null;
  52428. // public properties
  52429. /**
  52430. * A canvas where the renderer draws its output.This is automatically created by the renderer
  52431. * in the constructor (if not provided already); you just need to add it to your page like so:
  52432. * ```js
  52433. * document.body.appendChild( renderer.domElement );
  52434. * ```
  52435. *
  52436. * @type {HTMLCanvasElement|OffscreenCanvas}
  52437. */
  52438. this.domElement = canvas;
  52439. /**
  52440. * A object with debug configuration settings.
  52441. *
  52442. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52443. * checked for errors during compilation and linkage process. It may be useful to disable
  52444. * this check in production for performance gain. It is strongly recommended to keep these
  52445. * checks enabled during development. If the shader does not compile and link - it will not
  52446. * work and associated material will not render.
  52447. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52448. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52449. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52450. * Assigning a custom function disables the default error reporting.
  52451. *
  52452. * @type {Object}
  52453. */
  52454. this.debug = {
  52455. /**
  52456. * Enables error checking and reporting when shader programs are being compiled.
  52457. * @type {boolean}
  52458. */
  52459. checkShaderErrors: true,
  52460. /**
  52461. * Callback for custom error reporting.
  52462. * @type {?Function}
  52463. */
  52464. onShaderError: null
  52465. };
  52466. // clearing
  52467. /**
  52468. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52469. *
  52470. * @type {boolean}
  52471. * @default true
  52472. */
  52473. this.autoClear = true;
  52474. /**
  52475. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52476. * the color buffer or not.
  52477. *
  52478. * @type {boolean}
  52479. * @default true
  52480. */
  52481. this.autoClearColor = true;
  52482. /**
  52483. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52484. * the depth buffer or not.
  52485. *
  52486. * @type {boolean}
  52487. * @default true
  52488. */
  52489. this.autoClearDepth = true;
  52490. /**
  52491. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52492. * the stencil buffer or not.
  52493. *
  52494. * @type {boolean}
  52495. * @default true
  52496. */
  52497. this.autoClearStencil = true;
  52498. // scene graph
  52499. /**
  52500. * Whether the renderer should sort objects or not.
  52501. *
  52502. * Note: Sorting is used to attempt to properly render objects that have some
  52503. * degree of transparency. By definition, sorting objects may not work in all
  52504. * cases. Depending on the needs of application, it may be necessary to turn
  52505. * off sorting and use other methods to deal with transparency rendering e.g.
  52506. * manually determining each object's rendering order.
  52507. *
  52508. * @type {boolean}
  52509. * @default true
  52510. */
  52511. this.sortObjects = true;
  52512. // user-defined clipping
  52513. /**
  52514. * User-defined clipping planes specified in world space. These planes apply globally.
  52515. * Points in space whose dot product with the plane is negative are cut away.
  52516. *
  52517. * @type {Array<Plane>}
  52518. */
  52519. this.clippingPlanes = [];
  52520. /**
  52521. * Whether the renderer respects object-level clipping planes or not.
  52522. *
  52523. * @type {boolean}
  52524. * @default false
  52525. */
  52526. this.localClippingEnabled = false;
  52527. // tone mapping
  52528. /**
  52529. * The tone mapping technique of the renderer.
  52530. *
  52531. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52532. * @default NoToneMapping
  52533. */
  52534. this.toneMapping = NoToneMapping;
  52535. /**
  52536. * Exposure level of tone mapping.
  52537. *
  52538. * @type {number}
  52539. * @default 1
  52540. */
  52541. this.toneMappingExposure = 1.0;
  52542. // transmission
  52543. /**
  52544. * The normalized resolution scale for the transmission render target, measured in percentage
  52545. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52546. * when using {@link MeshPhysicalMaterial#transmission}.
  52547. *
  52548. * @type {number}
  52549. * @default 1
  52550. */
  52551. this.transmissionResolutionScale = 1.0;
  52552. // internal properties
  52553. const _this = this;
  52554. let _isContextLost = false;
  52555. // internal state cache
  52556. this._outputColorSpace = SRGBColorSpace;
  52557. let _currentActiveCubeFace = 0;
  52558. let _currentActiveMipmapLevel = 0;
  52559. let _currentRenderTarget = null;
  52560. let _currentMaterialId = -1;
  52561. let _currentCamera = null;
  52562. const _currentViewport = new Vector4();
  52563. const _currentScissor = new Vector4();
  52564. let _currentScissorTest = null;
  52565. const _currentClearColor = new Color( 0x000000 );
  52566. let _currentClearAlpha = 0;
  52567. //
  52568. let _width = canvas.width;
  52569. let _height = canvas.height;
  52570. let _pixelRatio = 1;
  52571. let _opaqueSort = null;
  52572. let _transparentSort = null;
  52573. const _viewport = new Vector4( 0, 0, _width, _height );
  52574. const _scissor = new Vector4( 0, 0, _width, _height );
  52575. let _scissorTest = false;
  52576. // frustum
  52577. const _frustum = new Frustum();
  52578. // clipping
  52579. let _clippingEnabled = false;
  52580. let _localClippingEnabled = false;
  52581. // camera matrices cache
  52582. const _projScreenMatrix = new Matrix4();
  52583. const _vector3 = new Vector3();
  52584. const _vector4 = new Vector4();
  52585. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  52586. let _renderBackground = false;
  52587. function getTargetPixelRatio() {
  52588. return _currentRenderTarget === null ? _pixelRatio : 1;
  52589. }
  52590. // initialize
  52591. let _gl = context;
  52592. function getContext( contextName, contextAttributes ) {
  52593. return canvas.getContext( contextName, contextAttributes );
  52594. }
  52595. try {
  52596. const contextAttributes = {
  52597. alpha: true,
  52598. depth,
  52599. stencil,
  52600. antialias,
  52601. premultipliedAlpha,
  52602. preserveDrawingBuffer,
  52603. powerPreference,
  52604. failIfMajorPerformanceCaveat,
  52605. };
  52606. // OffscreenCanvas does not have setAttribute, see #22811
  52607. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  52608. // event listeners must be registered before WebGL context is created, see #12753
  52609. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  52610. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  52611. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52612. if ( _gl === null ) {
  52613. const contextName = 'webgl2';
  52614. _gl = getContext( contextName, contextAttributes );
  52615. if ( _gl === null ) {
  52616. if ( getContext( contextName ) ) {
  52617. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  52618. } else {
  52619. throw new Error( 'Error creating WebGL context.' );
  52620. }
  52621. }
  52622. }
  52623. } catch ( e ) {
  52624. error( 'WebGLRenderer: ' + e.message );
  52625. throw e;
  52626. }
  52627. let extensions, capabilities, state, info;
  52628. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  52629. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  52630. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  52631. let utils, bindingStates, uniformsGroups;
  52632. function initGLContext() {
  52633. extensions = new WebGLExtensions( _gl );
  52634. extensions.init();
  52635. utils = new WebGLUtils( _gl, extensions );
  52636. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  52637. state = new WebGLState( _gl, extensions );
  52638. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  52639. state.buffers.depth.setReversed( true );
  52640. }
  52641. info = new WebGLInfo( _gl );
  52642. properties = new WebGLProperties();
  52643. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  52644. cubemaps = new WebGLCubeMaps( _this );
  52645. cubeuvmaps = new WebGLCubeUVMaps( _this );
  52646. attributes = new WebGLAttributes( _gl );
  52647. bindingStates = new WebGLBindingStates( _gl, attributes );
  52648. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  52649. objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info );
  52650. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  52651. clipping = new WebGLClipping( properties );
  52652. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  52653. materials = new WebGLMaterials( _this, properties );
  52654. renderLists = new WebGLRenderLists();
  52655. renderStates = new WebGLRenderStates( extensions );
  52656. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  52657. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  52658. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  52659. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  52660. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  52661. info.programs = programCache.programs;
  52662. /**
  52663. * Holds details about the capabilities of the current rendering context.
  52664. *
  52665. * @name WebGLRenderer#capabilities
  52666. * @type {WebGLRenderer~Capabilities}
  52667. */
  52668. _this.capabilities = capabilities;
  52669. /**
  52670. * Provides methods for retrieving and testing WebGL extensions.
  52671. *
  52672. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  52673. * and return the extension object if available.
  52674. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  52675. *
  52676. * @name WebGLRenderer#extensions
  52677. * @type {Object}
  52678. */
  52679. _this.extensions = extensions;
  52680. /**
  52681. * Used to track properties of other objects like native WebGL objects.
  52682. *
  52683. * @name WebGLRenderer#properties
  52684. * @type {Object}
  52685. */
  52686. _this.properties = properties;
  52687. /**
  52688. * Manages the render lists of the renderer.
  52689. *
  52690. * @name WebGLRenderer#renderLists
  52691. * @type {Object}
  52692. */
  52693. _this.renderLists = renderLists;
  52694. /**
  52695. * Interface for managing shadows.
  52696. *
  52697. * @name WebGLRenderer#shadowMap
  52698. * @type {WebGLRenderer~ShadowMap}
  52699. */
  52700. _this.shadowMap = shadowMap;
  52701. /**
  52702. * Interface for managing the WebGL state.
  52703. *
  52704. * @name WebGLRenderer#state
  52705. * @type {Object}
  52706. */
  52707. _this.state = state;
  52708. /**
  52709. * Holds a series of statistical information about the GPU memory
  52710. * and the rendering process. Useful for debugging and monitoring.
  52711. *
  52712. * By default these data are reset at each render call but when having
  52713. * multiple render passes per frame (e.g. when using post processing) it can
  52714. * be preferred to reset with a custom pattern. First, set `autoReset` to
  52715. * `false`.
  52716. * ```js
  52717. * renderer.info.autoReset = false;
  52718. * ```
  52719. * Call `reset()` whenever you have finished to render a single frame.
  52720. * ```js
  52721. * renderer.info.reset();
  52722. * ```
  52723. *
  52724. * @name WebGLRenderer#info
  52725. * @type {WebGLRenderer~Info}
  52726. */
  52727. _this.info = info;
  52728. }
  52729. initGLContext();
  52730. // initialize internal render target for non-UnsignedByteType color buffer
  52731. if ( _outputBufferType !== UnsignedByteType ) {
  52732. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  52733. }
  52734. // xr
  52735. const xr = new WebXRManager( _this, _gl );
  52736. /**
  52737. * A reference to the XR manager.
  52738. *
  52739. * @type {WebXRManager}
  52740. */
  52741. this.xr = xr;
  52742. /**
  52743. * Returns the rendering context.
  52744. *
  52745. * @return {WebGL2RenderingContext} The rendering context.
  52746. */
  52747. this.getContext = function () {
  52748. return _gl;
  52749. };
  52750. /**
  52751. * Returns the rendering context attributes.
  52752. *
  52753. * @return {WebGLContextAttributes} The rendering context attributes.
  52754. */
  52755. this.getContextAttributes = function () {
  52756. return _gl.getContextAttributes();
  52757. };
  52758. /**
  52759. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52760. */
  52761. this.forceContextLoss = function () {
  52762. const extension = extensions.get( 'WEBGL_lose_context' );
  52763. if ( extension ) extension.loseContext();
  52764. };
  52765. /**
  52766. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52767. */
  52768. this.forceContextRestore = function () {
  52769. const extension = extensions.get( 'WEBGL_lose_context' );
  52770. if ( extension ) extension.restoreContext();
  52771. };
  52772. /**
  52773. * Returns the pixel ratio.
  52774. *
  52775. * @return {number} The pixel ratio.
  52776. */
  52777. this.getPixelRatio = function () {
  52778. return _pixelRatio;
  52779. };
  52780. /**
  52781. * Sets the given pixel ratio and resizes the canvas if necessary.
  52782. *
  52783. * @param {number} value - The pixel ratio.
  52784. */
  52785. this.setPixelRatio = function ( value ) {
  52786. if ( value === undefined ) return;
  52787. _pixelRatio = value;
  52788. this.setSize( _width, _height, false );
  52789. };
  52790. /**
  52791. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52792. *
  52793. * @param {Vector2} target - The method writes the result in this target object.
  52794. * @return {Vector2} The renderer's size in logical pixels.
  52795. */
  52796. this.getSize = function ( target ) {
  52797. return target.set( _width, _height );
  52798. };
  52799. /**
  52800. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52801. * into account, and also sets the viewport to fit that size, starting in (0,
  52802. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52803. *
  52804. * @param {number} width - The width in logical pixels.
  52805. * @param {number} height - The height in logical pixels.
  52806. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52807. */
  52808. this.setSize = function ( width, height, updateStyle = true ) {
  52809. if ( xr.isPresenting ) {
  52810. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52811. return;
  52812. }
  52813. _width = width;
  52814. _height = height;
  52815. canvas.width = Math.floor( width * _pixelRatio );
  52816. canvas.height = Math.floor( height * _pixelRatio );
  52817. if ( updateStyle === true ) {
  52818. canvas.style.width = width + 'px';
  52819. canvas.style.height = height + 'px';
  52820. }
  52821. if ( output !== null ) {
  52822. output.setSize( canvas.width, canvas.height );
  52823. }
  52824. this.setViewport( 0, 0, width, height );
  52825. };
  52826. /**
  52827. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52828. *
  52829. * @param {Vector2} target - The method writes the result in this target object.
  52830. * @return {Vector2} The drawing buffer size.
  52831. */
  52832. this.getDrawingBufferSize = function ( target ) {
  52833. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52834. };
  52835. /**
  52836. * This method allows to define the drawing buffer size by specifying
  52837. * width, height and pixel ratio all at once. The size of the drawing
  52838. * buffer is computed with this formula:
  52839. * ```js
  52840. * size.x = width * pixelRatio;
  52841. * size.y = height * pixelRatio;
  52842. * ```
  52843. *
  52844. * @param {number} width - The width in logical pixels.
  52845. * @param {number} height - The height in logical pixels.
  52846. * @param {number} pixelRatio - The pixel ratio.
  52847. */
  52848. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52849. _width = width;
  52850. _height = height;
  52851. _pixelRatio = pixelRatio;
  52852. canvas.width = Math.floor( width * pixelRatio );
  52853. canvas.height = Math.floor( height * pixelRatio );
  52854. this.setViewport( 0, 0, width, height );
  52855. };
  52856. /**
  52857. * Sets the post-processing effects to be applied after rendering.
  52858. *
  52859. * @param {Array} effects - An array of post-processing effects.
  52860. */
  52861. this.setEffects = function ( effects ) {
  52862. if ( _outputBufferType === UnsignedByteType ) {
  52863. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  52864. return;
  52865. }
  52866. if ( effects ) {
  52867. for ( let i = 0; i < effects.length; i ++ ) {
  52868. if ( effects[ i ].isOutputPass === true ) {
  52869. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  52870. break;
  52871. }
  52872. }
  52873. }
  52874. output.setEffects( effects || [] );
  52875. };
  52876. /**
  52877. * Returns the current viewport definition.
  52878. *
  52879. * @param {Vector2} target - The method writes the result in this target object.
  52880. * @return {Vector2} The current viewport definition.
  52881. */
  52882. this.getCurrentViewport = function ( target ) {
  52883. return target.copy( _currentViewport );
  52884. };
  52885. /**
  52886. * Returns the viewport definition.
  52887. *
  52888. * @param {Vector4} target - The method writes the result in this target object.
  52889. * @return {Vector4} The viewport definition.
  52890. */
  52891. this.getViewport = function ( target ) {
  52892. return target.copy( _viewport );
  52893. };
  52894. /**
  52895. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52896. *
  52897. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52898. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52899. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52900. * @param {number} width - The width of the viewport in logical pixel unit.
  52901. * @param {number} height - The height of the viewport in logical pixel unit.
  52902. */
  52903. this.setViewport = function ( x, y, width, height ) {
  52904. if ( x.isVector4 ) {
  52905. _viewport.set( x.x, x.y, x.z, x.w );
  52906. } else {
  52907. _viewport.set( x, y, width, height );
  52908. }
  52909. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52910. };
  52911. /**
  52912. * Returns the scissor region.
  52913. *
  52914. * @param {Vector4} target - The method writes the result in this target object.
  52915. * @return {Vector4} The scissor region.
  52916. */
  52917. this.getScissor = function ( target ) {
  52918. return target.copy( _scissor );
  52919. };
  52920. /**
  52921. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52922. *
  52923. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52924. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52925. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52926. * @param {number} width - The width of the scissor region in logical pixel unit.
  52927. * @param {number} height - The height of the scissor region in logical pixel unit.
  52928. */
  52929. this.setScissor = function ( x, y, width, height ) {
  52930. if ( x.isVector4 ) {
  52931. _scissor.set( x.x, x.y, x.z, x.w );
  52932. } else {
  52933. _scissor.set( x, y, width, height );
  52934. }
  52935. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52936. };
  52937. /**
  52938. * Returns `true` if the scissor test is enabled.
  52939. *
  52940. * @return {boolean} Whether the scissor test is enabled or not.
  52941. */
  52942. this.getScissorTest = function () {
  52943. return _scissorTest;
  52944. };
  52945. /**
  52946. * Enable or disable the scissor test. When this is enabled, only the pixels
  52947. * within the defined scissor area will be affected by further renderer
  52948. * actions.
  52949. *
  52950. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52951. */
  52952. this.setScissorTest = function ( boolean ) {
  52953. state.setScissorTest( _scissorTest = boolean );
  52954. };
  52955. /**
  52956. * Sets a custom opaque sort function for the render lists. Pass `null`
  52957. * to use the default `painterSortStable` function.
  52958. *
  52959. * @param {?Function} method - The opaque sort function.
  52960. */
  52961. this.setOpaqueSort = function ( method ) {
  52962. _opaqueSort = method;
  52963. };
  52964. /**
  52965. * Sets a custom transparent sort function for the render lists. Pass `null`
  52966. * to use the default `reversePainterSortStable` function.
  52967. *
  52968. * @param {?Function} method - The opaque sort function.
  52969. */
  52970. this.setTransparentSort = function ( method ) {
  52971. _transparentSort = method;
  52972. };
  52973. // Clearing
  52974. /**
  52975. * Returns the clear color.
  52976. *
  52977. * @param {Color} target - The method writes the result in this target object.
  52978. * @return {Color} The clear color.
  52979. */
  52980. this.getClearColor = function ( target ) {
  52981. return target.copy( background.getClearColor() );
  52982. };
  52983. /**
  52984. * Sets the clear color and alpha.
  52985. *
  52986. * @param {Color} color - The clear color.
  52987. * @param {number} [alpha=1] - The clear alpha.
  52988. */
  52989. this.setClearColor = function () {
  52990. background.setClearColor( ...arguments );
  52991. };
  52992. /**
  52993. * Returns the clear alpha. Ranges within `[0,1]`.
  52994. *
  52995. * @return {number} The clear alpha.
  52996. */
  52997. this.getClearAlpha = function () {
  52998. return background.getClearAlpha();
  52999. };
  53000. /**
  53001. * Sets the clear alpha.
  53002. *
  53003. * @param {number} alpha - The clear alpha.
  53004. */
  53005. this.setClearAlpha = function () {
  53006. background.setClearAlpha( ...arguments );
  53007. };
  53008. /**
  53009. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  53010. * This method initializes the buffers to the current clear color values.
  53011. *
  53012. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  53013. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  53014. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  53015. */
  53016. this.clear = function ( color = true, depth = true, stencil = true ) {
  53017. let bits = 0;
  53018. if ( color ) {
  53019. // check if we're trying to clear an integer target
  53020. let isIntegerFormat = false;
  53021. if ( _currentRenderTarget !== null ) {
  53022. const targetFormat = _currentRenderTarget.texture.format;
  53023. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  53024. }
  53025. // use the appropriate clear functions to clear the target if it's a signed
  53026. // or unsigned integer target
  53027. if ( isIntegerFormat ) {
  53028. const targetType = _currentRenderTarget.texture.type;
  53029. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  53030. const clearColor = background.getClearColor();
  53031. const a = background.getClearAlpha();
  53032. const r = clearColor.r;
  53033. const g = clearColor.g;
  53034. const b = clearColor.b;
  53035. if ( isUnsignedType ) {
  53036. uintClearColor[ 0 ] = r;
  53037. uintClearColor[ 1 ] = g;
  53038. uintClearColor[ 2 ] = b;
  53039. uintClearColor[ 3 ] = a;
  53040. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  53041. } else {
  53042. intClearColor[ 0 ] = r;
  53043. intClearColor[ 1 ] = g;
  53044. intClearColor[ 2 ] = b;
  53045. intClearColor[ 3 ] = a;
  53046. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  53047. }
  53048. } else {
  53049. bits |= _gl.COLOR_BUFFER_BIT;
  53050. }
  53051. }
  53052. if ( depth ) {
  53053. bits |= _gl.DEPTH_BUFFER_BIT;
  53054. }
  53055. if ( stencil ) {
  53056. bits |= _gl.STENCIL_BUFFER_BIT;
  53057. this.state.buffers.stencil.setMask( 0xffffffff );
  53058. }
  53059. _gl.clear( bits );
  53060. };
  53061. /**
  53062. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  53063. */
  53064. this.clearColor = function () {
  53065. this.clear( true, false, false );
  53066. };
  53067. /**
  53068. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  53069. */
  53070. this.clearDepth = function () {
  53071. this.clear( false, true, false );
  53072. };
  53073. /**
  53074. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  53075. */
  53076. this.clearStencil = function () {
  53077. this.clear( false, false, true );
  53078. };
  53079. /**
  53080. * Frees the GPU-related resources allocated by this instance. Call this
  53081. * method whenever this instance is no longer used in your app.
  53082. */
  53083. this.dispose = function () {
  53084. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  53085. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  53086. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53087. background.dispose();
  53088. renderLists.dispose();
  53089. renderStates.dispose();
  53090. properties.dispose();
  53091. cubemaps.dispose();
  53092. cubeuvmaps.dispose();
  53093. objects.dispose();
  53094. bindingStates.dispose();
  53095. uniformsGroups.dispose();
  53096. programCache.dispose();
  53097. xr.dispose();
  53098. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  53099. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  53100. animation.stop();
  53101. };
  53102. // Events
  53103. function onContextLost( event ) {
  53104. event.preventDefault();
  53105. log( 'WebGLRenderer: Context Lost.' );
  53106. _isContextLost = true;
  53107. }
  53108. function onContextRestore( /* event */ ) {
  53109. log( 'WebGLRenderer: Context Restored.' );
  53110. _isContextLost = false;
  53111. const infoAutoReset = info.autoReset;
  53112. const shadowMapEnabled = shadowMap.enabled;
  53113. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  53114. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  53115. const shadowMapType = shadowMap.type;
  53116. initGLContext();
  53117. info.autoReset = infoAutoReset;
  53118. shadowMap.enabled = shadowMapEnabled;
  53119. shadowMap.autoUpdate = shadowMapAutoUpdate;
  53120. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  53121. shadowMap.type = shadowMapType;
  53122. }
  53123. function onContextCreationError( event ) {
  53124. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  53125. }
  53126. function onMaterialDispose( event ) {
  53127. const material = event.target;
  53128. material.removeEventListener( 'dispose', onMaterialDispose );
  53129. deallocateMaterial( material );
  53130. }
  53131. // Buffer deallocation
  53132. function deallocateMaterial( material ) {
  53133. releaseMaterialProgramReferences( material );
  53134. properties.remove( material );
  53135. }
  53136. function releaseMaterialProgramReferences( material ) {
  53137. const programs = properties.get( material ).programs;
  53138. if ( programs !== undefined ) {
  53139. programs.forEach( function ( program ) {
  53140. programCache.releaseProgram( program );
  53141. } );
  53142. if ( material.isShaderMaterial ) {
  53143. programCache.releaseShaderCache( material );
  53144. }
  53145. }
  53146. }
  53147. // Buffer rendering
  53148. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  53149. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  53150. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53151. const program = setProgram( camera, scene, geometry, material, object );
  53152. state.setMaterial( material, frontFaceCW );
  53153. //
  53154. let index = geometry.index;
  53155. let rangeFactor = 1;
  53156. if ( material.wireframe === true ) {
  53157. index = geometries.getWireframeAttribute( geometry );
  53158. if ( index === undefined ) return;
  53159. rangeFactor = 2;
  53160. }
  53161. //
  53162. const drawRange = geometry.drawRange;
  53163. const position = geometry.attributes.position;
  53164. let drawStart = drawRange.start * rangeFactor;
  53165. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  53166. if ( group !== null ) {
  53167. drawStart = Math.max( drawStart, group.start * rangeFactor );
  53168. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  53169. }
  53170. if ( index !== null ) {
  53171. drawStart = Math.max( drawStart, 0 );
  53172. drawEnd = Math.min( drawEnd, index.count );
  53173. } else if ( position !== undefined && position !== null ) {
  53174. drawStart = Math.max( drawStart, 0 );
  53175. drawEnd = Math.min( drawEnd, position.count );
  53176. }
  53177. const drawCount = drawEnd - drawStart;
  53178. if ( drawCount < 0 || drawCount === Infinity ) return;
  53179. //
  53180. bindingStates.setup( object, material, program, geometry, index );
  53181. let attribute;
  53182. let renderer = bufferRenderer;
  53183. if ( index !== null ) {
  53184. attribute = attributes.get( index );
  53185. renderer = indexedBufferRenderer;
  53186. renderer.setIndex( attribute );
  53187. }
  53188. //
  53189. if ( object.isMesh ) {
  53190. if ( material.wireframe === true ) {
  53191. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  53192. renderer.setMode( _gl.LINES );
  53193. } else {
  53194. renderer.setMode( _gl.TRIANGLES );
  53195. }
  53196. } else if ( object.isLine ) {
  53197. let lineWidth = material.linewidth;
  53198. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  53199. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  53200. if ( object.isLineSegments ) {
  53201. renderer.setMode( _gl.LINES );
  53202. } else if ( object.isLineLoop ) {
  53203. renderer.setMode( _gl.LINE_LOOP );
  53204. } else {
  53205. renderer.setMode( _gl.LINE_STRIP );
  53206. }
  53207. } else if ( object.isPoints ) {
  53208. renderer.setMode( _gl.POINTS );
  53209. } else if ( object.isSprite ) {
  53210. renderer.setMode( _gl.TRIANGLES );
  53211. }
  53212. if ( object.isBatchedMesh ) {
  53213. if ( object._multiDrawInstances !== null ) {
  53214. // @deprecated, r174
  53215. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53216. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  53217. } else {
  53218. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  53219. const starts = object._multiDrawStarts;
  53220. const counts = object._multiDrawCounts;
  53221. const drawCount = object._multiDrawCount;
  53222. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  53223. const uniforms = properties.get( material ).currentProgram.getUniforms();
  53224. for ( let i = 0; i < drawCount; i ++ ) {
  53225. uniforms.setValue( _gl, '_gl_DrawID', i );
  53226. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  53227. }
  53228. } else {
  53229. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  53230. }
  53231. }
  53232. } else if ( object.isInstancedMesh ) {
  53233. renderer.renderInstances( drawStart, drawCount, object.count );
  53234. } else if ( geometry.isInstancedBufferGeometry ) {
  53235. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  53236. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  53237. renderer.renderInstances( drawStart, drawCount, instanceCount );
  53238. } else {
  53239. renderer.render( drawStart, drawCount );
  53240. }
  53241. };
  53242. // Compile
  53243. function prepareMaterial( material, scene, object ) {
  53244. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53245. material.side = BackSide;
  53246. material.needsUpdate = true;
  53247. getProgram( material, scene, object );
  53248. material.side = FrontSide;
  53249. material.needsUpdate = true;
  53250. getProgram( material, scene, object );
  53251. material.side = DoubleSide;
  53252. } else {
  53253. getProgram( material, scene, object );
  53254. }
  53255. }
  53256. /**
  53257. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53258. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53259. * optional parameter for applying the target scene.
  53260. *
  53261. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53262. *
  53263. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53264. * @param {Camera} camera - The camera.
  53265. * @param {?Scene} [targetScene=null] - The target scene.
  53266. * @return {Set<Material>} The precompiled materials.
  53267. */
  53268. this.compile = function ( scene, camera, targetScene = null ) {
  53269. if ( targetScene === null ) targetScene = scene;
  53270. currentRenderState = renderStates.get( targetScene );
  53271. currentRenderState.init( camera );
  53272. renderStateStack.push( currentRenderState );
  53273. // gather lights from both the target scene and the new object that will be added to the scene.
  53274. targetScene.traverseVisible( function ( object ) {
  53275. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53276. currentRenderState.pushLight( object );
  53277. if ( object.castShadow ) {
  53278. currentRenderState.pushShadow( object );
  53279. }
  53280. }
  53281. } );
  53282. if ( scene !== targetScene ) {
  53283. scene.traverseVisible( function ( object ) {
  53284. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53285. currentRenderState.pushLight( object );
  53286. if ( object.castShadow ) {
  53287. currentRenderState.pushShadow( object );
  53288. }
  53289. }
  53290. } );
  53291. }
  53292. currentRenderState.setupLights();
  53293. // Only initialize materials in the new scene, not the targetScene.
  53294. const materials = new Set();
  53295. scene.traverse( function ( object ) {
  53296. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53297. return;
  53298. }
  53299. const material = object.material;
  53300. if ( material ) {
  53301. if ( Array.isArray( material ) ) {
  53302. for ( let i = 0; i < material.length; i ++ ) {
  53303. const material2 = material[ i ];
  53304. prepareMaterial( material2, targetScene, object );
  53305. materials.add( material2 );
  53306. }
  53307. } else {
  53308. prepareMaterial( material, targetScene, object );
  53309. materials.add( material );
  53310. }
  53311. }
  53312. } );
  53313. currentRenderState = renderStateStack.pop();
  53314. return materials;
  53315. };
  53316. // compileAsync
  53317. /**
  53318. * Asynchronous version of {@link WebGLRenderer#compile}.
  53319. *
  53320. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53321. * it is recommended to use this version of `compile()` whenever possible.
  53322. *
  53323. * @async
  53324. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53325. * @param {Camera} camera - The camera.
  53326. * @param {?Scene} [targetScene=null] - The target scene.
  53327. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53328. */
  53329. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53330. const materials = this.compile( scene, camera, targetScene );
  53331. // Wait for all the materials in the new object to indicate that they're
  53332. // ready to be used before resolving the promise.
  53333. return new Promise( ( resolve ) => {
  53334. function checkMaterialsReady() {
  53335. materials.forEach( function ( material ) {
  53336. const materialProperties = properties.get( material );
  53337. const program = materialProperties.currentProgram;
  53338. if ( program.isReady() ) {
  53339. // remove any programs that report they're ready to use from the list
  53340. materials.delete( material );
  53341. }
  53342. } );
  53343. // once the list of compiling materials is empty, call the callback
  53344. if ( materials.size === 0 ) {
  53345. resolve( scene );
  53346. return;
  53347. }
  53348. // if some materials are still not ready, wait a bit and check again
  53349. setTimeout( checkMaterialsReady, 10 );
  53350. }
  53351. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53352. // If we can check the compilation status of the materials without
  53353. // blocking then do so right away.
  53354. checkMaterialsReady();
  53355. } else {
  53356. // Otherwise start by waiting a bit to give the materials we just
  53357. // initialized a chance to finish.
  53358. setTimeout( checkMaterialsReady, 10 );
  53359. }
  53360. } );
  53361. };
  53362. // Animation Loop
  53363. let onAnimationFrameCallback = null;
  53364. function onAnimationFrame( time ) {
  53365. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53366. }
  53367. function onXRSessionStart() {
  53368. animation.stop();
  53369. }
  53370. function onXRSessionEnd() {
  53371. animation.start();
  53372. }
  53373. const animation = new WebGLAnimation();
  53374. animation.setAnimationLoop( onAnimationFrame );
  53375. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53376. /**
  53377. * Applications are advised to always define the animation loop
  53378. * with this method and not manually with `requestAnimationFrame()`
  53379. * for best compatibility.
  53380. *
  53381. * @param {?onAnimationCallback} callback - The application's animation loop.
  53382. */
  53383. this.setAnimationLoop = function ( callback ) {
  53384. onAnimationFrameCallback = callback;
  53385. xr.setAnimationLoop( callback );
  53386. ( callback === null ) ? animation.stop() : animation.start();
  53387. };
  53388. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53389. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53390. // Rendering
  53391. /**
  53392. * Renders the given scene (or other type of 3D object) using the given camera.
  53393. *
  53394. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53395. * or to the canvas as usual.
  53396. *
  53397. * By default render buffers are cleared before rendering but you can prevent
  53398. * this by setting the property `autoClear` to `false`. If you want to prevent
  53399. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53400. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53401. *
  53402. * @param {Object3D} scene - The scene to render.
  53403. * @param {Camera} camera - The camera.
  53404. */
  53405. this.render = function ( scene, camera ) {
  53406. if ( camera !== undefined && camera.isCamera !== true ) {
  53407. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53408. return;
  53409. }
  53410. if ( _isContextLost === true ) return;
  53411. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  53412. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  53413. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  53414. // update scene graph
  53415. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53416. // update camera matrices and frustum
  53417. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53418. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  53419. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53420. camera = xr.getCamera(); // use XR camera for rendering
  53421. }
  53422. //
  53423. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53424. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53425. currentRenderState.init( camera );
  53426. renderStateStack.push( currentRenderState );
  53427. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53428. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53429. _localClippingEnabled = this.localClippingEnabled;
  53430. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53431. currentRenderList = renderLists.get( scene, renderListStack.length );
  53432. currentRenderList.init();
  53433. renderListStack.push( currentRenderList );
  53434. if ( xr.enabled === true && xr.isPresenting === true ) {
  53435. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53436. if ( depthSensingMesh !== null ) {
  53437. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53438. }
  53439. }
  53440. projectObject( scene, camera, 0, _this.sortObjects );
  53441. currentRenderList.finish();
  53442. if ( _this.sortObjects === true ) {
  53443. currentRenderList.sort( _opaqueSort, _transparentSort );
  53444. }
  53445. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53446. if ( _renderBackground ) {
  53447. background.addToRenderList( currentRenderList, scene );
  53448. }
  53449. //
  53450. this.info.render.frame ++;
  53451. if ( _clippingEnabled === true ) clipping.beginShadows();
  53452. const shadowsArray = currentRenderState.state.shadowsArray;
  53453. shadowMap.render( shadowsArray, scene, camera );
  53454. if ( _clippingEnabled === true ) clipping.endShadows();
  53455. //
  53456. if ( this.info.autoReset === true ) this.info.reset();
  53457. // render scene (skip if first effect is a render pass - it will render the scene itself)
  53458. const skipSceneRender = useOutput && output.hasRenderPass();
  53459. if ( skipSceneRender === false ) {
  53460. const opaqueObjects = currentRenderList.opaque;
  53461. const transmissiveObjects = currentRenderList.transmissive;
  53462. currentRenderState.setupLights();
  53463. if ( camera.isArrayCamera ) {
  53464. const cameras = camera.cameras;
  53465. if ( transmissiveObjects.length > 0 ) {
  53466. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53467. const camera2 = cameras[ i ];
  53468. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53469. }
  53470. }
  53471. if ( _renderBackground ) background.render( scene );
  53472. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53473. const camera2 = cameras[ i ];
  53474. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53475. }
  53476. } else {
  53477. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53478. if ( _renderBackground ) background.render( scene );
  53479. renderScene( currentRenderList, scene, camera );
  53480. }
  53481. }
  53482. //
  53483. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53484. // resolve multisample renderbuffers to a single-sample texture if necessary
  53485. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53486. // Generate mipmap if we're using any kind of mipmap filtering
  53487. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53488. }
  53489. // copy from internal render target to canvas using fullscreen quad
  53490. if ( useOutput ) {
  53491. output.end( _this );
  53492. }
  53493. //
  53494. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53495. // _gl.finish();
  53496. bindingStates.resetDefaultState();
  53497. _currentMaterialId = -1;
  53498. _currentCamera = null;
  53499. renderStateStack.pop();
  53500. if ( renderStateStack.length > 0 ) {
  53501. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53502. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53503. } else {
  53504. currentRenderState = null;
  53505. }
  53506. renderListStack.pop();
  53507. if ( renderListStack.length > 0 ) {
  53508. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53509. } else {
  53510. currentRenderList = null;
  53511. }
  53512. };
  53513. function projectObject( object, camera, groupOrder, sortObjects ) {
  53514. if ( object.visible === false ) return;
  53515. const visible = object.layers.test( camera.layers );
  53516. if ( visible ) {
  53517. if ( object.isGroup ) {
  53518. groupOrder = object.renderOrder;
  53519. } else if ( object.isLOD ) {
  53520. if ( object.autoUpdate === true ) object.update( camera );
  53521. } else if ( object.isLight ) {
  53522. currentRenderState.pushLight( object );
  53523. if ( object.castShadow ) {
  53524. currentRenderState.pushShadow( object );
  53525. }
  53526. } else if ( object.isSprite ) {
  53527. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53528. if ( sortObjects ) {
  53529. _vector4.setFromMatrixPosition( object.matrixWorld )
  53530. .applyMatrix4( _projScreenMatrix );
  53531. }
  53532. const geometry = objects.update( object );
  53533. const material = object.material;
  53534. if ( material.visible ) {
  53535. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53536. }
  53537. }
  53538. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53539. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53540. const geometry = objects.update( object );
  53541. const material = object.material;
  53542. if ( sortObjects ) {
  53543. if ( object.boundingSphere !== undefined ) {
  53544. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53545. _vector4.copy( object.boundingSphere.center );
  53546. } else {
  53547. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53548. _vector4.copy( geometry.boundingSphere.center );
  53549. }
  53550. _vector4
  53551. .applyMatrix4( object.matrixWorld )
  53552. .applyMatrix4( _projScreenMatrix );
  53553. }
  53554. if ( Array.isArray( material ) ) {
  53555. const groups = geometry.groups;
  53556. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53557. const group = groups[ i ];
  53558. const groupMaterial = material[ group.materialIndex ];
  53559. if ( groupMaterial && groupMaterial.visible ) {
  53560. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  53561. }
  53562. }
  53563. } else if ( material.visible ) {
  53564. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53565. }
  53566. }
  53567. }
  53568. }
  53569. const children = object.children;
  53570. for ( let i = 0, l = children.length; i < l; i ++ ) {
  53571. projectObject( children[ i ], camera, groupOrder, sortObjects );
  53572. }
  53573. }
  53574. function renderScene( currentRenderList, scene, camera, viewport ) {
  53575. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  53576. currentRenderState.setupLightsView( camera );
  53577. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53578. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  53579. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  53580. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  53581. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  53582. // Ensure depth buffer writing is enabled so it can be cleared on next render
  53583. state.buffers.depth.setTest( true );
  53584. state.buffers.depth.setMask( true );
  53585. state.buffers.color.setMask( true );
  53586. state.setPolygonOffset( false );
  53587. }
  53588. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  53589. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53590. if ( overrideMaterial !== null ) {
  53591. return;
  53592. }
  53593. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  53594. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  53595. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  53596. generateMipmaps: true,
  53597. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  53598. minFilter: LinearMipmapLinearFilter,
  53599. samples: capabilities.samples,
  53600. stencilBuffer: stencil,
  53601. resolveDepthBuffer: false,
  53602. resolveStencilBuffer: false,
  53603. colorSpace: ColorManagement.workingColorSpace,
  53604. } );
  53605. // debug
  53606. /*
  53607. const geometry = new PlaneGeometry();
  53608. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  53609. const mesh = new Mesh( geometry, material );
  53610. scene.add( mesh );
  53611. */
  53612. }
  53613. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  53614. const activeViewport = camera.viewport || _currentViewport;
  53615. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  53616. //
  53617. const currentRenderTarget = _this.getRenderTarget();
  53618. const currentActiveCubeFace = _this.getActiveCubeFace();
  53619. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  53620. _this.setRenderTarget( transmissionRenderTarget );
  53621. _this.getClearColor( _currentClearColor );
  53622. _currentClearAlpha = _this.getClearAlpha();
  53623. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  53624. _this.clear();
  53625. if ( _renderBackground ) background.render( scene );
  53626. // Turn off the features which can affect the frag color for opaque objects pass.
  53627. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  53628. const currentToneMapping = _this.toneMapping;
  53629. _this.toneMapping = NoToneMapping;
  53630. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  53631. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  53632. const currentCameraViewport = camera.viewport;
  53633. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  53634. currentRenderState.setupLightsView( camera );
  53635. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53636. renderObjects( opaqueObjects, scene, camera );
  53637. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53638. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53639. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  53640. let renderTargetNeedsUpdate = false;
  53641. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  53642. const renderItem = transmissiveObjects[ i ];
  53643. const { object, geometry, material, group } = renderItem;
  53644. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  53645. const currentSide = material.side;
  53646. material.side = BackSide;
  53647. material.needsUpdate = true;
  53648. renderObject( object, scene, camera, geometry, material, group );
  53649. material.side = currentSide;
  53650. material.needsUpdate = true;
  53651. renderTargetNeedsUpdate = true;
  53652. }
  53653. }
  53654. if ( renderTargetNeedsUpdate === true ) {
  53655. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53656. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53657. }
  53658. }
  53659. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  53660. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  53661. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  53662. _this.toneMapping = currentToneMapping;
  53663. }
  53664. function renderObjects( renderList, scene, camera ) {
  53665. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53666. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  53667. const renderItem = renderList[ i ];
  53668. const { object, geometry, group } = renderItem;
  53669. let material = renderItem.material;
  53670. if ( material.allowOverride === true && overrideMaterial !== null ) {
  53671. material = overrideMaterial;
  53672. }
  53673. if ( object.layers.test( camera.layers ) ) {
  53674. renderObject( object, scene, camera, geometry, material, group );
  53675. }
  53676. }
  53677. }
  53678. function renderObject( object, scene, camera, geometry, material, group ) {
  53679. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  53680. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  53681. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  53682. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  53683. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53684. material.side = BackSide;
  53685. material.needsUpdate = true;
  53686. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53687. material.side = FrontSide;
  53688. material.needsUpdate = true;
  53689. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53690. material.side = DoubleSide;
  53691. } else {
  53692. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53693. }
  53694. object.onAfterRender( _this, scene, camera, geometry, material, group );
  53695. }
  53696. function getProgram( material, scene, object ) {
  53697. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53698. const materialProperties = properties.get( material );
  53699. const lights = currentRenderState.state.lights;
  53700. const shadowsArray = currentRenderState.state.shadowsArray;
  53701. const lightsStateVersion = lights.state.version;
  53702. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  53703. const programCacheKey = programCache.getProgramCacheKey( parameters );
  53704. let programs = materialProperties.programs;
  53705. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  53706. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  53707. materialProperties.fog = scene.fog;
  53708. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  53709. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  53710. if ( programs === undefined ) {
  53711. // new material
  53712. material.addEventListener( 'dispose', onMaterialDispose );
  53713. programs = new Map();
  53714. materialProperties.programs = programs;
  53715. }
  53716. let program = programs.get( programCacheKey );
  53717. if ( program !== undefined ) {
  53718. // early out if program and light state is identical
  53719. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  53720. updateCommonMaterialProperties( material, parameters );
  53721. return program;
  53722. }
  53723. } else {
  53724. parameters.uniforms = programCache.getUniforms( material );
  53725. material.onBeforeCompile( parameters, _this );
  53726. program = programCache.acquireProgram( parameters, programCacheKey );
  53727. programs.set( programCacheKey, program );
  53728. materialProperties.uniforms = parameters.uniforms;
  53729. }
  53730. const uniforms = materialProperties.uniforms;
  53731. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  53732. uniforms.clippingPlanes = clipping.uniform;
  53733. }
  53734. updateCommonMaterialProperties( material, parameters );
  53735. // store the light setup it was created for
  53736. materialProperties.needsLights = materialNeedsLights( material );
  53737. materialProperties.lightsStateVersion = lightsStateVersion;
  53738. if ( materialProperties.needsLights ) {
  53739. // wire up the material to this renderer's lighting state
  53740. uniforms.ambientLightColor.value = lights.state.ambient;
  53741. uniforms.lightProbe.value = lights.state.probe;
  53742. uniforms.directionalLights.value = lights.state.directional;
  53743. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  53744. uniforms.spotLights.value = lights.state.spot;
  53745. uniforms.spotLightShadows.value = lights.state.spotShadow;
  53746. uniforms.rectAreaLights.value = lights.state.rectArea;
  53747. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  53748. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  53749. uniforms.pointLights.value = lights.state.point;
  53750. uniforms.pointLightShadows.value = lights.state.pointShadow;
  53751. uniforms.hemisphereLights.value = lights.state.hemi;
  53752. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  53753. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  53754. uniforms.spotLightMap.value = lights.state.spotLightMap;
  53755. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  53756. // TODO (abelnation): add area lights shadow info to uniforms
  53757. }
  53758. materialProperties.currentProgram = program;
  53759. materialProperties.uniformsList = null;
  53760. return program;
  53761. }
  53762. function getUniformList( materialProperties ) {
  53763. if ( materialProperties.uniformsList === null ) {
  53764. const progUniforms = materialProperties.currentProgram.getUniforms();
  53765. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  53766. }
  53767. return materialProperties.uniformsList;
  53768. }
  53769. function updateCommonMaterialProperties( material, parameters ) {
  53770. const materialProperties = properties.get( material );
  53771. materialProperties.outputColorSpace = parameters.outputColorSpace;
  53772. materialProperties.batching = parameters.batching;
  53773. materialProperties.batchingColor = parameters.batchingColor;
  53774. materialProperties.instancing = parameters.instancing;
  53775. materialProperties.instancingColor = parameters.instancingColor;
  53776. materialProperties.instancingMorph = parameters.instancingMorph;
  53777. materialProperties.skinning = parameters.skinning;
  53778. materialProperties.morphTargets = parameters.morphTargets;
  53779. materialProperties.morphNormals = parameters.morphNormals;
  53780. materialProperties.morphColors = parameters.morphColors;
  53781. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  53782. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  53783. materialProperties.numIntersection = parameters.numClipIntersection;
  53784. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53785. materialProperties.vertexTangents = parameters.vertexTangents;
  53786. materialProperties.toneMapping = parameters.toneMapping;
  53787. }
  53788. function setProgram( camera, scene, geometry, material, object ) {
  53789. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53790. textures.resetTextureUnits();
  53791. const fog = scene.fog;
  53792. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53793. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53794. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53795. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53796. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53797. const morphTargets = !! geometry.morphAttributes.position;
  53798. const morphNormals = !! geometry.morphAttributes.normal;
  53799. const morphColors = !! geometry.morphAttributes.color;
  53800. let toneMapping = NoToneMapping;
  53801. if ( material.toneMapped ) {
  53802. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  53803. toneMapping = _this.toneMapping;
  53804. }
  53805. }
  53806. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  53807. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  53808. const materialProperties = properties.get( material );
  53809. const lights = currentRenderState.state.lights;
  53810. if ( _clippingEnabled === true ) {
  53811. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  53812. const useCache =
  53813. camera === _currentCamera &&
  53814. material.id === _currentMaterialId;
  53815. // we might want to call this function with some ClippingGroup
  53816. // object instead of the material, once it becomes feasible
  53817. // (#8465, #8379)
  53818. clipping.setState( material, camera, useCache );
  53819. }
  53820. }
  53821. //
  53822. let needsProgramChange = false;
  53823. if ( material.version === materialProperties.__version ) {
  53824. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53825. needsProgramChange = true;
  53826. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53827. needsProgramChange = true;
  53828. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53829. needsProgramChange = true;
  53830. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53831. needsProgramChange = true;
  53832. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53833. needsProgramChange = true;
  53834. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53835. needsProgramChange = true;
  53836. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53837. needsProgramChange = true;
  53838. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53839. needsProgramChange = true;
  53840. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53841. needsProgramChange = true;
  53842. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53843. needsProgramChange = true;
  53844. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53845. needsProgramChange = true;
  53846. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53847. needsProgramChange = true;
  53848. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53849. needsProgramChange = true;
  53850. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53851. needsProgramChange = true;
  53852. } else if ( materialProperties.envMap !== envMap ) {
  53853. needsProgramChange = true;
  53854. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53855. needsProgramChange = true;
  53856. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53857. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53858. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53859. needsProgramChange = true;
  53860. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53861. needsProgramChange = true;
  53862. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53863. needsProgramChange = true;
  53864. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53865. needsProgramChange = true;
  53866. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53867. needsProgramChange = true;
  53868. } else if ( materialProperties.morphColors !== morphColors ) {
  53869. needsProgramChange = true;
  53870. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53871. needsProgramChange = true;
  53872. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53873. needsProgramChange = true;
  53874. }
  53875. } else {
  53876. needsProgramChange = true;
  53877. materialProperties.__version = material.version;
  53878. }
  53879. //
  53880. let program = materialProperties.currentProgram;
  53881. if ( needsProgramChange === true ) {
  53882. program = getProgram( material, scene, object );
  53883. }
  53884. let refreshProgram = false;
  53885. let refreshMaterial = false;
  53886. let refreshLights = false;
  53887. const p_uniforms = program.getUniforms(),
  53888. m_uniforms = materialProperties.uniforms;
  53889. if ( state.useProgram( program.program ) ) {
  53890. refreshProgram = true;
  53891. refreshMaterial = true;
  53892. refreshLights = true;
  53893. }
  53894. if ( material.id !== _currentMaterialId ) {
  53895. _currentMaterialId = material.id;
  53896. refreshMaterial = true;
  53897. }
  53898. if ( refreshProgram || _currentCamera !== camera ) {
  53899. // common camera uniforms
  53900. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53901. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53902. camera._reversedDepth = true;
  53903. camera.updateProjectionMatrix();
  53904. }
  53905. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53906. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53907. const uCamPos = p_uniforms.map.cameraPosition;
  53908. if ( uCamPos !== undefined ) {
  53909. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53910. }
  53911. if ( capabilities.logarithmicDepthBuffer ) {
  53912. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53913. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53914. }
  53915. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53916. if ( material.isMeshPhongMaterial ||
  53917. material.isMeshToonMaterial ||
  53918. material.isMeshLambertMaterial ||
  53919. material.isMeshBasicMaterial ||
  53920. material.isMeshStandardMaterial ||
  53921. material.isShaderMaterial ) {
  53922. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53923. }
  53924. if ( _currentCamera !== camera ) {
  53925. _currentCamera = camera;
  53926. // lighting uniforms depend on the camera so enforce an update
  53927. // now, in case this material supports lights - or later, when
  53928. // the next material that does gets activated:
  53929. refreshMaterial = true; // set to true on material change
  53930. refreshLights = true; // remains set until update done
  53931. }
  53932. }
  53933. // Pre-allocate texture units for shadow samplers before setting data textures
  53934. if ( materialProperties.needsLights ) {
  53935. // Set shadow map uniforms first to ensure they get the first texture units
  53936. if ( lights.state.directionalShadowMap.length > 0 ) {
  53937. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  53938. }
  53939. if ( lights.state.spotShadowMap.length > 0 ) {
  53940. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  53941. }
  53942. if ( lights.state.pointShadowMap.length > 0 ) {
  53943. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  53944. }
  53945. }
  53946. // skinning and morph target uniforms must be set even if material didn't change
  53947. // auto-setting of texture unit for bone and morph texture must go before other textures
  53948. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53949. if ( object.isSkinnedMesh ) {
  53950. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53951. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53952. const skeleton = object.skeleton;
  53953. if ( skeleton ) {
  53954. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53955. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53956. }
  53957. }
  53958. if ( object.isBatchedMesh ) {
  53959. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53960. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53961. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53962. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53963. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53964. if ( object._colorsTexture !== null ) {
  53965. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53966. }
  53967. }
  53968. const morphAttributes = geometry.morphAttributes;
  53969. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53970. morphtargets.update( object, geometry, program );
  53971. }
  53972. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53973. materialProperties.receiveShadow = object.receiveShadow;
  53974. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53975. }
  53976. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53977. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53978. }
  53979. // Set DFG LUT for physically-based materials
  53980. if ( m_uniforms.dfgLUT !== undefined ) {
  53981. m_uniforms.dfgLUT.value = getDFGLUT();
  53982. }
  53983. if ( refreshMaterial ) {
  53984. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53985. if ( materialProperties.needsLights ) {
  53986. // the current material requires lighting info
  53987. // note: all lighting uniforms are always set correctly
  53988. // they simply reference the renderer's state for their
  53989. // values
  53990. //
  53991. // use the current material's .needsUpdate flags to set
  53992. // the GL state when required
  53993. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53994. }
  53995. // refresh uniforms common to several materials
  53996. if ( fog && material.fog === true ) {
  53997. materials.refreshFogUniforms( m_uniforms, fog );
  53998. }
  53999. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  54000. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54001. }
  54002. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  54003. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54004. material.uniformsNeedUpdate = false;
  54005. }
  54006. if ( material.isSpriteMaterial ) {
  54007. p_uniforms.setValue( _gl, 'center', object.center );
  54008. }
  54009. // common matrices
  54010. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  54011. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  54012. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  54013. // UBOs
  54014. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  54015. const groups = material.uniformsGroups;
  54016. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  54017. const group = groups[ i ];
  54018. uniformsGroups.update( group, program );
  54019. uniformsGroups.bind( group, program );
  54020. }
  54021. }
  54022. return program;
  54023. }
  54024. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  54025. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  54026. uniforms.ambientLightColor.needsUpdate = value;
  54027. uniforms.lightProbe.needsUpdate = value;
  54028. uniforms.directionalLights.needsUpdate = value;
  54029. uniforms.directionalLightShadows.needsUpdate = value;
  54030. uniforms.pointLights.needsUpdate = value;
  54031. uniforms.pointLightShadows.needsUpdate = value;
  54032. uniforms.spotLights.needsUpdate = value;
  54033. uniforms.spotLightShadows.needsUpdate = value;
  54034. uniforms.rectAreaLights.needsUpdate = value;
  54035. uniforms.hemisphereLights.needsUpdate = value;
  54036. }
  54037. function materialNeedsLights( material ) {
  54038. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  54039. material.isMeshStandardMaterial || material.isShadowMaterial ||
  54040. ( material.isShaderMaterial && material.lights === true );
  54041. }
  54042. /**
  54043. * Returns the active cube face.
  54044. *
  54045. * @return {number} The active cube face.
  54046. */
  54047. this.getActiveCubeFace = function () {
  54048. return _currentActiveCubeFace;
  54049. };
  54050. /**
  54051. * Returns the active mipmap level.
  54052. *
  54053. * @return {number} The active mipmap level.
  54054. */
  54055. this.getActiveMipmapLevel = function () {
  54056. return _currentActiveMipmapLevel;
  54057. };
  54058. /**
  54059. * Returns the active render target.
  54060. *
  54061. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  54062. * is currently set.
  54063. */
  54064. this.getRenderTarget = function () {
  54065. return _currentRenderTarget;
  54066. };
  54067. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  54068. const renderTargetProperties = properties.get( renderTarget );
  54069. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  54070. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  54071. // The multisample_render_to_texture extension doesn't work properly if there
  54072. // are midframe flushes and an external depth buffer. Disable use of the extension.
  54073. renderTargetProperties.__useRenderToTexture = false;
  54074. }
  54075. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  54076. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  54077. renderTargetProperties.__hasExternalTextures = true;
  54078. };
  54079. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  54080. const renderTargetProperties = properties.get( renderTarget );
  54081. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  54082. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  54083. };
  54084. const _scratchFrameBuffer = _gl.createFramebuffer();
  54085. /**
  54086. * Sets the active rendertarget.
  54087. *
  54088. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  54089. * the canvas is set as the active render target instead.
  54090. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  54091. * Indicates the z layer to render in to when using 3D or array render targets.
  54092. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  54093. */
  54094. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  54095. _currentRenderTarget = renderTarget;
  54096. _currentActiveCubeFace = activeCubeFace;
  54097. _currentActiveMipmapLevel = activeMipmapLevel;
  54098. let framebuffer = null;
  54099. let isCube = false;
  54100. let isRenderTarget3D = false;
  54101. if ( renderTarget ) {
  54102. const renderTargetProperties = properties.get( renderTarget );
  54103. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  54104. // Externally-managed framebuffer (e.g. XR)
  54105. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  54106. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  54107. _currentViewport.copy( renderTarget.viewport );
  54108. _currentScissor.copy( renderTarget.scissor );
  54109. _currentScissorTest = renderTarget.scissorTest;
  54110. state.viewport( _currentViewport );
  54111. state.scissor( _currentScissor );
  54112. state.setScissorTest( _currentScissorTest );
  54113. _currentMaterialId = -1;
  54114. return;
  54115. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  54116. textures.setupRenderTarget( renderTarget );
  54117. } else if ( renderTargetProperties.__hasExternalTextures ) {
  54118. // Color and depth texture must be rebound in order for the swapchain to update.
  54119. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  54120. } else if ( renderTarget.depthBuffer ) {
  54121. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  54122. const depthTexture = renderTarget.depthTexture;
  54123. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  54124. // check if the depth texture is compatible
  54125. if (
  54126. depthTexture !== null &&
  54127. properties.has( depthTexture ) &&
  54128. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  54129. ) {
  54130. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  54131. }
  54132. // Swap the depth buffer to the currently attached one
  54133. textures.setupDepthRenderbuffer( renderTarget );
  54134. }
  54135. }
  54136. const texture = renderTarget.texture;
  54137. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54138. isRenderTarget3D = true;
  54139. }
  54140. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54141. if ( renderTarget.isWebGLCubeRenderTarget ) {
  54142. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  54143. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  54144. } else {
  54145. framebuffer = __webglFramebuffer[ activeCubeFace ];
  54146. }
  54147. isCube = true;
  54148. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  54149. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  54150. } else {
  54151. if ( Array.isArray( __webglFramebuffer ) ) {
  54152. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  54153. } else {
  54154. framebuffer = __webglFramebuffer;
  54155. }
  54156. }
  54157. _currentViewport.copy( renderTarget.viewport );
  54158. _currentScissor.copy( renderTarget.scissor );
  54159. _currentScissorTest = renderTarget.scissorTest;
  54160. } else {
  54161. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  54162. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  54163. _currentScissorTest = _scissorTest;
  54164. }
  54165. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  54166. // being bound that are different sizes.
  54167. if ( activeMipmapLevel !== 0 ) {
  54168. framebuffer = _scratchFrameBuffer;
  54169. }
  54170. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54171. if ( framebufferBound ) {
  54172. state.drawBuffers( renderTarget, framebuffer );
  54173. }
  54174. state.viewport( _currentViewport );
  54175. state.scissor( _currentScissor );
  54176. state.setScissorTest( _currentScissorTest );
  54177. if ( isCube ) {
  54178. const textureProperties = properties.get( renderTarget.texture );
  54179. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  54180. } else if ( isRenderTarget3D ) {
  54181. const layer = activeCubeFace;
  54182. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  54183. const textureProperties = properties.get( renderTarget.textures[ i ] );
  54184. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  54185. }
  54186. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  54187. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  54188. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  54189. const textureProperties = properties.get( renderTarget.texture );
  54190. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  54191. }
  54192. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  54193. };
  54194. /**
  54195. * Reads the pixel data from the given render target into the given buffer.
  54196. *
  54197. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54198. * @param {number} x - The `x` coordinate of the copy region's origin.
  54199. * @param {number} y - The `y` coordinate of the copy region's origin.
  54200. * @param {number} width - The width of the copy region.
  54201. * @param {number} height - The height of the copy region.
  54202. * @param {TypedArray} buffer - The result buffer.
  54203. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54204. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54205. */
  54206. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54207. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54208. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54209. return;
  54210. }
  54211. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54212. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54213. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54214. }
  54215. if ( framebuffer ) {
  54216. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54217. try {
  54218. const texture = renderTarget.textures[ textureIndex ];
  54219. const textureFormat = texture.format;
  54220. const textureType = texture.type;
  54221. // when using MRT, select the correct color buffer for the subsequent read command
  54222. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54223. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54224. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  54225. return;
  54226. }
  54227. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54228. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54229. return;
  54230. }
  54231. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54232. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54233. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  54234. }
  54235. } finally {
  54236. // restore framebuffer of current render target if necessary
  54237. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54238. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54239. }
  54240. }
  54241. };
  54242. /**
  54243. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  54244. *
  54245. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  54246. *
  54247. * @async
  54248. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54249. * @param {number} x - The `x` coordinate of the copy region's origin.
  54250. * @param {number} y - The `y` coordinate of the copy region's origin.
  54251. * @param {number} width - The width of the copy region.
  54252. * @param {number} height - The height of the copy region.
  54253. * @param {TypedArray} buffer - The result buffer.
  54254. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54255. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54256. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54257. */
  54258. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54259. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54260. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54261. }
  54262. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54263. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54264. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54265. }
  54266. if ( framebuffer ) {
  54267. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54268. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54269. // set the active frame buffer to the one we want to read
  54270. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54271. const texture = renderTarget.textures[ textureIndex ];
  54272. const textureFormat = texture.format;
  54273. const textureType = texture.type;
  54274. // when using MRT, select the correct color buffer for the subsequent read command
  54275. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54276. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54277. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54278. }
  54279. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54280. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54281. }
  54282. const glBuffer = _gl.createBuffer();
  54283. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54284. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54285. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54286. // reset the frame buffer to the currently set buffer before waiting
  54287. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54288. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54289. // check if the commands have finished every 8 ms
  54290. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54291. _gl.flush();
  54292. await probeAsync( _gl, sync, 4 );
  54293. // read the data and delete the buffer
  54294. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54295. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54296. _gl.deleteBuffer( glBuffer );
  54297. _gl.deleteSync( sync );
  54298. return buffer;
  54299. } else {
  54300. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54301. }
  54302. }
  54303. };
  54304. /**
  54305. * Copies pixels from the current bound framebuffer into the given texture.
  54306. *
  54307. * @param {FramebufferTexture} texture - The texture.
  54308. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54309. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54310. */
  54311. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54312. const levelScale = Math.pow( 2, - level );
  54313. const width = Math.floor( texture.image.width * levelScale );
  54314. const height = Math.floor( texture.image.height * levelScale );
  54315. const x = position !== null ? position.x : 0;
  54316. const y = position !== null ? position.y : 0;
  54317. textures.setTexture2D( texture, 0 );
  54318. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54319. state.unbindTexture();
  54320. };
  54321. const _srcFramebuffer = _gl.createFramebuffer();
  54322. const _dstFramebuffer = _gl.createFramebuffer();
  54323. /**
  54324. * Copies data of the given source texture into a destination texture.
  54325. *
  54326. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54327. * {@link WebGLRenderer#initRenderTarget}.
  54328. *
  54329. * @param {Texture} srcTexture - The source texture.
  54330. * @param {Texture} dstTexture - The destination texture.
  54331. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54332. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54333. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54334. * @param {?number} [dstLevel=0] - The destination mipmap level.
  54335. */
  54336. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54337. // gather the necessary dimensions to copy
  54338. let width, height, depth, minX, minY, minZ;
  54339. let dstX, dstY, dstZ;
  54340. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54341. if ( srcRegion !== null ) {
  54342. width = srcRegion.max.x - srcRegion.min.x;
  54343. height = srcRegion.max.y - srcRegion.min.y;
  54344. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54345. minX = srcRegion.min.x;
  54346. minY = srcRegion.min.y;
  54347. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54348. } else {
  54349. const levelScale = Math.pow( 2, - srcLevel );
  54350. width = Math.floor( image.width * levelScale );
  54351. height = Math.floor( image.height * levelScale );
  54352. if ( srcTexture.isDataArrayTexture ) {
  54353. depth = image.depth;
  54354. } else if ( srcTexture.isData3DTexture ) {
  54355. depth = Math.floor( image.depth * levelScale );
  54356. } else {
  54357. depth = 1;
  54358. }
  54359. minX = 0;
  54360. minY = 0;
  54361. minZ = 0;
  54362. }
  54363. if ( dstPosition !== null ) {
  54364. dstX = dstPosition.x;
  54365. dstY = dstPosition.y;
  54366. dstZ = dstPosition.z;
  54367. } else {
  54368. dstX = 0;
  54369. dstY = 0;
  54370. dstZ = 0;
  54371. }
  54372. // Set up the destination target
  54373. const glFormat = utils.convert( dstTexture.format );
  54374. const glType = utils.convert( dstTexture.type );
  54375. let glTarget;
  54376. if ( dstTexture.isData3DTexture ) {
  54377. textures.setTexture3D( dstTexture, 0 );
  54378. glTarget = _gl.TEXTURE_3D;
  54379. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54380. textures.setTexture2DArray( dstTexture, 0 );
  54381. glTarget = _gl.TEXTURE_2D_ARRAY;
  54382. } else {
  54383. textures.setTexture2D( dstTexture, 0 );
  54384. glTarget = _gl.TEXTURE_2D;
  54385. }
  54386. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54387. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54388. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54389. // used for copying data from cpu
  54390. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54391. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54392. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54393. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54394. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54395. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54396. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54397. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54398. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54399. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54400. // set up the src texture
  54401. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54402. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54403. if ( srcTexture.isDepthTexture ) {
  54404. const srcTextureProperties = properties.get( srcTexture );
  54405. const dstTextureProperties = properties.get( dstTexture );
  54406. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54407. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54408. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54409. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54410. for ( let i = 0; i < depth; i ++ ) {
  54411. // if the source or destination are a 3d target then a layer needs to be bound
  54412. if ( isSrc3D ) {
  54413. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54414. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54415. }
  54416. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54417. }
  54418. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54419. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54420. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54421. // get the appropriate frame buffers
  54422. const srcTextureProperties = properties.get( srcTexture );
  54423. const dstTextureProperties = properties.get( dstTexture );
  54424. // bind the frame buffer targets
  54425. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54426. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54427. for ( let i = 0; i < depth; i ++ ) {
  54428. // assign the correct layers and mip maps to the frame buffers
  54429. if ( isSrc3D ) {
  54430. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54431. } else {
  54432. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54433. }
  54434. if ( isDst3D ) {
  54435. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54436. } else {
  54437. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54438. }
  54439. // copy the data using the fastest function that can achieve the copy
  54440. if ( srcLevel !== 0 ) {
  54441. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54442. } else if ( isDst3D ) {
  54443. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54444. } else {
  54445. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54446. }
  54447. }
  54448. // unbind read, draw buffers
  54449. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54450. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54451. } else {
  54452. if ( isDst3D ) {
  54453. // copy data into the 3d texture
  54454. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54455. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54456. } else if ( dstTexture.isCompressedArrayTexture ) {
  54457. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54458. } else {
  54459. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54460. }
  54461. } else {
  54462. // copy data into the 2d texture
  54463. if ( srcTexture.isDataTexture ) {
  54464. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54465. } else if ( srcTexture.isCompressedTexture ) {
  54466. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54467. } else {
  54468. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54469. }
  54470. }
  54471. }
  54472. // reset values
  54473. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54474. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54475. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54476. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54477. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54478. // Generate mipmaps only when copying level 0
  54479. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54480. _gl.generateMipmap( glTarget );
  54481. }
  54482. state.unbindTexture();
  54483. };
  54484. /**
  54485. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54486. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54487. * rendered to.
  54488. *
  54489. * @param {WebGLRenderTarget} target - The render target.
  54490. */
  54491. this.initRenderTarget = function ( target ) {
  54492. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54493. textures.setupRenderTarget( target );
  54494. }
  54495. };
  54496. /**
  54497. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54498. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54499. *
  54500. * @param {Texture} texture - The texture.
  54501. */
  54502. this.initTexture = function ( texture ) {
  54503. if ( texture.isCubeTexture ) {
  54504. textures.setTextureCube( texture, 0 );
  54505. } else if ( texture.isData3DTexture ) {
  54506. textures.setTexture3D( texture, 0 );
  54507. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54508. textures.setTexture2DArray( texture, 0 );
  54509. } else {
  54510. textures.setTexture2D( texture, 0 );
  54511. }
  54512. state.unbindTexture();
  54513. };
  54514. /**
  54515. * Can be used to reset the internal WebGL state. This method is mostly
  54516. * relevant for applications which share a single WebGL context across
  54517. * multiple WebGL libraries.
  54518. */
  54519. this.resetState = function () {
  54520. _currentActiveCubeFace = 0;
  54521. _currentActiveMipmapLevel = 0;
  54522. _currentRenderTarget = null;
  54523. state.reset();
  54524. bindingStates.reset();
  54525. };
  54526. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54527. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54528. }
  54529. }
  54530. /**
  54531. * Defines the coordinate system of the renderer.
  54532. *
  54533. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54534. *
  54535. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54536. * @default WebGLCoordinateSystem
  54537. * @readonly
  54538. */
  54539. get coordinateSystem() {
  54540. return WebGLCoordinateSystem;
  54541. }
  54542. /**
  54543. * Defines the output color space of the renderer.
  54544. *
  54545. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54546. * @default SRGBColorSpace
  54547. */
  54548. get outputColorSpace() {
  54549. return this._outputColorSpace;
  54550. }
  54551. set outputColorSpace( colorSpace ) {
  54552. this._outputColorSpace = colorSpace;
  54553. const gl = this.getContext();
  54554. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54555. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54556. }
  54557. }
  54558. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  54559. exports.AddEquation = AddEquation;
  54560. exports.AddOperation = AddOperation;
  54561. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  54562. exports.AdditiveBlending = AdditiveBlending;
  54563. exports.AgXToneMapping = AgXToneMapping;
  54564. exports.AlphaFormat = AlphaFormat;
  54565. exports.AlwaysCompare = AlwaysCompare;
  54566. exports.AlwaysDepth = AlwaysDepth;
  54567. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  54568. exports.AmbientLight = AmbientLight;
  54569. exports.AnimationAction = AnimationAction;
  54570. exports.AnimationClip = AnimationClip;
  54571. exports.AnimationLoader = AnimationLoader;
  54572. exports.AnimationMixer = AnimationMixer;
  54573. exports.AnimationObjectGroup = AnimationObjectGroup;
  54574. exports.AnimationUtils = AnimationUtils;
  54575. exports.ArcCurve = ArcCurve;
  54576. exports.ArrayCamera = ArrayCamera;
  54577. exports.ArrowHelper = ArrowHelper;
  54578. exports.AttachedBindMode = AttachedBindMode;
  54579. exports.Audio = Audio;
  54580. exports.AudioAnalyser = AudioAnalyser;
  54581. exports.AudioContext = AudioContext;
  54582. exports.AudioListener = AudioListener;
  54583. exports.AudioLoader = AudioLoader;
  54584. exports.AxesHelper = AxesHelper;
  54585. exports.BackSide = BackSide;
  54586. exports.BasicDepthPacking = BasicDepthPacking;
  54587. exports.BasicShadowMap = BasicShadowMap;
  54588. exports.BatchedMesh = BatchedMesh;
  54589. exports.Bone = Bone;
  54590. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  54591. exports.Box2 = Box2;
  54592. exports.Box3 = Box3;
  54593. exports.Box3Helper = Box3Helper;
  54594. exports.BoxGeometry = BoxGeometry;
  54595. exports.BoxHelper = BoxHelper;
  54596. exports.BufferAttribute = BufferAttribute;
  54597. exports.BufferGeometry = BufferGeometry;
  54598. exports.BufferGeometryLoader = BufferGeometryLoader;
  54599. exports.ByteType = ByteType;
  54600. exports.Cache = Cache;
  54601. exports.Camera = Camera;
  54602. exports.CameraHelper = CameraHelper;
  54603. exports.CanvasTexture = CanvasTexture;
  54604. exports.CapsuleGeometry = CapsuleGeometry;
  54605. exports.CatmullRomCurve3 = CatmullRomCurve3;
  54606. exports.CineonToneMapping = CineonToneMapping;
  54607. exports.CircleGeometry = CircleGeometry;
  54608. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  54609. exports.Clock = Clock;
  54610. exports.Color = Color;
  54611. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  54612. exports.ColorManagement = ColorManagement;
  54613. exports.Compatibility = Compatibility;
  54614. exports.CompressedArrayTexture = CompressedArrayTexture;
  54615. exports.CompressedCubeTexture = CompressedCubeTexture;
  54616. exports.CompressedTexture = CompressedTexture;
  54617. exports.CompressedTextureLoader = CompressedTextureLoader;
  54618. exports.ConeGeometry = ConeGeometry;
  54619. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  54620. exports.ConstantColorFactor = ConstantColorFactor;
  54621. exports.Controls = Controls;
  54622. exports.CubeCamera = CubeCamera;
  54623. exports.CubeDepthTexture = CubeDepthTexture;
  54624. exports.CubeReflectionMapping = CubeReflectionMapping;
  54625. exports.CubeRefractionMapping = CubeRefractionMapping;
  54626. exports.CubeTexture = CubeTexture;
  54627. exports.CubeTextureLoader = CubeTextureLoader;
  54628. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  54629. exports.CubicBezierCurve = CubicBezierCurve;
  54630. exports.CubicBezierCurve3 = CubicBezierCurve3;
  54631. exports.CubicInterpolant = CubicInterpolant;
  54632. exports.CullFaceBack = CullFaceBack;
  54633. exports.CullFaceFront = CullFaceFront;
  54634. exports.CullFaceFrontBack = CullFaceFrontBack;
  54635. exports.CullFaceNone = CullFaceNone;
  54636. exports.Curve = Curve;
  54637. exports.CurvePath = CurvePath;
  54638. exports.CustomBlending = CustomBlending;
  54639. exports.CustomToneMapping = CustomToneMapping;
  54640. exports.CylinderGeometry = CylinderGeometry;
  54641. exports.Cylindrical = Cylindrical;
  54642. exports.Data3DTexture = Data3DTexture;
  54643. exports.DataArrayTexture = DataArrayTexture;
  54644. exports.DataTexture = DataTexture;
  54645. exports.DataTextureLoader = DataTextureLoader;
  54646. exports.DataUtils = DataUtils;
  54647. exports.DecrementStencilOp = DecrementStencilOp;
  54648. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  54649. exports.DefaultLoadingManager = DefaultLoadingManager;
  54650. exports.DepthFormat = DepthFormat;
  54651. exports.DepthStencilFormat = DepthStencilFormat;
  54652. exports.DepthTexture = DepthTexture;
  54653. exports.DetachedBindMode = DetachedBindMode;
  54654. exports.DirectionalLight = DirectionalLight;
  54655. exports.DirectionalLightHelper = DirectionalLightHelper;
  54656. exports.DiscreteInterpolant = DiscreteInterpolant;
  54657. exports.DodecahedronGeometry = DodecahedronGeometry;
  54658. exports.DoubleSide = DoubleSide;
  54659. exports.DstAlphaFactor = DstAlphaFactor;
  54660. exports.DstColorFactor = DstColorFactor;
  54661. exports.DynamicCopyUsage = DynamicCopyUsage;
  54662. exports.DynamicDrawUsage = DynamicDrawUsage;
  54663. exports.DynamicReadUsage = DynamicReadUsage;
  54664. exports.EdgesGeometry = EdgesGeometry;
  54665. exports.EllipseCurve = EllipseCurve;
  54666. exports.EqualCompare = EqualCompare;
  54667. exports.EqualDepth = EqualDepth;
  54668. exports.EqualStencilFunc = EqualStencilFunc;
  54669. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  54670. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  54671. exports.Euler = Euler;
  54672. exports.EventDispatcher = EventDispatcher;
  54673. exports.ExternalTexture = ExternalTexture;
  54674. exports.ExtrudeGeometry = ExtrudeGeometry;
  54675. exports.FileLoader = FileLoader;
  54676. exports.Float16BufferAttribute = Float16BufferAttribute;
  54677. exports.Float32BufferAttribute = Float32BufferAttribute;
  54678. exports.FloatType = FloatType;
  54679. exports.Fog = Fog;
  54680. exports.FogExp2 = FogExp2;
  54681. exports.FramebufferTexture = FramebufferTexture;
  54682. exports.FrontSide = FrontSide;
  54683. exports.Frustum = Frustum;
  54684. exports.FrustumArray = FrustumArray;
  54685. exports.GLBufferAttribute = GLBufferAttribute;
  54686. exports.GLSL1 = GLSL1;
  54687. exports.GLSL3 = GLSL3;
  54688. exports.GreaterCompare = GreaterCompare;
  54689. exports.GreaterDepth = GreaterDepth;
  54690. exports.GreaterEqualCompare = GreaterEqualCompare;
  54691. exports.GreaterEqualDepth = GreaterEqualDepth;
  54692. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  54693. exports.GreaterStencilFunc = GreaterStencilFunc;
  54694. exports.GridHelper = GridHelper;
  54695. exports.Group = Group;
  54696. exports.HalfFloatType = HalfFloatType;
  54697. exports.HemisphereLight = HemisphereLight;
  54698. exports.HemisphereLightHelper = HemisphereLightHelper;
  54699. exports.IcosahedronGeometry = IcosahedronGeometry;
  54700. exports.ImageBitmapLoader = ImageBitmapLoader;
  54701. exports.ImageLoader = ImageLoader;
  54702. exports.ImageUtils = ImageUtils;
  54703. exports.IncrementStencilOp = IncrementStencilOp;
  54704. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  54705. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  54706. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  54707. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  54708. exports.InstancedMesh = InstancedMesh;
  54709. exports.Int16BufferAttribute = Int16BufferAttribute;
  54710. exports.Int32BufferAttribute = Int32BufferAttribute;
  54711. exports.Int8BufferAttribute = Int8BufferAttribute;
  54712. exports.IntType = IntType;
  54713. exports.InterleavedBuffer = InterleavedBuffer;
  54714. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  54715. exports.Interpolant = Interpolant;
  54716. exports.InterpolateDiscrete = InterpolateDiscrete;
  54717. exports.InterpolateLinear = InterpolateLinear;
  54718. exports.InterpolateSmooth = InterpolateSmooth;
  54719. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  54720. exports.InterpolationSamplingType = InterpolationSamplingType;
  54721. exports.InvertStencilOp = InvertStencilOp;
  54722. exports.KeepStencilOp = KeepStencilOp;
  54723. exports.KeyframeTrack = KeyframeTrack;
  54724. exports.LOD = LOD;
  54725. exports.LatheGeometry = LatheGeometry;
  54726. exports.Layers = Layers;
  54727. exports.LessCompare = LessCompare;
  54728. exports.LessDepth = LessDepth;
  54729. exports.LessEqualCompare = LessEqualCompare;
  54730. exports.LessEqualDepth = LessEqualDepth;
  54731. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  54732. exports.LessStencilFunc = LessStencilFunc;
  54733. exports.Light = Light;
  54734. exports.LightProbe = LightProbe;
  54735. exports.Line = Line;
  54736. exports.Line3 = Line3;
  54737. exports.LineBasicMaterial = LineBasicMaterial;
  54738. exports.LineCurve = LineCurve;
  54739. exports.LineCurve3 = LineCurve3;
  54740. exports.LineDashedMaterial = LineDashedMaterial;
  54741. exports.LineLoop = LineLoop;
  54742. exports.LineSegments = LineSegments;
  54743. exports.LinearFilter = LinearFilter;
  54744. exports.LinearInterpolant = LinearInterpolant;
  54745. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  54746. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  54747. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  54748. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  54749. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  54750. exports.LinearToneMapping = LinearToneMapping;
  54751. exports.LinearTransfer = LinearTransfer;
  54752. exports.Loader = Loader;
  54753. exports.LoaderUtils = LoaderUtils;
  54754. exports.LoadingManager = LoadingManager;
  54755. exports.LoopOnce = LoopOnce;
  54756. exports.LoopPingPong = LoopPingPong;
  54757. exports.LoopRepeat = LoopRepeat;
  54758. exports.MOUSE = MOUSE;
  54759. exports.Material = Material;
  54760. exports.MaterialLoader = MaterialLoader;
  54761. exports.MathUtils = MathUtils;
  54762. exports.Matrix2 = Matrix2;
  54763. exports.Matrix3 = Matrix3;
  54764. exports.Matrix4 = Matrix4;
  54765. exports.MaxEquation = MaxEquation;
  54766. exports.Mesh = Mesh;
  54767. exports.MeshBasicMaterial = MeshBasicMaterial;
  54768. exports.MeshDepthMaterial = MeshDepthMaterial;
  54769. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  54770. exports.MeshLambertMaterial = MeshLambertMaterial;
  54771. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  54772. exports.MeshNormalMaterial = MeshNormalMaterial;
  54773. exports.MeshPhongMaterial = MeshPhongMaterial;
  54774. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  54775. exports.MeshStandardMaterial = MeshStandardMaterial;
  54776. exports.MeshToonMaterial = MeshToonMaterial;
  54777. exports.MinEquation = MinEquation;
  54778. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  54779. exports.MixOperation = MixOperation;
  54780. exports.MultiplyBlending = MultiplyBlending;
  54781. exports.MultiplyOperation = MultiplyOperation;
  54782. exports.NearestFilter = NearestFilter;
  54783. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  54784. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  54785. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  54786. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  54787. exports.NeutralToneMapping = NeutralToneMapping;
  54788. exports.NeverCompare = NeverCompare;
  54789. exports.NeverDepth = NeverDepth;
  54790. exports.NeverStencilFunc = NeverStencilFunc;
  54791. exports.NoBlending = NoBlending;
  54792. exports.NoColorSpace = NoColorSpace;
  54793. exports.NoNormalPacking = NoNormalPacking;
  54794. exports.NoToneMapping = NoToneMapping;
  54795. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54796. exports.NormalBlending = NormalBlending;
  54797. exports.NormalGAPacking = NormalGAPacking;
  54798. exports.NormalRGPacking = NormalRGPacking;
  54799. exports.NotEqualCompare = NotEqualCompare;
  54800. exports.NotEqualDepth = NotEqualDepth;
  54801. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  54802. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  54803. exports.Object3D = Object3D;
  54804. exports.ObjectLoader = ObjectLoader;
  54805. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  54806. exports.OctahedronGeometry = OctahedronGeometry;
  54807. exports.OneFactor = OneFactor;
  54808. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  54809. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  54810. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  54811. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  54812. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  54813. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  54814. exports.OrthographicCamera = OrthographicCamera;
  54815. exports.PCFShadowMap = PCFShadowMap;
  54816. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  54817. exports.PMREMGenerator = PMREMGenerator;
  54818. exports.Path = Path;
  54819. exports.PerspectiveCamera = PerspectiveCamera;
  54820. exports.Plane = Plane;
  54821. exports.PlaneGeometry = PlaneGeometry;
  54822. exports.PlaneHelper = PlaneHelper;
  54823. exports.PointLight = PointLight;
  54824. exports.PointLightHelper = PointLightHelper;
  54825. exports.Points = Points;
  54826. exports.PointsMaterial = PointsMaterial;
  54827. exports.PolarGridHelper = PolarGridHelper;
  54828. exports.PolyhedronGeometry = PolyhedronGeometry;
  54829. exports.PositionalAudio = PositionalAudio;
  54830. exports.PropertyBinding = PropertyBinding;
  54831. exports.PropertyMixer = PropertyMixer;
  54832. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  54833. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54834. exports.Quaternion = Quaternion;
  54835. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54836. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54837. exports.R11_EAC_Format = R11_EAC_Format;
  54838. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54839. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54840. exports.REVISION = REVISION;
  54841. exports.RG11_EAC_Format = RG11_EAC_Format;
  54842. exports.RGBADepthPacking = RGBADepthPacking;
  54843. exports.RGBAFormat = RGBAFormat;
  54844. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54845. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54846. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54847. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54848. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54849. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54850. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54851. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54852. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54853. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54854. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54855. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54856. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54857. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54858. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54859. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54860. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54861. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54862. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54863. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54864. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54865. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54866. exports.RGBDepthPacking = RGBDepthPacking;
  54867. exports.RGBFormat = RGBFormat;
  54868. exports.RGBIntegerFormat = RGBIntegerFormat;
  54869. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54870. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54871. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54872. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54873. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54874. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54875. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54876. exports.RGDepthPacking = RGDepthPacking;
  54877. exports.RGFormat = RGFormat;
  54878. exports.RGIntegerFormat = RGIntegerFormat;
  54879. exports.RawShaderMaterial = RawShaderMaterial;
  54880. exports.Ray = Ray;
  54881. exports.Raycaster = Raycaster;
  54882. exports.RectAreaLight = RectAreaLight;
  54883. exports.RedFormat = RedFormat;
  54884. exports.RedIntegerFormat = RedIntegerFormat;
  54885. exports.ReinhardToneMapping = ReinhardToneMapping;
  54886. exports.RenderTarget = RenderTarget;
  54887. exports.RenderTarget3D = RenderTarget3D;
  54888. exports.RepeatWrapping = RepeatWrapping;
  54889. exports.ReplaceStencilOp = ReplaceStencilOp;
  54890. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54891. exports.RingGeometry = RingGeometry;
  54892. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  54893. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54894. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54895. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  54896. exports.SRGBColorSpace = SRGBColorSpace;
  54897. exports.SRGBTransfer = SRGBTransfer;
  54898. exports.Scene = Scene;
  54899. exports.ShaderChunk = ShaderChunk;
  54900. exports.ShaderLib = ShaderLib;
  54901. exports.ShaderMaterial = ShaderMaterial;
  54902. exports.ShadowMaterial = ShadowMaterial;
  54903. exports.Shape = Shape;
  54904. exports.ShapeGeometry = ShapeGeometry;
  54905. exports.ShapePath = ShapePath;
  54906. exports.ShapeUtils = ShapeUtils;
  54907. exports.ShortType = ShortType;
  54908. exports.Skeleton = Skeleton;
  54909. exports.SkeletonHelper = SkeletonHelper;
  54910. exports.SkinnedMesh = SkinnedMesh;
  54911. exports.Source = Source;
  54912. exports.Sphere = Sphere;
  54913. exports.SphereGeometry = SphereGeometry;
  54914. exports.Spherical = Spherical;
  54915. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54916. exports.SplineCurve = SplineCurve;
  54917. exports.SpotLight = SpotLight;
  54918. exports.SpotLightHelper = SpotLightHelper;
  54919. exports.Sprite = Sprite;
  54920. exports.SpriteMaterial = SpriteMaterial;
  54921. exports.SrcAlphaFactor = SrcAlphaFactor;
  54922. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54923. exports.SrcColorFactor = SrcColorFactor;
  54924. exports.StaticCopyUsage = StaticCopyUsage;
  54925. exports.StaticDrawUsage = StaticDrawUsage;
  54926. exports.StaticReadUsage = StaticReadUsage;
  54927. exports.StereoCamera = StereoCamera;
  54928. exports.StreamCopyUsage = StreamCopyUsage;
  54929. exports.StreamDrawUsage = StreamDrawUsage;
  54930. exports.StreamReadUsage = StreamReadUsage;
  54931. exports.StringKeyframeTrack = StringKeyframeTrack;
  54932. exports.SubtractEquation = SubtractEquation;
  54933. exports.SubtractiveBlending = SubtractiveBlending;
  54934. exports.TOUCH = TOUCH;
  54935. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54936. exports.TetrahedronGeometry = TetrahedronGeometry;
  54937. exports.Texture = Texture;
  54938. exports.TextureLoader = TextureLoader;
  54939. exports.TextureUtils = TextureUtils;
  54940. exports.Timer = Timer;
  54941. exports.TimestampQuery = TimestampQuery;
  54942. exports.TorusGeometry = TorusGeometry;
  54943. exports.TorusKnotGeometry = TorusKnotGeometry;
  54944. exports.Triangle = Triangle;
  54945. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54946. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54947. exports.TrianglesDrawMode = TrianglesDrawMode;
  54948. exports.TubeGeometry = TubeGeometry;
  54949. exports.UVMapping = UVMapping;
  54950. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54951. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54952. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54953. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54954. exports.Uniform = Uniform;
  54955. exports.UniformsGroup = UniformsGroup;
  54956. exports.UniformsLib = UniformsLib;
  54957. exports.UniformsUtils = UniformsUtils;
  54958. exports.UnsignedByteType = UnsignedByteType;
  54959. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  54960. exports.UnsignedInt248Type = UnsignedInt248Type;
  54961. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54962. exports.UnsignedIntType = UnsignedIntType;
  54963. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54964. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54965. exports.UnsignedShortType = UnsignedShortType;
  54966. exports.VSMShadowMap = VSMShadowMap;
  54967. exports.Vector2 = Vector2;
  54968. exports.Vector3 = Vector3;
  54969. exports.Vector4 = Vector4;
  54970. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54971. exports.VideoFrameTexture = VideoFrameTexture;
  54972. exports.VideoTexture = VideoTexture;
  54973. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54974. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54975. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54976. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54977. exports.WebGLRenderTarget = WebGLRenderTarget;
  54978. exports.WebGLRenderer = WebGLRenderer;
  54979. exports.WebGLUtils = WebGLUtils;
  54980. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54981. exports.WebXRController = WebXRController;
  54982. exports.WireframeGeometry = WireframeGeometry;
  54983. exports.WrapAroundEnding = WrapAroundEnding;
  54984. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54985. exports.ZeroFactor = ZeroFactor;
  54986. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54987. exports.ZeroStencilOp = ZeroStencilOp;
  54988. exports.createCanvasElement = createCanvasElement;
  54989. exports.error = error;
  54990. exports.getConsoleFunction = getConsoleFunction;
  54991. exports.log = log;
  54992. exports.setConsoleFunction = setConsoleFunction;
  54993. exports.warn = warn;
  54994. exports.warnOnce = warnOnce;
粤ICP备19079148号