three.cjs 1.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '175dev';
  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. * Discards the red, green and blue components and reads just the alpha component.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const AlphaFormat = 1021;
  649. /**
  650. * Discards the alpha component and reads the red, green and blue component.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const RGBFormat = 1022;
  656. /**
  657. * Reads the red, green, blue and alpha components.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const RGBAFormat = 1023;
  663. /**
  664. * reads each element as a single luminance component. This is then converted to a floating point,
  665. * clamped to the range `[0,1]`, and then assembled into an RGBA element by placing the luminance value
  666. * in the red, green and blue channels, and attaching 1.0 to the alpha channel.
  667. *
  668. * @type {number}
  669. * @constant
  670. */
  671. const LuminanceFormat = 1024;
  672. /**
  673. * Reads each element as a luminance/alpha double. The same process occurs as for the `LuminanceFormat`,
  674. * except that the alpha channel may have values other than `1.0`.
  675. *
  676. * @type {number}
  677. * @constant
  678. */
  679. const LuminanceAlphaFormat = 1025;
  680. /**
  681. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  682. *
  683. * @type {number}
  684. * @constant
  685. */
  686. const DepthFormat = 1026;
  687. /**
  688. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  689. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  690. *
  691. * @type {number}
  692. * @constant
  693. */
  694. const DepthStencilFormat = 1027;
  695. /**
  696. * Discards the green, blue and alpha components and reads just the red component.
  697. *
  698. * @type {number}
  699. * @constant
  700. */
  701. const RedFormat = 1028;
  702. /**
  703. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  704. *
  705. * @type {number}
  706. * @constant
  707. */
  708. const RedIntegerFormat = 1029;
  709. /**
  710. * Discards the alpha, and blue components and reads the red, and green components.
  711. *
  712. * @type {number}
  713. * @constant
  714. */
  715. const RGFormat = 1030;
  716. /**
  717. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  718. *
  719. * @type {number}
  720. * @constant
  721. */
  722. const RGIntegerFormat = 1031;
  723. /**
  724. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  725. *
  726. * @type {number}
  727. * @constant
  728. */
  729. const RGBIntegerFormat = 1032;
  730. /**
  731. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  732. *
  733. * @type {number}
  734. * @constant
  735. */
  736. const RGBAIntegerFormat = 1033;
  737. /**
  738. * A DXT1-compressed image in an RGB image format.
  739. *
  740. * @type {number}
  741. * @constant
  742. */
  743. const RGB_S3TC_DXT1_Format = 33776;
  744. /**
  745. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  746. *
  747. * @type {number}
  748. * @constant
  749. */
  750. const RGBA_S3TC_DXT1_Format = 33777;
  751. /**
  752. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  753. *
  754. * @type {number}
  755. * @constant
  756. */
  757. const RGBA_S3TC_DXT3_Format = 33778;
  758. /**
  759. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  760. * compression in how the alpha compression is done.
  761. *
  762. * @type {number}
  763. * @constant
  764. */
  765. const RGBA_S3TC_DXT5_Format = 33779;
  766. /**
  767. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  768. *
  769. * @type {number}
  770. * @constant
  771. */
  772. const RGB_PVRTC_4BPPV1_Format = 35840;
  773. /**
  774. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  775. *
  776. * @type {number}
  777. * @constant
  778. */
  779. const RGB_PVRTC_2BPPV1_Format = 35841;
  780. /**
  781. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  782. *
  783. * @type {number}
  784. * @constant
  785. */
  786. const RGBA_PVRTC_4BPPV1_Format = 35842;
  787. /**
  788. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  789. *
  790. * @type {number}
  791. * @constant
  792. */
  793. const RGBA_PVRTC_2BPPV1_Format = 35843;
  794. /**
  795. * ETC1 RGB format.
  796. *
  797. * @type {number}
  798. * @constant
  799. */
  800. const RGB_ETC1_Format = 36196;
  801. /**
  802. * ETC2 RGB format.
  803. *
  804. * @type {number}
  805. * @constant
  806. */
  807. const RGB_ETC2_Format = 37492;
  808. /**
  809. * ETC2 RGBA format.
  810. *
  811. * @type {number}
  812. * @constant
  813. */
  814. const RGBA_ETC2_EAC_Format = 37496;
  815. /**
  816. * ASTC RGBA 4x4 format.
  817. *
  818. * @type {number}
  819. * @constant
  820. */
  821. const RGBA_ASTC_4x4_Format = 37808;
  822. /**
  823. * ASTC RGBA 5x4 format.
  824. *
  825. * @type {number}
  826. * @constant
  827. */
  828. const RGBA_ASTC_5x4_Format = 37809;
  829. /**
  830. * ASTC RGBA 5x5 format.
  831. *
  832. * @type {number}
  833. * @constant
  834. */
  835. const RGBA_ASTC_5x5_Format = 37810;
  836. /**
  837. * ASTC RGBA 6x5 format.
  838. *
  839. * @type {number}
  840. * @constant
  841. */
  842. const RGBA_ASTC_6x5_Format = 37811;
  843. /**
  844. * ASTC RGBA 6x6 format.
  845. *
  846. * @type {number}
  847. * @constant
  848. */
  849. const RGBA_ASTC_6x6_Format = 37812;
  850. /**
  851. * ASTC RGBA 8x5 format.
  852. *
  853. * @type {number}
  854. * @constant
  855. */
  856. const RGBA_ASTC_8x5_Format = 37813;
  857. /**
  858. * ASTC RGBA 8x6 format.
  859. *
  860. * @type {number}
  861. * @constant
  862. */
  863. const RGBA_ASTC_8x6_Format = 37814;
  864. /**
  865. * ASTC RGBA 8x8 format.
  866. *
  867. * @type {number}
  868. * @constant
  869. */
  870. const RGBA_ASTC_8x8_Format = 37815;
  871. /**
  872. * ASTC RGBA 10x5 format.
  873. *
  874. * @type {number}
  875. * @constant
  876. */
  877. const RGBA_ASTC_10x5_Format = 37816;
  878. /**
  879. * ASTC RGBA 10x6 format.
  880. *
  881. * @type {number}
  882. * @constant
  883. */
  884. const RGBA_ASTC_10x6_Format = 37817;
  885. /**
  886. * ASTC RGBA 10x8 format.
  887. *
  888. * @type {number}
  889. * @constant
  890. */
  891. const RGBA_ASTC_10x8_Format = 37818;
  892. /**
  893. * ASTC RGBA 10x10 format.
  894. *
  895. * @type {number}
  896. * @constant
  897. */
  898. const RGBA_ASTC_10x10_Format = 37819;
  899. /**
  900. * ASTC RGBA 12x10 format.
  901. *
  902. * @type {number}
  903. * @constant
  904. */
  905. const RGBA_ASTC_12x10_Format = 37820;
  906. /**
  907. * ASTC RGBA 12x12 format.
  908. *
  909. * @type {number}
  910. * @constant
  911. */
  912. const RGBA_ASTC_12x12_Format = 37821;
  913. /**
  914. * BPTC RGBA format.
  915. *
  916. * @type {number}
  917. * @constant
  918. */
  919. const RGBA_BPTC_Format = 36492;
  920. /**
  921. * BPTC Signed RGB format.
  922. *
  923. * @type {number}
  924. * @constant
  925. */
  926. const RGB_BPTC_SIGNED_Format = 36494;
  927. /**
  928. * BPTC Unsigned RGB format.
  929. *
  930. * @type {number}
  931. * @constant
  932. */
  933. const RGB_BPTC_UNSIGNED_Format = 36495;
  934. /**
  935. * RGTC1 Red format.
  936. *
  937. * @type {number}
  938. * @constant
  939. */
  940. const RED_RGTC1_Format = 36283;
  941. /**
  942. * RGTC1 Signed Red format.
  943. *
  944. * @type {number}
  945. * @constant
  946. */
  947. const SIGNED_RED_RGTC1_Format = 36284;
  948. /**
  949. * RGTC2 Red Green format.
  950. *
  951. * @type {number}
  952. * @constant
  953. */
  954. const RED_GREEN_RGTC2_Format = 36285;
  955. /**
  956. * RGTC2 Signed Red Green format.
  957. *
  958. * @type {number}
  959. * @constant
  960. */
  961. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  962. /**
  963. * Animations are played once.
  964. *
  965. * @type {number}
  966. * @constant
  967. */
  968. const LoopOnce = 2200;
  969. /**
  970. * Animations are played with a chosen number of repetitions, each time jumping from
  971. * the end of the clip directly to its beginning.
  972. *
  973. * @type {number}
  974. * @constant
  975. */
  976. const LoopRepeat = 2201;
  977. /**
  978. * Animations are played with a chosen number of repetitions, alternately playing forward
  979. * and backward.
  980. *
  981. * @type {number}
  982. * @constant
  983. */
  984. const LoopPingPong = 2202;
  985. /**
  986. * Discrete interpolation mode for keyframe tracks.
  987. *
  988. * @type {number}
  989. * @constant
  990. */
  991. const InterpolateDiscrete = 2300;
  992. /**
  993. * Linear interpolation mode for keyframe tracks.
  994. *
  995. * @type {number}
  996. * @constant
  997. */
  998. const InterpolateLinear = 2301;
  999. /**
  1000. * Smooth interpolation mode for keyframe tracks.
  1001. *
  1002. * @type {number}
  1003. * @constant
  1004. */
  1005. const InterpolateSmooth = 2302;
  1006. /**
  1007. * Zero curvature ending for animations.
  1008. *
  1009. * @type {number}
  1010. * @constant
  1011. */
  1012. const ZeroCurvatureEnding = 2400;
  1013. /**
  1014. * Zero slope ending for animations.
  1015. *
  1016. * @type {number}
  1017. * @constant
  1018. */
  1019. const ZeroSlopeEnding = 2401;
  1020. /**
  1021. * Wrap around ending for animations.
  1022. *
  1023. * @type {number}
  1024. * @constant
  1025. */
  1026. const WrapAroundEnding = 2402;
  1027. /**
  1028. * Default animation blend mode.
  1029. *
  1030. * @type {number}
  1031. * @constant
  1032. */
  1033. const NormalAnimationBlendMode = 2500;
  1034. /**
  1035. * Additive animation blend mode. Can be used to layer motions on top of
  1036. * each other to build complex performances from smaller re-usable assets.
  1037. *
  1038. * @type {number}
  1039. * @constant
  1040. */
  1041. const AdditiveAnimationBlendMode = 2501;
  1042. /**
  1043. * For every three vertices draw a single triangle.
  1044. *
  1045. * @type {number}
  1046. * @constant
  1047. */
  1048. const TrianglesDrawMode = 0;
  1049. /**
  1050. * For each vertex draw a triangle from the last three vertices.
  1051. *
  1052. * @type {number}
  1053. * @constant
  1054. */
  1055. const TriangleStripDrawMode = 1;
  1056. /**
  1057. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1058. *
  1059. * @type {number}
  1060. * @constant
  1061. */
  1062. const TriangleFanDrawMode = 2;
  1063. /**
  1064. * Basic depth packing.
  1065. *
  1066. * @type {number}
  1067. * @constant
  1068. */
  1069. const BasicDepthPacking = 3200;
  1070. /**
  1071. * A depth value is packed into 32 bit RGBA.
  1072. *
  1073. * @type {number}
  1074. * @constant
  1075. */
  1076. const RGBADepthPacking = 3201;
  1077. /**
  1078. * A depth value is packed into 24 bit RGB.
  1079. *
  1080. * @type {number}
  1081. * @constant
  1082. */
  1083. const RGBDepthPacking = 3202;
  1084. /**
  1085. * A depth value is packed into 16 bit RG.
  1086. *
  1087. * @type {number}
  1088. * @constant
  1089. */
  1090. const RGDepthPacking = 3203;
  1091. /**
  1092. * Normal information is relative to the underlying surface.
  1093. *
  1094. * @type {number}
  1095. * @constant
  1096. */
  1097. const TangentSpaceNormalMap = 0;
  1098. /**
  1099. * Normal information is relative to the object orientation.
  1100. *
  1101. * @type {number}
  1102. * @constant
  1103. */
  1104. const ObjectSpaceNormalMap = 1;
  1105. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1106. /**
  1107. * No color space.
  1108. *
  1109. * @type {string}
  1110. * @constant
  1111. */
  1112. const NoColorSpace = '';
  1113. /**
  1114. * sRGB color space.
  1115. *
  1116. * @type {string}
  1117. * @constant
  1118. */
  1119. const SRGBColorSpace = 'srgb';
  1120. /**
  1121. * sRGB-linear color space.
  1122. *
  1123. * @type {string}
  1124. * @constant
  1125. */
  1126. const LinearSRGBColorSpace = 'srgb-linear';
  1127. /**
  1128. * Linear transfer function.
  1129. *
  1130. * @type {string}
  1131. * @constant
  1132. */
  1133. const LinearTransfer = 'linear';
  1134. /**
  1135. * sRGB transfer function.
  1136. *
  1137. * @type {string}
  1138. * @constant
  1139. */
  1140. const SRGBTransfer = 'srgb';
  1141. /**
  1142. * Sets the stencil buffer value to `0`.
  1143. *
  1144. * @type {number}
  1145. * @constant
  1146. */
  1147. const ZeroStencilOp = 0;
  1148. /**
  1149. * Keeps the current value.
  1150. *
  1151. * @type {number}
  1152. * @constant
  1153. */
  1154. const KeepStencilOp = 7680;
  1155. /**
  1156. * Sets the stencil buffer value to the specified reference value.
  1157. *
  1158. * @type {number}
  1159. * @constant
  1160. */
  1161. const ReplaceStencilOp = 7681;
  1162. /**
  1163. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1164. *
  1165. * @type {number}
  1166. * @constant
  1167. */
  1168. const IncrementStencilOp = 7682;
  1169. /**
  1170. * Decrements the current stencil buffer value. Clamps to `0`.
  1171. *
  1172. * @type {number}
  1173. * @constant
  1174. */
  1175. const DecrementStencilOp = 7683;
  1176. /**
  1177. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1178. * the maximum representable unsigned value.
  1179. *
  1180. * @type {number}
  1181. * @constant
  1182. */
  1183. const IncrementWrapStencilOp = 34055;
  1184. /**
  1185. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1186. * unsigned value when decrementing a stencil buffer value of `0`.
  1187. *
  1188. * @type {number}
  1189. * @constant
  1190. */
  1191. const DecrementWrapStencilOp = 34056;
  1192. /**
  1193. * Inverts the current stencil buffer value bitwise.
  1194. *
  1195. * @type {number}
  1196. * @constant
  1197. */
  1198. const InvertStencilOp = 5386;
  1199. /**
  1200. * Will never return true.
  1201. *
  1202. * @type {number}
  1203. * @constant
  1204. */
  1205. const NeverStencilFunc = 512;
  1206. /**
  1207. * Will return true if the stencil reference value is less than the current stencil value.
  1208. *
  1209. * @type {number}
  1210. * @constant
  1211. */
  1212. const LessStencilFunc = 513;
  1213. /**
  1214. * Will return true if the stencil reference value is equal to the current stencil value.
  1215. *
  1216. * @type {number}
  1217. * @constant
  1218. */
  1219. const EqualStencilFunc = 514;
  1220. /**
  1221. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1222. *
  1223. * @type {number}
  1224. * @constant
  1225. */
  1226. const LessEqualStencilFunc = 515;
  1227. /**
  1228. * Will return true if the stencil reference value is greater than the current stencil value.
  1229. *
  1230. * @type {number}
  1231. * @constant
  1232. */
  1233. const GreaterStencilFunc = 516;
  1234. /**
  1235. * Will return true if the stencil reference value is not equal to the current stencil value.
  1236. *
  1237. * @type {number}
  1238. * @constant
  1239. */
  1240. const NotEqualStencilFunc = 517;
  1241. /**
  1242. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1243. *
  1244. * @type {number}
  1245. * @constant
  1246. */
  1247. const GreaterEqualStencilFunc = 518;
  1248. /**
  1249. * Will always return true.
  1250. *
  1251. * @type {number}
  1252. * @constant
  1253. */
  1254. const AlwaysStencilFunc = 519;
  1255. /**
  1256. * Never pass.
  1257. *
  1258. * @type {number}
  1259. * @constant
  1260. */
  1261. const NeverCompare = 512;
  1262. /**
  1263. * Pass if the incoming value is less than the texture value.
  1264. *
  1265. * @type {number}
  1266. * @constant
  1267. */
  1268. const LessCompare = 513;
  1269. /**
  1270. * Pass if the incoming value equals the texture value.
  1271. *
  1272. * @type {number}
  1273. * @constant
  1274. */
  1275. const EqualCompare = 514;
  1276. /**
  1277. * Pass if the incoming value is less than or equal to the texture value.
  1278. *
  1279. * @type {number}
  1280. * @constant
  1281. */
  1282. const LessEqualCompare = 515;
  1283. /**
  1284. * Pass if the incoming value is greater than the texture value.
  1285. *
  1286. * @type {number}
  1287. * @constant
  1288. */
  1289. const GreaterCompare = 516;
  1290. /**
  1291. * Pass if the incoming value is not equal to the texture value.
  1292. *
  1293. * @type {number}
  1294. * @constant
  1295. */
  1296. const NotEqualCompare = 517;
  1297. /**
  1298. * Pass if the incoming value is greater than or equal to the texture value.
  1299. *
  1300. * @type {number}
  1301. * @constant
  1302. */
  1303. const GreaterEqualCompare = 518;
  1304. /**
  1305. * Always pass.
  1306. *
  1307. * @type {number}
  1308. * @constant
  1309. */
  1310. const AlwaysCompare = 519;
  1311. /**
  1312. * The contents are intended to be specified once by the application, and used many
  1313. * times as the source for drawing and image specification commands.
  1314. *
  1315. * @type {number}
  1316. * @constant
  1317. */
  1318. const StaticDrawUsage = 35044;
  1319. /**
  1320. * The contents are intended to be respecified repeatedly by the application, and
  1321. * used many times as the source for drawing and image specification commands.
  1322. *
  1323. * @type {number}
  1324. * @constant
  1325. */
  1326. const DynamicDrawUsage = 35048;
  1327. /**
  1328. * The contents are intended to be specified once by the application, and used at most
  1329. * a few times as the source for drawing and image specification commands.
  1330. *
  1331. * @type {number}
  1332. * @constant
  1333. */
  1334. const StreamDrawUsage = 35040;
  1335. /**
  1336. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1337. * many times by the application.
  1338. *
  1339. * @type {number}
  1340. * @constant
  1341. */
  1342. const StaticReadUsage = 35045;
  1343. /**
  1344. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1345. * many times by the application.
  1346. *
  1347. * @type {number}
  1348. * @constant
  1349. */
  1350. const DynamicReadUsage = 35049;
  1351. /**
  1352. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1353. * a few times by the application
  1354. *
  1355. * @type {number}
  1356. * @constant
  1357. */
  1358. const StreamReadUsage = 35041;
  1359. /**
  1360. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1361. * the source for WebGL drawing and image specification commands.
  1362. *
  1363. * @type {number}
  1364. * @constant
  1365. */
  1366. const StaticCopyUsage = 35046;
  1367. /**
  1368. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1369. * as the source for WebGL drawing and image specification commands.
  1370. *
  1371. * @type {number}
  1372. * @constant
  1373. */
  1374. const DynamicCopyUsage = 35050;
  1375. /**
  1376. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1377. * as the source for WebGL drawing and image specification commands.
  1378. *
  1379. * @type {number}
  1380. * @constant
  1381. */
  1382. const StreamCopyUsage = 35042;
  1383. /**
  1384. * GLSL 1 shader code.
  1385. *
  1386. * @type {string}
  1387. * @constant
  1388. */
  1389. const GLSL1 = '100';
  1390. /**
  1391. * GLSL 3 shader code.
  1392. *
  1393. * @type {string}
  1394. * @constant
  1395. */
  1396. const GLSL3 = '300 es';
  1397. /**
  1398. * WebGL coordinate system.
  1399. *
  1400. * @type {number}
  1401. * @constant
  1402. */
  1403. const WebGLCoordinateSystem = 2000;
  1404. /**
  1405. * WebGPU coordinate system.
  1406. *
  1407. * @type {number}
  1408. * @constant
  1409. */
  1410. const WebGPUCoordinateSystem = 2001;
  1411. /**
  1412. * Represents the different timestamp query types.
  1413. *
  1414. * @type {ConstantsTimestampQuery}
  1415. * @constant
  1416. */
  1417. const TimestampQuery = {
  1418. COMPUTE: 'compute',
  1419. RENDER: 'render'
  1420. };
  1421. /**
  1422. * This type represents mouse buttons and interaction types in context of controls.
  1423. *
  1424. * @typedef {Object} ConstantsMouse
  1425. * @property {number} MIDDLE - The left mouse button.
  1426. * @property {number} LEFT - The middle mouse button.
  1427. * @property {number} RIGHT - The right mouse button.
  1428. * @property {number} ROTATE - A rotate interaction.
  1429. * @property {number} DOLLY - A dolly interaction.
  1430. * @property {number} PAN - A pan interaction.
  1431. **/
  1432. /**
  1433. * This type represents touch interaction types in context of controls.
  1434. *
  1435. * @typedef {Object} ConstantsTouch
  1436. * @property {number} ROTATE - A rotate interaction.
  1437. * @property {number} PAN - A pan interaction.
  1438. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1439. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1440. **/
  1441. /**
  1442. * This type represents the different timestamp query types.
  1443. *
  1444. * @typedef {Object} ConstantsTimestampQuery
  1445. * @property {string} COMPUTE - A `compute` timestamp query.
  1446. * @property {string} RENDER - A `render` timestamp query.
  1447. **/
  1448. /**
  1449. * This modules allows to dispatch event objects on custom JavaScript objects.
  1450. *
  1451. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1452. *
  1453. * Code Example:
  1454. * ```js
  1455. * class Car extends EventDispatcher {
  1456. * start() {
  1457. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1458. * }
  1459. *};
  1460. *
  1461. * // Using events with the custom object
  1462. * const car = new Car();
  1463. * car.addEventListener( 'start', function ( event ) {
  1464. * alert( event.message );
  1465. * } );
  1466. *
  1467. * car.start();
  1468. * ```
  1469. */
  1470. class EventDispatcher {
  1471. /**
  1472. * Adds the given event listener to the given event type.
  1473. *
  1474. * @param {string} type - The type of event to listen to.
  1475. * @param {Function} listener - The function that gets called when the event is fired.
  1476. */
  1477. addEventListener( type, listener ) {
  1478. if ( this._listeners === undefined ) this._listeners = {};
  1479. const listeners = this._listeners;
  1480. if ( listeners[ type ] === undefined ) {
  1481. listeners[ type ] = [];
  1482. }
  1483. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1484. listeners[ type ].push( listener );
  1485. }
  1486. }
  1487. /**
  1488. * Returns `true` if the given event listener has been added to the given event type.
  1489. *
  1490. * @param {string} type - The type of event.
  1491. * @param {Function} listener - The listener to check.
  1492. * @return {boolean} Whether the given event listener has been added to the given event type.
  1493. */
  1494. hasEventListener( type, listener ) {
  1495. const listeners = this._listeners;
  1496. if ( listeners === undefined ) return false;
  1497. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  1498. }
  1499. /**
  1500. * Removes the given event listener from the given event type.
  1501. *
  1502. * @param {string} type - The type of event.
  1503. * @param {Function} listener - The listener to remove.
  1504. */
  1505. removeEventListener( type, listener ) {
  1506. const listeners = this._listeners;
  1507. if ( listeners === undefined ) return;
  1508. const listenerArray = listeners[ type ];
  1509. if ( listenerArray !== undefined ) {
  1510. const index = listenerArray.indexOf( listener );
  1511. if ( index !== - 1 ) {
  1512. listenerArray.splice( index, 1 );
  1513. }
  1514. }
  1515. }
  1516. /**
  1517. * Dispatches an event object.
  1518. *
  1519. * @param {Object} event - The event that gets fired.
  1520. */
  1521. dispatchEvent( event ) {
  1522. const listeners = this._listeners;
  1523. if ( listeners === undefined ) return;
  1524. const listenerArray = listeners[ event.type ];
  1525. if ( listenerArray !== undefined ) {
  1526. event.target = this;
  1527. // Make a copy, in case listeners are removed while iterating.
  1528. const array = listenerArray.slice( 0 );
  1529. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1530. array[ i ].call( this, event );
  1531. }
  1532. event.target = null;
  1533. }
  1534. }
  1535. }
  1536. 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' ];
  1537. let _seed = 1234567;
  1538. const DEG2RAD = Math.PI / 180;
  1539. const RAD2DEG = 180 / Math.PI;
  1540. /**
  1541. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1542. * (universally unique identifier).
  1543. *
  1544. * @return {string} The UUID.
  1545. */
  1546. function generateUUID() {
  1547. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1548. const d0 = Math.random() * 0xffffffff | 0;
  1549. const d1 = Math.random() * 0xffffffff | 0;
  1550. const d2 = Math.random() * 0xffffffff | 0;
  1551. const d3 = Math.random() * 0xffffffff | 0;
  1552. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1553. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1554. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1555. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1556. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1557. return uuid.toLowerCase();
  1558. }
  1559. /**
  1560. * Clamps the given value between min and max.
  1561. *
  1562. * @param {number} value - The value to clamp.
  1563. * @param {number} min - The min value.
  1564. * @param {number} max - The max value.
  1565. * @return {number} The clamped value.
  1566. */
  1567. function clamp( value, min, max ) {
  1568. return Math.max( min, Math.min( max, value ) );
  1569. }
  1570. /**
  1571. * Computes the Euclidean modulo of the given parameters that
  1572. * is `( ( n % m ) + m ) % m`.
  1573. *
  1574. * @param {number} n - The first parameter.
  1575. * @param {number} m - The second parameter.
  1576. * @return {number} The Euclidean modulo.
  1577. */
  1578. function euclideanModulo( n, m ) {
  1579. // https://en.wikipedia.org/wiki/Modulo_operation
  1580. return ( ( n % m ) + m ) % m;
  1581. }
  1582. /**
  1583. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1584. * for the given value.
  1585. *
  1586. * @param {number} x - The value to be mapped.
  1587. * @param {number} a1 - Minimum value for range A.
  1588. * @param {number} a2 - Maximum value for range A.
  1589. * @param {number} b1 - Minimum value for range B.
  1590. * @param {number} b2 - Maximum value for range B.
  1591. * @return {number} The mapped value.
  1592. */
  1593. function mapLinear( x, a1, a2, b1, b2 ) {
  1594. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1595. }
  1596. /**
  1597. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1598. * between the start and end point.
  1599. *
  1600. * @param {number} x - The start point
  1601. * @param {number} y - The end point.
  1602. * @param {number} value - A value between start and end.
  1603. * @return {number} The interpolation factor.
  1604. */
  1605. function inverseLerp( x, y, value ) {
  1606. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1607. if ( x !== y ) {
  1608. return ( value - x ) / ( y - x );
  1609. } else {
  1610. return 0;
  1611. }
  1612. }
  1613. /**
  1614. * Returns a value linearly interpolated from two known points based on the given interval -
  1615. * `t = 0` will return `x` and `t = 1` will return `y`.
  1616. *
  1617. * @param {number} x - The start point
  1618. * @param {number} y - The end point.
  1619. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1620. * @return {number} The interpolated value.
  1621. */
  1622. function lerp( x, y, t ) {
  1623. return ( 1 - t ) * x + t * y;
  1624. }
  1625. /**
  1626. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1627. * time to maintain frame rate independent movement. For details, see
  1628. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1629. *
  1630. * @param {number} x - The current point.
  1631. * @param {number} y - The target point.
  1632. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1633. * and a lower value will make the movement more gradual.
  1634. * @param {number} dt - Delta time in seconds.
  1635. * @return {number} The interpolated value.
  1636. */
  1637. function damp( x, y, lambda, dt ) {
  1638. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1639. }
  1640. /**
  1641. * Returns a value that alternates between `0` and the given `length` parameter.
  1642. *
  1643. * @param {number} x - The value to pingpong.
  1644. * @param {number} [length=1] - The positive value the function will pingpong to.
  1645. * @return {number} The alternated value.
  1646. */
  1647. function pingpong( x, length = 1 ) {
  1648. // https://www.desmos.com/calculator/vcsjnyz7x4
  1649. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1650. }
  1651. /**
  1652. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1653. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1654. * the `min` and `max`.
  1655. *
  1656. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1657. *
  1658. * @param {number} x - The value to evaluate based on its position between min and max.
  1659. * @param {number} min - The min value. Any x value below min will be `0`.
  1660. * @param {number} max - The max value. Any x value above max will be `1`.
  1661. * @return {number} The alternated value.
  1662. */
  1663. function smoothstep( x, min, max ) {
  1664. if ( x <= min ) return 0;
  1665. if ( x >= max ) return 1;
  1666. x = ( x - min ) / ( max - min );
  1667. return x * x * ( 3 - 2 * x );
  1668. }
  1669. /**
  1670. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1671. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1672. *
  1673. * @param {number} x - The value to evaluate based on its position between min and max.
  1674. * @param {number} min - The min value. Any x value below min will be `0`.
  1675. * @param {number} max - The max value. Any x value above max will be `1`.
  1676. * @return {number} The alternated value.
  1677. */
  1678. function smootherstep( x, min, max ) {
  1679. if ( x <= min ) return 0;
  1680. if ( x >= max ) return 1;
  1681. x = ( x - min ) / ( max - min );
  1682. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1683. }
  1684. /**
  1685. * Returns a random integer from `<low, high>` interval.
  1686. *
  1687. * @param {number} low - The lower value boundary.
  1688. * @param {number} high - The upper value boundary
  1689. * @return {number} A random integer.
  1690. */
  1691. function randInt( low, high ) {
  1692. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1693. }
  1694. /**
  1695. * Returns a random float from `<low, high>` interval.
  1696. *
  1697. * @param {number} low - The lower value boundary.
  1698. * @param {number} high - The upper value boundary
  1699. * @return {number} A random float.
  1700. */
  1701. function randFloat( low, high ) {
  1702. return low + Math.random() * ( high - low );
  1703. }
  1704. /**
  1705. * Returns a random integer from `<-range/2, range/2>` interval.
  1706. *
  1707. * @param {number} range - Defines the value range.
  1708. * @return {number} A random float.
  1709. */
  1710. function randFloatSpread( range ) {
  1711. return range * ( 0.5 - Math.random() );
  1712. }
  1713. /**
  1714. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1715. *
  1716. * @param {number} [s] - The integer seed.
  1717. * @return {number} A random float.
  1718. */
  1719. function seededRandom( s ) {
  1720. if ( s !== undefined ) _seed = s;
  1721. // Mulberry32 generator
  1722. let t = _seed += 0x6D2B79F5;
  1723. t = Math.imul( t ^ t >>> 15, t | 1 );
  1724. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1725. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1726. }
  1727. /**
  1728. * Converts degrees to radians.
  1729. *
  1730. * @param {number} degrees - A value in degrees.
  1731. * @return {number} The converted value in radians.
  1732. */
  1733. function degToRad( degrees ) {
  1734. return degrees * DEG2RAD;
  1735. }
  1736. /**
  1737. * Converts radians to degrees.
  1738. *
  1739. * @param {number} radians - A value in radians.
  1740. * @return {number} The converted value in degrees.
  1741. */
  1742. function radToDeg( radians ) {
  1743. return radians * RAD2DEG;
  1744. }
  1745. /**
  1746. * Returns `true` if the given number is a power of two.
  1747. *
  1748. * @param {number} value - The value to check.
  1749. * @return {boolean} Whether the given number is a power of two or not.
  1750. */
  1751. function isPowerOfTwo( value ) {
  1752. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1753. }
  1754. /**
  1755. * Returns the smallest power of two that is greater than or equal to the given number.
  1756. *
  1757. * @param {number} value - The value to find a POT for.
  1758. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1759. */
  1760. function ceilPowerOfTwo( value ) {
  1761. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1762. }
  1763. /**
  1764. * Returns the largest power of two that is less than or equal to the given number.
  1765. *
  1766. * @param {number} value - The value to find a POT for.
  1767. * @return {number} The largest power of two that is less than or equal to the given number.
  1768. */
  1769. function floorPowerOfTwo( value ) {
  1770. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1771. }
  1772. /**
  1773. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1774. * defined by the given angles and order.
  1775. *
  1776. * Rotations are applied to the axes in the order specified by order:
  1777. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1778. *
  1779. * @param {Quaternion} q - The quaternion to set.
  1780. * @param {number} a - The rotation applied to the first axis, in radians.
  1781. * @param {number} b - The rotation applied to the second axis, in radians.
  1782. * @param {number} c - The rotation applied to the third axis, in radians.
  1783. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1784. */
  1785. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1786. const cos = Math.cos;
  1787. const sin = Math.sin;
  1788. const c2 = cos( b / 2 );
  1789. const s2 = sin( b / 2 );
  1790. const c13 = cos( ( a + c ) / 2 );
  1791. const s13 = sin( ( a + c ) / 2 );
  1792. const c1_3 = cos( ( a - c ) / 2 );
  1793. const s1_3 = sin( ( a - c ) / 2 );
  1794. const c3_1 = cos( ( c - a ) / 2 );
  1795. const s3_1 = sin( ( c - a ) / 2 );
  1796. switch ( order ) {
  1797. case 'XYX':
  1798. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1799. break;
  1800. case 'YZY':
  1801. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1802. break;
  1803. case 'ZXZ':
  1804. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1805. break;
  1806. case 'XZX':
  1807. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1808. break;
  1809. case 'YXY':
  1810. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1811. break;
  1812. case 'ZYZ':
  1813. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1814. break;
  1815. default:
  1816. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1817. }
  1818. }
  1819. /**
  1820. * Denormalizes the given value according to the given typed array.
  1821. *
  1822. * @param {number} value - The value to denormalize.
  1823. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1824. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1825. */
  1826. function denormalize( value, array ) {
  1827. switch ( array.constructor ) {
  1828. case Float32Array:
  1829. return value;
  1830. case Uint32Array:
  1831. return value / 4294967295.0;
  1832. case Uint16Array:
  1833. return value / 65535.0;
  1834. case Uint8Array:
  1835. return value / 255.0;
  1836. case Int32Array:
  1837. return Math.max( value / 2147483647.0, - 1.0 );
  1838. case Int16Array:
  1839. return Math.max( value / 32767.0, - 1.0 );
  1840. case Int8Array:
  1841. return Math.max( value / 127.0, - 1.0 );
  1842. default:
  1843. throw new Error( 'Invalid component type.' );
  1844. }
  1845. }
  1846. /**
  1847. * Normalizes the given value according to the given typed array.
  1848. *
  1849. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1850. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1851. * @return {number} The normalize value.
  1852. */
  1853. function normalize( value, array ) {
  1854. switch ( array.constructor ) {
  1855. case Float32Array:
  1856. return value;
  1857. case Uint32Array:
  1858. return Math.round( value * 4294967295.0 );
  1859. case Uint16Array:
  1860. return Math.round( value * 65535.0 );
  1861. case Uint8Array:
  1862. return Math.round( value * 255.0 );
  1863. case Int32Array:
  1864. return Math.round( value * 2147483647.0 );
  1865. case Int16Array:
  1866. return Math.round( value * 32767.0 );
  1867. case Int8Array:
  1868. return Math.round( value * 127.0 );
  1869. default:
  1870. throw new Error( 'Invalid component type.' );
  1871. }
  1872. }
  1873. /**
  1874. * @class
  1875. * @classdesc A collection of math utility functions.
  1876. * @hideconstructor
  1877. */
  1878. const MathUtils = {
  1879. DEG2RAD: DEG2RAD,
  1880. RAD2DEG: RAD2DEG,
  1881. /**
  1882. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1883. * (universally unique identifier).
  1884. *
  1885. * @static
  1886. * @method
  1887. * @return {string} The UUID.
  1888. */
  1889. generateUUID: generateUUID,
  1890. /**
  1891. * Clamps the given value between min and max.
  1892. *
  1893. * @static
  1894. * @method
  1895. * @param {number} value - The value to clamp.
  1896. * @param {number} min - The min value.
  1897. * @param {number} max - The max value.
  1898. * @return {number} The clamped value.
  1899. */
  1900. clamp: clamp,
  1901. /**
  1902. * Computes the Euclidean modulo of the given parameters that
  1903. * is `( ( n % m ) + m ) % m`.
  1904. *
  1905. * @static
  1906. * @method
  1907. * @param {number} n - The first parameter.
  1908. * @param {number} m - The second parameter.
  1909. * @return {number} The Euclidean modulo.
  1910. */
  1911. euclideanModulo: euclideanModulo,
  1912. /**
  1913. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1914. * for the given value.
  1915. *
  1916. * @static
  1917. * @method
  1918. * @param {number} x - The value to be mapped.
  1919. * @param {number} a1 - Minimum value for range A.
  1920. * @param {number} a2 - Maximum value for range A.
  1921. * @param {number} b1 - Minimum value for range B.
  1922. * @param {number} b2 - Maximum value for range B.
  1923. * @return {number} The mapped value.
  1924. */
  1925. mapLinear: mapLinear,
  1926. /**
  1927. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1928. * between the start and end point.
  1929. *
  1930. * @static
  1931. * @method
  1932. * @param {number} x - The start point
  1933. * @param {number} y - The end point.
  1934. * @param {number} value - A value between start and end.
  1935. * @return {number} The interpolation factor.
  1936. */
  1937. inverseLerp: inverseLerp,
  1938. /**
  1939. * Returns a value linearly interpolated from two known points based on the given interval -
  1940. * `t = 0` will return `x` and `t = 1` will return `y`.
  1941. *
  1942. * @static
  1943. * @method
  1944. * @param {number} x - The start point
  1945. * @param {number} y - The end point.
  1946. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1947. * @return {number} The interpolated value.
  1948. */
  1949. lerp: lerp,
  1950. /**
  1951. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1952. * time to maintain frame rate independent movement. For details, see
  1953. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1954. *
  1955. * @static
  1956. * @method
  1957. * @param {number} x - The current point.
  1958. * @param {number} y - The target point.
  1959. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1960. * and a lower value will make the movement more gradual.
  1961. * @param {number} dt - Delta time in seconds.
  1962. * @return {number} The interpolated value.
  1963. */
  1964. damp: damp,
  1965. /**
  1966. * Returns a value that alternates between `0` and the given `length` parameter.
  1967. *
  1968. * @static
  1969. * @method
  1970. * @param {number} x - The value to pingpong.
  1971. * @param {number} [length=1] - The positive value the function will pingpong to.
  1972. * @return {number} The alternated value.
  1973. */
  1974. pingpong: pingpong,
  1975. /**
  1976. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1977. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1978. * the `min` and `max`.
  1979. *
  1980. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1981. *
  1982. * @static
  1983. * @method
  1984. * @param {number} x - The value to evaluate based on its position between min and max.
  1985. * @param {number} min - The min value. Any x value below min will be `0`.
  1986. * @param {number} max - The max value. Any x value above max will be `1`.
  1987. * @return {number} The alternated value.
  1988. */
  1989. smoothstep: smoothstep,
  1990. /**
  1991. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1992. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1993. *
  1994. * @static
  1995. * @method
  1996. * @param {number} x - The value to evaluate based on its position between min and max.
  1997. * @param {number} min - The min value. Any x value below min will be `0`.
  1998. * @param {number} max - The max value. Any x value above max will be `1`.
  1999. * @return {number} The alternated value.
  2000. */
  2001. smootherstep: smootherstep,
  2002. /**
  2003. * Returns a random integer from `<low, high>` interval.
  2004. *
  2005. * @static
  2006. * @method
  2007. * @param {number} low - The lower value boundary.
  2008. * @param {number} high - The upper value boundary
  2009. * @return {number} A random integer.
  2010. */
  2011. randInt: randInt,
  2012. /**
  2013. * Returns a random float from `<low, high>` interval.
  2014. *
  2015. * @static
  2016. * @method
  2017. * @param {number} low - The lower value boundary.
  2018. * @param {number} high - The upper value boundary
  2019. * @return {number} A random float.
  2020. */
  2021. randFloat: randFloat,
  2022. /**
  2023. * Returns a random integer from `<-range/2, range/2>` interval.
  2024. *
  2025. * @static
  2026. * @method
  2027. * @param {number} range - Defines the value range.
  2028. * @return {number} A random float.
  2029. */
  2030. randFloatSpread: randFloatSpread,
  2031. /**
  2032. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2033. *
  2034. * @static
  2035. * @method
  2036. * @param {number} [s] - The integer seed.
  2037. * @return {number} A random float.
  2038. */
  2039. seededRandom: seededRandom,
  2040. /**
  2041. * Converts degrees to radians.
  2042. *
  2043. * @static
  2044. * @method
  2045. * @param {number} degrees - A value in degrees.
  2046. * @return {number} The converted value in radians.
  2047. */
  2048. degToRad: degToRad,
  2049. /**
  2050. * Converts radians to degrees.
  2051. *
  2052. * @static
  2053. * @method
  2054. * @param {number} radians - A value in radians.
  2055. * @return {number} The converted value in degrees.
  2056. */
  2057. radToDeg: radToDeg,
  2058. /**
  2059. * Returns `true` if the given number is a power of two.
  2060. *
  2061. * @static
  2062. * @method
  2063. * @param {number} value - The value to check.
  2064. * @return {boolean} Whether the given number is a power of two or not.
  2065. */
  2066. isPowerOfTwo: isPowerOfTwo,
  2067. /**
  2068. * Returns the smallest power of two that is greater than or equal to the given number.
  2069. *
  2070. * @static
  2071. * @method
  2072. * @param {number} value - The value to find a POT for.
  2073. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2074. */
  2075. ceilPowerOfTwo: ceilPowerOfTwo,
  2076. /**
  2077. * Returns the largest power of two that is less than or equal to the given number.
  2078. *
  2079. * @static
  2080. * @method
  2081. * @param {number} value - The value to find a POT for.
  2082. * @return {number} The largest power of two that is less than or equal to the given number.
  2083. */
  2084. floorPowerOfTwo: floorPowerOfTwo,
  2085. /**
  2086. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2087. * defined by the given angles and order.
  2088. *
  2089. * Rotations are applied to the axes in the order specified by order:
  2090. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2091. *
  2092. * @static
  2093. * @method
  2094. * @param {Quaternion} q - The quaternion to set.
  2095. * @param {number} a - The rotation applied to the first axis, in radians.
  2096. * @param {number} b - The rotation applied to the second axis, in radians.
  2097. * @param {number} c - The rotation applied to the third axis, in radians.
  2098. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2099. */
  2100. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2101. /**
  2102. * Normalizes the given value according to the given typed array.
  2103. *
  2104. * @static
  2105. * @method
  2106. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2107. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2108. * @return {number} The normalize value.
  2109. */
  2110. normalize: normalize,
  2111. /**
  2112. * Denormalizes the given value according to the given typed array.
  2113. *
  2114. * @static
  2115. * @method
  2116. * @param {number} value - The value to denormalize.
  2117. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2118. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2119. */
  2120. denormalize: denormalize
  2121. };
  2122. /**
  2123. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2124. * (labeled x and y), which can be used to represent a number of things, such as:
  2125. *
  2126. * - A point in 2D space (i.e. a position on a plane).
  2127. * - A direction and length across a plane. In three.js the length will
  2128. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2129. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2130. * - Any arbitrary ordered pair of numbers.
  2131. *
  2132. * There are other things a 2D vector can be used to represent, such as
  2133. * momentum vectors, complex numbers and so on, however these are the most
  2134. * common uses in three.js.
  2135. *
  2136. * Iterating through a vector instance will yield its components `(x, y)` in
  2137. * the corresponding order.
  2138. * ```js
  2139. * const a = new THREE.Vector2( 0, 1 );
  2140. *
  2141. * //no arguments; will be initialised to (0, 0)
  2142. * const b = new THREE.Vector2( );
  2143. *
  2144. * const d = a.distanceTo( b );
  2145. * ```
  2146. */
  2147. class Vector2 {
  2148. /**
  2149. * Constructs a new 2D vector.
  2150. *
  2151. * @param {number} [x=0] - The x value of this vector.
  2152. * @param {number} [y=0] - The y value of this vector.
  2153. */
  2154. constructor( x = 0, y = 0 ) {
  2155. /**
  2156. * This flag can be used for type testing.
  2157. *
  2158. * @type {boolean}
  2159. * @readonly
  2160. * @default true
  2161. */
  2162. Vector2.prototype.isVector2 = true;
  2163. /**
  2164. * The x value of this vector.
  2165. *
  2166. * @type {number}
  2167. */
  2168. this.x = x;
  2169. /**
  2170. * The y value of this vector.
  2171. *
  2172. * @type {number}
  2173. */
  2174. this.y = y;
  2175. }
  2176. /**
  2177. * Alias for {@link Vector2#x}.
  2178. *
  2179. * @type {number}
  2180. */
  2181. get width() {
  2182. return this.x;
  2183. }
  2184. set width( value ) {
  2185. this.x = value;
  2186. }
  2187. /**
  2188. * Alias for {@link Vector2#y}.
  2189. *
  2190. * @type {number}
  2191. */
  2192. get height() {
  2193. return this.y;
  2194. }
  2195. set height( value ) {
  2196. this.y = value;
  2197. }
  2198. /**
  2199. * Sets the vector components.
  2200. *
  2201. * @param {number} x - The value of the x component.
  2202. * @param {number} y - The value of the y component.
  2203. * @return {Vector2} A reference to this vector.
  2204. */
  2205. set( x, y ) {
  2206. this.x = x;
  2207. this.y = y;
  2208. return this;
  2209. }
  2210. /**
  2211. * Sets the vector components to the same value.
  2212. *
  2213. * @param {number} scalar - The value to set for all vector components.
  2214. * @return {Vector2} A reference to this vector.
  2215. */
  2216. setScalar( scalar ) {
  2217. this.x = scalar;
  2218. this.y = scalar;
  2219. return this;
  2220. }
  2221. /**
  2222. * Sets the vector's x component to the given value
  2223. *
  2224. * @param {number} x - The value to set.
  2225. * @return {Vector2} A reference to this vector.
  2226. */
  2227. setX( x ) {
  2228. this.x = x;
  2229. return this;
  2230. }
  2231. /**
  2232. * Sets the vector's y component to the given value
  2233. *
  2234. * @param {number} y - The value to set.
  2235. * @return {Vector2} A reference to this vector.
  2236. */
  2237. setY( y ) {
  2238. this.y = y;
  2239. return this;
  2240. }
  2241. /**
  2242. * Allows to set a vector component with an index.
  2243. *
  2244. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2245. * @param {number} value - The value to set.
  2246. * @return {Vector2} A reference to this vector.
  2247. */
  2248. setComponent( index, value ) {
  2249. switch ( index ) {
  2250. case 0: this.x = value; break;
  2251. case 1: this.y = value; break;
  2252. default: throw new Error( 'index is out of range: ' + index );
  2253. }
  2254. return this;
  2255. }
  2256. /**
  2257. * Returns the value of the vector component which matches the given index.
  2258. *
  2259. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2260. * @return {number} A vector component value.
  2261. */
  2262. getComponent( index ) {
  2263. switch ( index ) {
  2264. case 0: return this.x;
  2265. case 1: return this.y;
  2266. default: throw new Error( 'index is out of range: ' + index );
  2267. }
  2268. }
  2269. /**
  2270. * Returns a new vector with copied values from this instance.
  2271. *
  2272. * @return {Vector2} A clone of this instance.
  2273. */
  2274. clone() {
  2275. return new this.constructor( this.x, this.y );
  2276. }
  2277. /**
  2278. * Copies the values of the given vector to this instance.
  2279. *
  2280. * @param {Vector2} v - The vector to copy.
  2281. * @return {Vector2} A reference to this vector.
  2282. */
  2283. copy( v ) {
  2284. this.x = v.x;
  2285. this.y = v.y;
  2286. return this;
  2287. }
  2288. /**
  2289. * Adds the given vector to this instance.
  2290. *
  2291. * @param {Vector2} v - The vector to add.
  2292. * @return {Vector2} A reference to this vector.
  2293. */
  2294. add( v ) {
  2295. this.x += v.x;
  2296. this.y += v.y;
  2297. return this;
  2298. }
  2299. /**
  2300. * Adds the given scalar value to all components of this instance.
  2301. *
  2302. * @param {number} s - The scalar to add.
  2303. * @return {Vector2} A reference to this vector.
  2304. */
  2305. addScalar( s ) {
  2306. this.x += s;
  2307. this.y += s;
  2308. return this;
  2309. }
  2310. /**
  2311. * Adds the given vectors and stores the result in this instance.
  2312. *
  2313. * @param {Vector2} a - The first vector.
  2314. * @param {Vector2} b - The second vector.
  2315. * @return {Vector2} A reference to this vector.
  2316. */
  2317. addVectors( a, b ) {
  2318. this.x = a.x + b.x;
  2319. this.y = a.y + b.y;
  2320. return this;
  2321. }
  2322. /**
  2323. * Adds the given vector scaled by the given factor to this instance.
  2324. *
  2325. * @param {Vector2} v - The vector.
  2326. * @param {number} s - The factor that scales `v`.
  2327. * @return {Vector2} A reference to this vector.
  2328. */
  2329. addScaledVector( v, s ) {
  2330. this.x += v.x * s;
  2331. this.y += v.y * s;
  2332. return this;
  2333. }
  2334. /**
  2335. * Subtracts the given vector from this instance.
  2336. *
  2337. * @param {Vector2} v - The vector to subtract.
  2338. * @return {Vector2} A reference to this vector.
  2339. */
  2340. sub( v ) {
  2341. this.x -= v.x;
  2342. this.y -= v.y;
  2343. return this;
  2344. }
  2345. /**
  2346. * Subtracts the given scalar value from all components of this instance.
  2347. *
  2348. * @param {number} s - The scalar to subtract.
  2349. * @return {Vector2} A reference to this vector.
  2350. */
  2351. subScalar( s ) {
  2352. this.x -= s;
  2353. this.y -= s;
  2354. return this;
  2355. }
  2356. /**
  2357. * Subtracts the given vectors and stores the result in this instance.
  2358. *
  2359. * @param {Vector2} a - The first vector.
  2360. * @param {Vector2} b - The second vector.
  2361. * @return {Vector2} A reference to this vector.
  2362. */
  2363. subVectors( a, b ) {
  2364. this.x = a.x - b.x;
  2365. this.y = a.y - b.y;
  2366. return this;
  2367. }
  2368. /**
  2369. * Multiplies the given vector with this instance.
  2370. *
  2371. * @param {Vector2} v - The vector to multiply.
  2372. * @return {Vector2} A reference to this vector.
  2373. */
  2374. multiply( v ) {
  2375. this.x *= v.x;
  2376. this.y *= v.y;
  2377. return this;
  2378. }
  2379. /**
  2380. * Multiplies the given scalar value with all components of this instance.
  2381. *
  2382. * @param {number} scalar - The scalar to multiply.
  2383. * @return {Vector2} A reference to this vector.
  2384. */
  2385. multiplyScalar( scalar ) {
  2386. this.x *= scalar;
  2387. this.y *= scalar;
  2388. return this;
  2389. }
  2390. /**
  2391. * Divides this instance by the given vector.
  2392. *
  2393. * @param {Vector2} v - The vector to divide.
  2394. * @return {Vector2} A reference to this vector.
  2395. */
  2396. divide( v ) {
  2397. this.x /= v.x;
  2398. this.y /= v.y;
  2399. return this;
  2400. }
  2401. /**
  2402. * Divides this vector by the given scalar.
  2403. *
  2404. * @param {number} scalar - The scalar to divide.
  2405. * @return {Vector2} A reference to this vector.
  2406. */
  2407. divideScalar( scalar ) {
  2408. return this.multiplyScalar( 1 / scalar );
  2409. }
  2410. /**
  2411. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2412. * the given 3x3 matrix.
  2413. *
  2414. * @param {Matrix3} m - The matrix to apply.
  2415. * @return {Vector2} A reference to this vector.
  2416. */
  2417. applyMatrix3( m ) {
  2418. const x = this.x, y = this.y;
  2419. const e = m.elements;
  2420. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2421. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2422. return this;
  2423. }
  2424. /**
  2425. * If this vector's x or y value is greater than the given vector's x or y
  2426. * value, replace that value with the corresponding min value.
  2427. *
  2428. * @param {Vector2} v - The vector.
  2429. * @return {Vector2} A reference to this vector.
  2430. */
  2431. min( v ) {
  2432. this.x = Math.min( this.x, v.x );
  2433. this.y = Math.min( this.y, v.y );
  2434. return this;
  2435. }
  2436. /**
  2437. * If this vector's x or y value is less than the given vector's x or y
  2438. * value, replace that value with the corresponding max value.
  2439. *
  2440. * @param {Vector2} v - The vector.
  2441. * @return {Vector2} A reference to this vector.
  2442. */
  2443. max( v ) {
  2444. this.x = Math.max( this.x, v.x );
  2445. this.y = Math.max( this.y, v.y );
  2446. return this;
  2447. }
  2448. /**
  2449. * If this vector's x or y value is greater than the max vector's x or y
  2450. * value, it is replaced by the corresponding value.
  2451. * If this vector's x or y value is less than the min vector's x or y value,
  2452. * it is replaced by the corresponding value.
  2453. *
  2454. * @param {Vector2} min - The minimum x and y values.
  2455. * @param {Vector2} max - The maximum x and y values in the desired range.
  2456. * @return {Vector2} A reference to this vector.
  2457. */
  2458. clamp( min, max ) {
  2459. // assumes min < max, componentwise
  2460. this.x = clamp( this.x, min.x, max.x );
  2461. this.y = clamp( this.y, min.y, max.y );
  2462. return this;
  2463. }
  2464. /**
  2465. * If this vector's x or y values are greater than the max value, they are
  2466. * replaced by the max value.
  2467. * If this vector's x or y values are less than the min value, they are
  2468. * replaced by the min value.
  2469. *
  2470. * @param {number} minVal - The minimum value the components will be clamped to.
  2471. * @param {number} maxVal - The maximum value the components will be clamped to.
  2472. * @return {Vector2} A reference to this vector.
  2473. */
  2474. clampScalar( minVal, maxVal ) {
  2475. this.x = clamp( this.x, minVal, maxVal );
  2476. this.y = clamp( this.y, minVal, maxVal );
  2477. return this;
  2478. }
  2479. /**
  2480. * If this vector's length is greater than the max value, it is replaced by
  2481. * the max value.
  2482. * If this vector's length is less than the min value, it is replaced by the
  2483. * min value.
  2484. *
  2485. * @param {number} min - The minimum value the vector length will be clamped to.
  2486. * @param {number} max - The maximum value the vector length will be clamped to.
  2487. * @return {Vector2} A reference to this vector.
  2488. */
  2489. clampLength( min, max ) {
  2490. const length = this.length();
  2491. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2492. }
  2493. /**
  2494. * The components of this vector are rounded down to the nearest integer value.
  2495. *
  2496. * @return {Vector2} A reference to this vector.
  2497. */
  2498. floor() {
  2499. this.x = Math.floor( this.x );
  2500. this.y = Math.floor( this.y );
  2501. return this;
  2502. }
  2503. /**
  2504. * The components of this vector are rounded up to the nearest integer value.
  2505. *
  2506. * @return {Vector2} A reference to this vector.
  2507. */
  2508. ceil() {
  2509. this.x = Math.ceil( this.x );
  2510. this.y = Math.ceil( this.y );
  2511. return this;
  2512. }
  2513. /**
  2514. * The components of this vector are rounded to the nearest integer value
  2515. *
  2516. * @return {Vector2} A reference to this vector.
  2517. */
  2518. round() {
  2519. this.x = Math.round( this.x );
  2520. this.y = Math.round( this.y );
  2521. return this;
  2522. }
  2523. /**
  2524. * The components of this vector are rounded towards zero (up if negative,
  2525. * down if positive) to an integer value.
  2526. *
  2527. * @return {Vector2} A reference to this vector.
  2528. */
  2529. roundToZero() {
  2530. this.x = Math.trunc( this.x );
  2531. this.y = Math.trunc( this.y );
  2532. return this;
  2533. }
  2534. /**
  2535. * Inverts this vector - i.e. sets x = -x and y = -y.
  2536. *
  2537. * @return {Vector2} A reference to this vector.
  2538. */
  2539. negate() {
  2540. this.x = - this.x;
  2541. this.y = - this.y;
  2542. return this;
  2543. }
  2544. /**
  2545. * Calculates the dot product of the given vector with this instance.
  2546. *
  2547. * @param {Vector2} v - The vector to compute the dot product with.
  2548. * @return {number} The result of the dot product.
  2549. */
  2550. dot( v ) {
  2551. return this.x * v.x + this.y * v.y;
  2552. }
  2553. /**
  2554. * Calculates the cross product of the given vector with this instance.
  2555. *
  2556. * @param {Vector2} v - The vector to compute the cross product with.
  2557. * @return {number} The result of the cross product.
  2558. */
  2559. cross( v ) {
  2560. return this.x * v.y - this.y * v.x;
  2561. }
  2562. /**
  2563. * Computes the square of the Euclidean length (straight-line length) from
  2564. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2565. * compare the length squared instead as it is slightly more efficient to calculate.
  2566. *
  2567. * @return {number} The square length of this vector.
  2568. */
  2569. lengthSq() {
  2570. return this.x * this.x + this.y * this.y;
  2571. }
  2572. /**
  2573. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2574. *
  2575. * @return {number} The length of this vector.
  2576. */
  2577. length() {
  2578. return Math.sqrt( this.x * this.x + this.y * this.y );
  2579. }
  2580. /**
  2581. * Computes the Manhattan length of this vector.
  2582. *
  2583. * @return {number} The length of this vector.
  2584. */
  2585. manhattanLength() {
  2586. return Math.abs( this.x ) + Math.abs( this.y );
  2587. }
  2588. /**
  2589. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2590. * with the same direction as this one, but with a vector length of `1`.
  2591. *
  2592. * @return {Vector2} A reference to this vector.
  2593. */
  2594. normalize() {
  2595. return this.divideScalar( this.length() || 1 );
  2596. }
  2597. /**
  2598. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2599. *
  2600. * @return {number} The angle in radians.
  2601. */
  2602. angle() {
  2603. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2604. return angle;
  2605. }
  2606. /**
  2607. * Returns the angle between the given vector and this instance in radians.
  2608. *
  2609. * @param {Vector2} v - The vector to compute the angle with.
  2610. * @return {number} The angle in radians.
  2611. */
  2612. angleTo( v ) {
  2613. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2614. if ( denominator === 0 ) return Math.PI / 2;
  2615. const theta = this.dot( v ) / denominator;
  2616. // clamp, to handle numerical problems
  2617. return Math.acos( clamp( theta, - 1, 1 ) );
  2618. }
  2619. /**
  2620. * Computes the distance from the given vector to this instance.
  2621. *
  2622. * @param {Vector2} v - The vector to compute the distance to.
  2623. * @return {number} The distance.
  2624. */
  2625. distanceTo( v ) {
  2626. return Math.sqrt( this.distanceToSquared( v ) );
  2627. }
  2628. /**
  2629. * Computes the squared distance from the given vector to this instance.
  2630. * If you are just comparing the distance with another distance, you should compare
  2631. * the distance squared instead as it is slightly more efficient to calculate.
  2632. *
  2633. * @param {Vector2} v - The vector to compute the squared distance to.
  2634. * @return {number} The squared distance.
  2635. */
  2636. distanceToSquared( v ) {
  2637. const dx = this.x - v.x, dy = this.y - v.y;
  2638. return dx * dx + dy * dy;
  2639. }
  2640. /**
  2641. * Computes the Manhattan distance from the given vector to this instance.
  2642. *
  2643. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2644. * @return {number} The Manhattan distance.
  2645. */
  2646. manhattanDistanceTo( v ) {
  2647. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2648. }
  2649. /**
  2650. * Sets this vector to a vector with the same direction as this one, but
  2651. * with the specified length.
  2652. *
  2653. * @param {number} length - The new length of this vector.
  2654. * @return {Vector2} A reference to this vector.
  2655. */
  2656. setLength( length ) {
  2657. return this.normalize().multiplyScalar( length );
  2658. }
  2659. /**
  2660. * Linearly interpolates between the given vector and this instance, where
  2661. * alpha is the percent distance along the line - alpha = 0 will be this
  2662. * vector, and alpha = 1 will be the given one.
  2663. *
  2664. * @param {Vector2} v - The vector to interpolate towards.
  2665. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2666. * @return {Vector2} A reference to this vector.
  2667. */
  2668. lerp( v, alpha ) {
  2669. this.x += ( v.x - this.x ) * alpha;
  2670. this.y += ( v.y - this.y ) * alpha;
  2671. return this;
  2672. }
  2673. /**
  2674. * Linearly interpolates between the given vectors, where alpha is the percent
  2675. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2676. * be the second one. The result is stored in this instance.
  2677. *
  2678. * @param {Vector2} v1 - The first vector.
  2679. * @param {Vector2} v2 - The second vector.
  2680. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2681. * @return {Vector2} A reference to this vector.
  2682. */
  2683. lerpVectors( v1, v2, alpha ) {
  2684. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2685. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2686. return this;
  2687. }
  2688. /**
  2689. * Returns `true` if this vector is equal with the given one.
  2690. *
  2691. * @param {Vector2} v - The vector to test for equality.
  2692. * @return {boolean} Whether this vector is equal with the given one.
  2693. */
  2694. equals( v ) {
  2695. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2696. }
  2697. /**
  2698. * Sets this vector's x value to be `array[ offset ]` and y
  2699. * value to be `array[ offset + 1 ]`.
  2700. *
  2701. * @param {Array<number>} array - An array holding the vector component values.
  2702. * @param {number} [offset=0] - The offset into the array.
  2703. * @return {Vector2} A reference to this vector.
  2704. */
  2705. fromArray( array, offset = 0 ) {
  2706. this.x = array[ offset ];
  2707. this.y = array[ offset + 1 ];
  2708. return this;
  2709. }
  2710. /**
  2711. * Writes the components of this vector to the given array. If no array is provided,
  2712. * the method returns a new instance.
  2713. *
  2714. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2715. * @param {number} [offset=0] - Index of the first element in the array.
  2716. * @return {Array<number>} The vector components.
  2717. */
  2718. toArray( array = [], offset = 0 ) {
  2719. array[ offset ] = this.x;
  2720. array[ offset + 1 ] = this.y;
  2721. return array;
  2722. }
  2723. /**
  2724. * Sets the components of this vector from the given buffer attribute.
  2725. *
  2726. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2727. * @param {number} index - The index into the attribute.
  2728. * @return {Vector2} A reference to this vector.
  2729. */
  2730. fromBufferAttribute( attribute, index ) {
  2731. this.x = attribute.getX( index );
  2732. this.y = attribute.getY( index );
  2733. return this;
  2734. }
  2735. /**
  2736. * Rotates this vector around the given center by the given angle.
  2737. *
  2738. * @param {Vector2} center - The point around which to rotate.
  2739. * @param {number} angle - The angle to rotate, in radians.
  2740. * @return {Vector2} A reference to this vector.
  2741. */
  2742. rotateAround( center, angle ) {
  2743. const c = Math.cos( angle ), s = Math.sin( angle );
  2744. const x = this.x - center.x;
  2745. const y = this.y - center.y;
  2746. this.x = x * c - y * s + center.x;
  2747. this.y = x * s + y * c + center.y;
  2748. return this;
  2749. }
  2750. /**
  2751. * Sets each component of this vector to a pseudo-random value between `0` and
  2752. * `1`, excluding `1`.
  2753. *
  2754. * @return {Vector2} A reference to this vector.
  2755. */
  2756. random() {
  2757. this.x = Math.random();
  2758. this.y = Math.random();
  2759. return this;
  2760. }
  2761. *[ Symbol.iterator ]() {
  2762. yield this.x;
  2763. yield this.y;
  2764. }
  2765. }
  2766. /**
  2767. * Represents a 3x3 matrix.
  2768. *
  2769. * A Note on Row-Major and Column-Major Ordering:
  2770. *
  2771. * The constructor and {@link Matrix3#set} method take arguments in
  2772. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  2773. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  2774. * This means that calling:
  2775. * ```js
  2776. * const m = new THREE.Matrix();
  2777. * m.set( 11, 12, 13,
  2778. * 21, 22, 23,
  2779. * 31, 32, 33 );
  2780. * ```
  2781. * will result in the elements array containing:
  2782. * ```js
  2783. * m.elements = [ 11, 21, 31,
  2784. * 12, 22, 32,
  2785. * 13, 23, 33 ];
  2786. * ```
  2787. * and internally all calculations are performed using column-major ordering.
  2788. * However, as the actual ordering makes no difference mathematically and
  2789. * most people are used to thinking about matrices in row-major order, the
  2790. * three.js documentation shows matrices in row-major order. Just bear in
  2791. * mind that if you are reading the source code, you'll have to take the
  2792. * transpose of any matrices outlined here to make sense of the calculations.
  2793. */
  2794. class Matrix3 {
  2795. /**
  2796. * Constructs a new 3x3 matrix. The arguments are supposed to be
  2797. * in row-major order. If no arguments are provided, the constructor
  2798. * initializes the matrix as an identity matrix.
  2799. *
  2800. * @param {number} [n11] - 1-1 matrix element.
  2801. * @param {number} [n12] - 1-2 matrix element.
  2802. * @param {number} [n13] - 1-3 matrix element.
  2803. * @param {number} [n21] - 2-1 matrix element.
  2804. * @param {number} [n22] - 2-2 matrix element.
  2805. * @param {number} [n23] - 2-3 matrix element.
  2806. * @param {number} [n31] - 3-1 matrix element.
  2807. * @param {number} [n32] - 3-2 matrix element.
  2808. * @param {number} [n33] - 3-3 matrix element.
  2809. */
  2810. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2811. /**
  2812. * This flag can be used for type testing.
  2813. *
  2814. * @type {boolean}
  2815. * @readonly
  2816. * @default true
  2817. */
  2818. Matrix3.prototype.isMatrix3 = true;
  2819. /**
  2820. * A column-major list of matrix values.
  2821. *
  2822. * @type {Array<number>}
  2823. */
  2824. this.elements = [
  2825. 1, 0, 0,
  2826. 0, 1, 0,
  2827. 0, 0, 1
  2828. ];
  2829. if ( n11 !== undefined ) {
  2830. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  2831. }
  2832. }
  2833. /**
  2834. * Sets the elements of the matrix.The arguments are supposed to be
  2835. * in row-major order.
  2836. *
  2837. * @param {number} [n11] - 1-1 matrix element.
  2838. * @param {number} [n12] - 1-2 matrix element.
  2839. * @param {number} [n13] - 1-3 matrix element.
  2840. * @param {number} [n21] - 2-1 matrix element.
  2841. * @param {number} [n22] - 2-2 matrix element.
  2842. * @param {number} [n23] - 2-3 matrix element.
  2843. * @param {number} [n31] - 3-1 matrix element.
  2844. * @param {number} [n32] - 3-2 matrix element.
  2845. * @param {number} [n33] - 3-3 matrix element.
  2846. * @return {Matrix3} A reference to this matrix.
  2847. */
  2848. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2849. const te = this.elements;
  2850. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  2851. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  2852. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  2853. return this;
  2854. }
  2855. /**
  2856. * Sets this matrix to the 3x3 identity matrix.
  2857. *
  2858. * @return {Matrix3} A reference to this matrix.
  2859. */
  2860. identity() {
  2861. this.set(
  2862. 1, 0, 0,
  2863. 0, 1, 0,
  2864. 0, 0, 1
  2865. );
  2866. return this;
  2867. }
  2868. /**
  2869. * Copies the values of the given matrix to this instance.
  2870. *
  2871. * @param {Matrix3} m - The matrix to copy.
  2872. * @return {Matrix3} A reference to this matrix.
  2873. */
  2874. copy( m ) {
  2875. const te = this.elements;
  2876. const me = m.elements;
  2877. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  2878. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  2879. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  2880. return this;
  2881. }
  2882. /**
  2883. * Extracts the basis of this matrix into the three axis vectors provided.
  2884. *
  2885. * @param {Vector3} xAxis - The basis's x axis.
  2886. * @param {Vector3} yAxis - The basis's y axis.
  2887. * @param {Vector3} zAxis - The basis's z axis.
  2888. * @return {Matrix3} A reference to this matrix.
  2889. */
  2890. extractBasis( xAxis, yAxis, zAxis ) {
  2891. xAxis.setFromMatrix3Column( this, 0 );
  2892. yAxis.setFromMatrix3Column( this, 1 );
  2893. zAxis.setFromMatrix3Column( this, 2 );
  2894. return this;
  2895. }
  2896. /**
  2897. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  2898. *
  2899. * @param {Matrix4} m - The 4x4 matrix.
  2900. * @return {Matrix3} A reference to this matrix.
  2901. */
  2902. setFromMatrix4( m ) {
  2903. const me = m.elements;
  2904. this.set(
  2905. me[ 0 ], me[ 4 ], me[ 8 ],
  2906. me[ 1 ], me[ 5 ], me[ 9 ],
  2907. me[ 2 ], me[ 6 ], me[ 10 ]
  2908. );
  2909. return this;
  2910. }
  2911. /**
  2912. * Post-multiplies this matrix by the given 3x3 matrix.
  2913. *
  2914. * @param {Matrix3} m - The matrix to multiply with.
  2915. * @return {Matrix3} A reference to this matrix.
  2916. */
  2917. multiply( m ) {
  2918. return this.multiplyMatrices( this, m );
  2919. }
  2920. /**
  2921. * Pre-multiplies this matrix by the given 3x3 matrix.
  2922. *
  2923. * @param {Matrix3} m - The matrix to multiply with.
  2924. * @return {Matrix3} A reference to this matrix.
  2925. */
  2926. premultiply( m ) {
  2927. return this.multiplyMatrices( m, this );
  2928. }
  2929. /**
  2930. * Multiples the given 3x3 matrices and stores the result
  2931. * in this matrix.
  2932. *
  2933. * @param {Matrix3} a - The first matrix.
  2934. * @param {Matrix3} b - The second matrix.
  2935. * @return {Matrix3} A reference to this matrix.
  2936. */
  2937. multiplyMatrices( a, b ) {
  2938. const ae = a.elements;
  2939. const be = b.elements;
  2940. const te = this.elements;
  2941. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  2942. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  2943. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  2944. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  2945. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  2946. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  2947. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  2948. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  2949. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  2950. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  2951. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  2952. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  2953. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  2954. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  2955. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  2956. return this;
  2957. }
  2958. /**
  2959. * Multiplies every component of the matrix by the given scalar.
  2960. *
  2961. * @param {number} s - The scalar.
  2962. * @return {Matrix3} A reference to this matrix.
  2963. */
  2964. multiplyScalar( s ) {
  2965. const te = this.elements;
  2966. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2967. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2968. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2969. return this;
  2970. }
  2971. /**
  2972. * Computes and returns the determinant of this matrix.
  2973. *
  2974. * @return {number} The determinant.
  2975. */
  2976. determinant() {
  2977. const te = this.elements;
  2978. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2979. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2980. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2981. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2982. }
  2983. /**
  2984. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  2985. * You can not invert with a determinant of zero. If you attempt this, the method produces
  2986. * a zero matrix instead.
  2987. *
  2988. * @return {Matrix3} A reference to this matrix.
  2989. */
  2990. invert() {
  2991. const te = this.elements,
  2992. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  2993. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  2994. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  2995. t11 = n33 * n22 - n32 * n23,
  2996. t12 = n32 * n13 - n33 * n12,
  2997. t13 = n23 * n12 - n22 * n13,
  2998. det = n11 * t11 + n21 * t12 + n31 * t13;
  2999. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3000. const detInv = 1 / det;
  3001. te[ 0 ] = t11 * detInv;
  3002. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  3003. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  3004. te[ 3 ] = t12 * detInv;
  3005. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  3006. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  3007. te[ 6 ] = t13 * detInv;
  3008. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  3009. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  3010. return this;
  3011. }
  3012. /**
  3013. * Transposes this matrix in place.
  3014. *
  3015. * @return {Matrix3} A reference to this matrix.
  3016. */
  3017. transpose() {
  3018. let tmp;
  3019. const m = this.elements;
  3020. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  3021. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  3022. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  3023. return this;
  3024. }
  3025. /**
  3026. * Computes the normal matrix which is the inverse transpose of the upper
  3027. * left 3x3 portion of the given 4x4 matrix.
  3028. *
  3029. * @param {Matrix4} matrix4 - The 4x4 matrix.
  3030. * @return {Matrix3} A reference to this matrix.
  3031. */
  3032. getNormalMatrix( matrix4 ) {
  3033. return this.setFromMatrix4( matrix4 ).invert().transpose();
  3034. }
  3035. /**
  3036. * Transposes this matrix into the supplied array, and returns itself unchanged.
  3037. *
  3038. * @param {Array<number>} r - An array to store the transposed matrix elements.
  3039. * @return {Matrix3} A reference to this matrix.
  3040. */
  3041. transposeIntoArray( r ) {
  3042. const m = this.elements;
  3043. r[ 0 ] = m[ 0 ];
  3044. r[ 1 ] = m[ 3 ];
  3045. r[ 2 ] = m[ 6 ];
  3046. r[ 3 ] = m[ 1 ];
  3047. r[ 4 ] = m[ 4 ];
  3048. r[ 5 ] = m[ 7 ];
  3049. r[ 6 ] = m[ 2 ];
  3050. r[ 7 ] = m[ 5 ];
  3051. r[ 8 ] = m[ 8 ];
  3052. return this;
  3053. }
  3054. /**
  3055. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  3056. *
  3057. * @param {number} tx - Offset x.
  3058. * @param {number} ty - Offset y.
  3059. * @param {number} sx - Repeat x.
  3060. * @param {number} sy - Repeat y.
  3061. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  3062. * @param {number} cx - Center x of rotation.
  3063. * @param {number} cy - Center y of rotation
  3064. * @return {Matrix3} A reference to this matrix.
  3065. */
  3066. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  3067. const c = Math.cos( rotation );
  3068. const s = Math.sin( rotation );
  3069. this.set(
  3070. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  3071. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  3072. 0, 0, 1
  3073. );
  3074. return this;
  3075. }
  3076. /**
  3077. * Scales this matrix with the given scalar values.
  3078. *
  3079. * @param {number} sx - The amount to scale in the X axis.
  3080. * @param {number} sy - The amount to scale in the Y axis.
  3081. * @return {Matrix3} A reference to this matrix.
  3082. */
  3083. scale( sx, sy ) {
  3084. this.premultiply( _m3.makeScale( sx, sy ) );
  3085. return this;
  3086. }
  3087. /**
  3088. * Rotates this matrix by the given angle.
  3089. *
  3090. * @param {number} theta - The rotation in radians.
  3091. * @return {Matrix3} A reference to this matrix.
  3092. */
  3093. rotate( theta ) {
  3094. this.premultiply( _m3.makeRotation( - theta ) );
  3095. return this;
  3096. }
  3097. /**
  3098. * Translates this matrix by the given scalar values.
  3099. *
  3100. * @param {number} tx - The amount to translate in the X axis.
  3101. * @param {number} ty - The amount to translate in the Y axis.
  3102. * @return {Matrix3} A reference to this matrix.
  3103. */
  3104. translate( tx, ty ) {
  3105. this.premultiply( _m3.makeTranslation( tx, ty ) );
  3106. return this;
  3107. }
  3108. // for 2D Transforms
  3109. /**
  3110. * Sets this matrix as a 2D translation transform.
  3111. *
  3112. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  3113. * @param {number} y - The amount to translate in the Y axis.
  3114. * @return {Matrix3} A reference to this matrix.
  3115. */
  3116. makeTranslation( x, y ) {
  3117. if ( x.isVector2 ) {
  3118. this.set(
  3119. 1, 0, x.x,
  3120. 0, 1, x.y,
  3121. 0, 0, 1
  3122. );
  3123. } else {
  3124. this.set(
  3125. 1, 0, x,
  3126. 0, 1, y,
  3127. 0, 0, 1
  3128. );
  3129. }
  3130. return this;
  3131. }
  3132. /**
  3133. * Sets this matrix as a 2D rotational transformation.
  3134. *
  3135. * @param {number} theta - The rotation in radians.
  3136. * @return {Matrix3} A reference to this matrix.
  3137. */
  3138. makeRotation( theta ) {
  3139. // counterclockwise
  3140. const c = Math.cos( theta );
  3141. const s = Math.sin( theta );
  3142. this.set(
  3143. c, - s, 0,
  3144. s, c, 0,
  3145. 0, 0, 1
  3146. );
  3147. return this;
  3148. }
  3149. /**
  3150. * Sets this matrix as a 2D scale transform.
  3151. *
  3152. * @param {number} x - The amount to scale in the X axis.
  3153. * @param {number} y - The amount to scale in the Y axis.
  3154. * @return {Matrix3} A reference to this matrix.
  3155. */
  3156. makeScale( x, y ) {
  3157. this.set(
  3158. x, 0, 0,
  3159. 0, y, 0,
  3160. 0, 0, 1
  3161. );
  3162. return this;
  3163. }
  3164. /**
  3165. * Returns `true` if this matrix is equal with the given one.
  3166. *
  3167. * @param {Matrix3} matrix - The matrix to test for equality.
  3168. * @return {boolean} Whether this matrix is equal with the given one.
  3169. */
  3170. equals( matrix ) {
  3171. const te = this.elements;
  3172. const me = matrix.elements;
  3173. for ( let i = 0; i < 9; i ++ ) {
  3174. if ( te[ i ] !== me[ i ] ) return false;
  3175. }
  3176. return true;
  3177. }
  3178. /**
  3179. * Sets the elements of the matrix from the given array.
  3180. *
  3181. * @param {Array<number>} array - The matrix elements in column-major order.
  3182. * @param {number} [offset=0] - Index of the first element in the array.
  3183. * @return {Matrix3} A reference to this matrix.
  3184. */
  3185. fromArray( array, offset = 0 ) {
  3186. for ( let i = 0; i < 9; i ++ ) {
  3187. this.elements[ i ] = array[ i + offset ];
  3188. }
  3189. return this;
  3190. }
  3191. /**
  3192. * Writes the elements of this matrix to the given array. If no array is provided,
  3193. * the method returns a new instance.
  3194. *
  3195. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  3196. * @param {number} [offset=0] - Index of the first element in the array.
  3197. * @return {Array<number>} The matrix elements in column-major order.
  3198. */
  3199. toArray( array = [], offset = 0 ) {
  3200. const te = this.elements;
  3201. array[ offset ] = te[ 0 ];
  3202. array[ offset + 1 ] = te[ 1 ];
  3203. array[ offset + 2 ] = te[ 2 ];
  3204. array[ offset + 3 ] = te[ 3 ];
  3205. array[ offset + 4 ] = te[ 4 ];
  3206. array[ offset + 5 ] = te[ 5 ];
  3207. array[ offset + 6 ] = te[ 6 ];
  3208. array[ offset + 7 ] = te[ 7 ];
  3209. array[ offset + 8 ] = te[ 8 ];
  3210. return array;
  3211. }
  3212. /**
  3213. * Returns a matrix with copied values from this instance.
  3214. *
  3215. * @return {Matrix3} A clone of this instance.
  3216. */
  3217. clone() {
  3218. return new this.constructor().fromArray( this.elements );
  3219. }
  3220. }
  3221. const _m3 = /*@__PURE__*/ new Matrix3();
  3222. function arrayNeedsUint32( array ) {
  3223. // assumes larger values usually on last
  3224. for ( let i = array.length - 1; i >= 0; -- i ) {
  3225. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  3226. }
  3227. return false;
  3228. }
  3229. const TYPED_ARRAYS = {
  3230. Int8Array: Int8Array,
  3231. Uint8Array: Uint8Array,
  3232. Uint8ClampedArray: Uint8ClampedArray,
  3233. Int16Array: Int16Array,
  3234. Uint16Array: Uint16Array,
  3235. Int32Array: Int32Array,
  3236. Uint32Array: Uint32Array,
  3237. Float32Array: Float32Array,
  3238. Float64Array: Float64Array
  3239. };
  3240. function getTypedArray( type, buffer ) {
  3241. return new TYPED_ARRAYS[ type ]( buffer );
  3242. }
  3243. function createElementNS( name ) {
  3244. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  3245. }
  3246. function createCanvasElement() {
  3247. const canvas = createElementNS( 'canvas' );
  3248. canvas.style.display = 'block';
  3249. return canvas;
  3250. }
  3251. const _cache = {};
  3252. function warnOnce( message ) {
  3253. if ( message in _cache ) return;
  3254. _cache[ message ] = true;
  3255. console.warn( message );
  3256. }
  3257. function probeAsync( gl, sync, interval ) {
  3258. return new Promise( function ( resolve, reject ) {
  3259. function probe() {
  3260. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  3261. case gl.WAIT_FAILED:
  3262. reject();
  3263. break;
  3264. case gl.TIMEOUT_EXPIRED:
  3265. setTimeout( probe, interval );
  3266. break;
  3267. default:
  3268. resolve();
  3269. }
  3270. }
  3271. setTimeout( probe, interval );
  3272. } );
  3273. }
  3274. function toNormalizedProjectionMatrix( projectionMatrix ) {
  3275. const m = projectionMatrix.elements;
  3276. // Convert [-1, 1] to [0, 1] projection matrix
  3277. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  3278. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  3279. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  3280. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  3281. }
  3282. function toReversedProjectionMatrix( projectionMatrix ) {
  3283. const m = projectionMatrix.elements;
  3284. const isPerspectiveMatrix = m[ 11 ] === - 1;
  3285. // Reverse [0, 1] projection matrix
  3286. if ( isPerspectiveMatrix ) {
  3287. m[ 10 ] = - m[ 10 ] - 1;
  3288. m[ 14 ] = - m[ 14 ];
  3289. } else {
  3290. m[ 10 ] = - m[ 10 ];
  3291. m[ 14 ] = - m[ 14 ] + 1;
  3292. }
  3293. }
  3294. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  3295. 0.4123908, 0.3575843, 0.1804808,
  3296. 0.2126390, 0.7151687, 0.0721923,
  3297. 0.0193308, 0.1191948, 0.9505322
  3298. );
  3299. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  3300. 3.2409699, - 1.5373832, - 0.4986108,
  3301. - 0.9692436, 1.8759675, 0.0415551,
  3302. 0.0556301, - 0.2039770, 1.0569715
  3303. );
  3304. function createColorManagement() {
  3305. const ColorManagement = {
  3306. enabled: true,
  3307. workingColorSpace: LinearSRGBColorSpace,
  3308. /**
  3309. * Implementations of supported color spaces.
  3310. *
  3311. * Required:
  3312. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  3313. * - whitePoint: reference white [ x y ]
  3314. * - transfer: transfer function (pre-defined)
  3315. * - toXYZ: Matrix3 RGB to XYZ transform
  3316. * - fromXYZ: Matrix3 XYZ to RGB transform
  3317. * - luminanceCoefficients: RGB luminance coefficients
  3318. *
  3319. * Optional:
  3320. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  3321. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  3322. *
  3323. * Reference:
  3324. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  3325. */
  3326. spaces: {},
  3327. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  3328. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  3329. return color;
  3330. }
  3331. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  3332. color.r = SRGBToLinear( color.r );
  3333. color.g = SRGBToLinear( color.g );
  3334. color.b = SRGBToLinear( color.b );
  3335. }
  3336. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  3337. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  3338. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  3339. }
  3340. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  3341. color.r = LinearToSRGB( color.r );
  3342. color.g = LinearToSRGB( color.g );
  3343. color.b = LinearToSRGB( color.b );
  3344. }
  3345. return color;
  3346. },
  3347. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  3348. return this.convert( color, this.workingColorSpace, targetColorSpace );
  3349. },
  3350. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  3351. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  3352. },
  3353. getPrimaries: function ( colorSpace ) {
  3354. return this.spaces[ colorSpace ].primaries;
  3355. },
  3356. getTransfer: function ( colorSpace ) {
  3357. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  3358. return this.spaces[ colorSpace ].transfer;
  3359. },
  3360. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  3361. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  3362. },
  3363. define: function ( colorSpaces ) {
  3364. Object.assign( this.spaces, colorSpaces );
  3365. },
  3366. // Internal APIs
  3367. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  3368. return targetMatrix
  3369. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  3370. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  3371. },
  3372. _getDrawingBufferColorSpace: function ( colorSpace ) {
  3373. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  3374. },
  3375. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  3376. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  3377. }
  3378. };
  3379. /******************************************************************************
  3380. * sRGB definitions
  3381. */
  3382. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  3383. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  3384. const D65 = [ 0.3127, 0.3290 ];
  3385. ColorManagement.define( {
  3386. [ LinearSRGBColorSpace ]: {
  3387. primaries: REC709_PRIMARIES,
  3388. whitePoint: D65,
  3389. transfer: LinearTransfer,
  3390. toXYZ: LINEAR_REC709_TO_XYZ,
  3391. fromXYZ: XYZ_TO_LINEAR_REC709,
  3392. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  3393. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  3394. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  3395. },
  3396. [ SRGBColorSpace ]: {
  3397. primaries: REC709_PRIMARIES,
  3398. whitePoint: D65,
  3399. transfer: SRGBTransfer,
  3400. toXYZ: LINEAR_REC709_TO_XYZ,
  3401. fromXYZ: XYZ_TO_LINEAR_REC709,
  3402. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  3403. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  3404. },
  3405. } );
  3406. return ColorManagement;
  3407. }
  3408. const ColorManagement = /*@__PURE__*/ createColorManagement();
  3409. function SRGBToLinear( c ) {
  3410. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  3411. }
  3412. function LinearToSRGB( c ) {
  3413. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  3414. }
  3415. let _canvas;
  3416. /**
  3417. * A class containing utility functions for images.
  3418. *
  3419. * @hideconstructor
  3420. */
  3421. class ImageUtils {
  3422. /**
  3423. * Returns a data URI containing a representation of the given image.
  3424. *
  3425. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  3426. * @param {string} [type='image/png'] - Indicates the image format.
  3427. * @return {string} The data URI.
  3428. */
  3429. static getDataURL( image, type = 'image/png' ) {
  3430. if ( /^data:/i.test( image.src ) ) {
  3431. return image.src;
  3432. }
  3433. if ( typeof HTMLCanvasElement === 'undefined' ) {
  3434. return image.src;
  3435. }
  3436. let canvas;
  3437. if ( image instanceof HTMLCanvasElement ) {
  3438. canvas = image;
  3439. } else {
  3440. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  3441. _canvas.width = image.width;
  3442. _canvas.height = image.height;
  3443. const context = _canvas.getContext( '2d' );
  3444. if ( image instanceof ImageData ) {
  3445. context.putImageData( image, 0, 0 );
  3446. } else {
  3447. context.drawImage( image, 0, 0, image.width, image.height );
  3448. }
  3449. canvas = _canvas;
  3450. }
  3451. return canvas.toDataURL( type );
  3452. }
  3453. /**
  3454. * Converts the given sRGB image data to linear color space.
  3455. *
  3456. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  3457. * @return {HTMLCanvasElement|Object} The converted image.
  3458. */
  3459. static sRGBToLinear( image ) {
  3460. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  3461. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  3462. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  3463. const canvas = createElementNS( 'canvas' );
  3464. canvas.width = image.width;
  3465. canvas.height = image.height;
  3466. const context = canvas.getContext( '2d' );
  3467. context.drawImage( image, 0, 0, image.width, image.height );
  3468. const imageData = context.getImageData( 0, 0, image.width, image.height );
  3469. const data = imageData.data;
  3470. for ( let i = 0; i < data.length; i ++ ) {
  3471. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  3472. }
  3473. context.putImageData( imageData, 0, 0 );
  3474. return canvas;
  3475. } else if ( image.data ) {
  3476. const data = image.data.slice( 0 );
  3477. for ( let i = 0; i < data.length; i ++ ) {
  3478. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  3479. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  3480. } else {
  3481. // assuming float
  3482. data[ i ] = SRGBToLinear( data[ i ] );
  3483. }
  3484. }
  3485. return {
  3486. data: data,
  3487. width: image.width,
  3488. height: image.height
  3489. };
  3490. } else {
  3491. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  3492. return image;
  3493. }
  3494. }
  3495. }
  3496. let _sourceId = 0;
  3497. /**
  3498. * Represents the data source of a texture.
  3499. *
  3500. * The main purpose of this class is to decouple the data definition from the texture
  3501. * definition so the same data can be used with multiple texture instances.
  3502. */
  3503. class Source {
  3504. /**
  3505. * Constructs a new video texture.
  3506. *
  3507. * @param {any} [data=null] - The data definition of a texture.
  3508. */
  3509. constructor( data = null ) {
  3510. /**
  3511. * This flag can be used for type testing.
  3512. *
  3513. * @type {boolean}
  3514. * @readonly
  3515. * @default true
  3516. */
  3517. this.isSource = true;
  3518. /**
  3519. * The ID of the source.
  3520. *
  3521. * @name Source#id
  3522. * @type {number}
  3523. * @readonly
  3524. */
  3525. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  3526. /**
  3527. * The UUID of the source.
  3528. *
  3529. * @type {string}
  3530. * @readonly
  3531. */
  3532. this.uuid = generateUUID();
  3533. /**
  3534. * The data definition of a texture.
  3535. *
  3536. * @type {any}
  3537. */
  3538. this.data = data;
  3539. /**
  3540. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  3541. * provides more control on how texture data should be processed. When `dataReady` is set
  3542. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  3543. * the data into the GPU memory.
  3544. *
  3545. * @type {boolean}
  3546. * @default true
  3547. */
  3548. this.dataReady = true;
  3549. /**
  3550. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  3551. *
  3552. * @type {number}
  3553. * @readonly
  3554. * @default 0
  3555. */
  3556. this.version = 0;
  3557. }
  3558. /**
  3559. * When the property is set to `true`, the engine allocates the memory
  3560. * for the texture (if necessary) and triggers the actual texture upload
  3561. * to the GPU next time the source is used.
  3562. *
  3563. * @type {boolean}
  3564. * @default false
  3565. * @param {boolean} value
  3566. */
  3567. set needsUpdate( value ) {
  3568. if ( value === true ) this.version ++;
  3569. }
  3570. /**
  3571. * Serializes the source into JSON.
  3572. *
  3573. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  3574. * @return {Object} A JSON object representing the serialized source.
  3575. * @see {@link ObjectLoader#parse}
  3576. */
  3577. toJSON( meta ) {
  3578. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  3579. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  3580. return meta.images[ this.uuid ];
  3581. }
  3582. const output = {
  3583. uuid: this.uuid,
  3584. url: ''
  3585. };
  3586. const data = this.data;
  3587. if ( data !== null ) {
  3588. let url;
  3589. if ( Array.isArray( data ) ) {
  3590. // cube texture
  3591. url = [];
  3592. for ( let i = 0, l = data.length; i < l; i ++ ) {
  3593. if ( data[ i ].isDataTexture ) {
  3594. url.push( serializeImage( data[ i ].image ) );
  3595. } else {
  3596. url.push( serializeImage( data[ i ] ) );
  3597. }
  3598. }
  3599. } else {
  3600. // texture
  3601. url = serializeImage( data );
  3602. }
  3603. output.url = url;
  3604. }
  3605. if ( ! isRootObject ) {
  3606. meta.images[ this.uuid ] = output;
  3607. }
  3608. return output;
  3609. }
  3610. }
  3611. function serializeImage( image ) {
  3612. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  3613. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  3614. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  3615. // default images
  3616. return ImageUtils.getDataURL( image );
  3617. } else {
  3618. if ( image.data ) {
  3619. // images of DataTexture
  3620. return {
  3621. data: Array.from( image.data ),
  3622. width: image.width,
  3623. height: image.height,
  3624. type: image.data.constructor.name
  3625. };
  3626. } else {
  3627. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  3628. return {};
  3629. }
  3630. }
  3631. }
  3632. let _textureId = 0;
  3633. /**
  3634. * Base class for all textures.
  3635. *
  3636. * Note: After the initial use of a texture, its dimensions, format, and type
  3637. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  3638. *
  3639. * @augments EventDispatcher
  3640. */
  3641. class Texture extends EventDispatcher {
  3642. /**
  3643. * Constructs a new texture.
  3644. *
  3645. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  3646. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  3647. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  3648. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  3649. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  3650. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  3651. * @param {number} [format=RGBAFormat] - The texture format.
  3652. * @param {number} [type=UnsignedByteType] - The texture type.
  3653. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  3654. * @param {string} [colorSpace=NoColorSpace] - The color space.
  3655. */
  3656. 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 ) {
  3657. super();
  3658. /**
  3659. * This flag can be used for type testing.
  3660. *
  3661. * @type {boolean}
  3662. * @readonly
  3663. * @default true
  3664. */
  3665. this.isTexture = true;
  3666. /**
  3667. * The ID of the texture.
  3668. *
  3669. * @name Texture#id
  3670. * @type {number}
  3671. * @readonly
  3672. */
  3673. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  3674. /**
  3675. * The UUID of the material.
  3676. *
  3677. * @type {string}
  3678. * @readonly
  3679. */
  3680. this.uuid = generateUUID();
  3681. /**
  3682. * The name of the material.
  3683. *
  3684. * @type {string}
  3685. */
  3686. this.name = '';
  3687. /**
  3688. * The data definition of a texture. A reference to the data source can be
  3689. * shared across textures. This is often useful in context of spritesheets
  3690. * where multiple textures render the same data but with different texture
  3691. * transformations.
  3692. *
  3693. * @type {Source}
  3694. */
  3695. this.source = new Source( image );
  3696. /**
  3697. * An array holding user-defined mipmaps.
  3698. *
  3699. * @type {Array<Object>}
  3700. */
  3701. this.mipmaps = [];
  3702. /**
  3703. * How the texture is applied to the object. The value `UVMapping`
  3704. * is the default, where texture or uv coordinates are used to apply the map.
  3705. *
  3706. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  3707. * @default UVMapping
  3708. */
  3709. this.mapping = mapping;
  3710. /**
  3711. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  3712. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  3713. *
  3714. * @type {number}
  3715. * @default 0
  3716. */
  3717. this.channel = 0;
  3718. /**
  3719. * This defines how the texture is wrapped horizontally and corresponds to
  3720. * *U* in UV mapping.
  3721. *
  3722. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  3723. * @default ClampToEdgeWrapping
  3724. */
  3725. this.wrapS = wrapS;
  3726. /**
  3727. * This defines how the texture is wrapped horizontally and corresponds to
  3728. * *V* in UV mapping.
  3729. *
  3730. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  3731. * @default ClampToEdgeWrapping
  3732. */
  3733. this.wrapT = wrapT;
  3734. /**
  3735. * How the texture is sampled when a texel covers more than one pixel.
  3736. *
  3737. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  3738. * @default LinearFilter
  3739. */
  3740. this.magFilter = magFilter;
  3741. /**
  3742. * How the texture is sampled when a texel covers less than one pixel.
  3743. *
  3744. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  3745. * @default LinearMipmapLinearFilter
  3746. */
  3747. this.minFilter = minFilter;
  3748. /**
  3749. * The number of samples taken along the axis through the pixel that has the
  3750. * highest density of texels. By default, this value is `1`. A higher value
  3751. * gives a less blurry result than a basic mipmap, at the cost of more
  3752. * texture samples being used.
  3753. *
  3754. * @type {number}
  3755. * @default 0
  3756. */
  3757. this.anisotropy = anisotropy;
  3758. /**
  3759. * The format of the texture.
  3760. *
  3761. * @type {number}
  3762. * @default RGBAFormat
  3763. */
  3764. this.format = format;
  3765. /**
  3766. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  3767. * defines how the texture data is going to be stored on the GPU.
  3768. *
  3769. * This property allows to overwrite the default format.
  3770. *
  3771. * @type {?string}
  3772. * @default null
  3773. */
  3774. this.internalFormat = null;
  3775. /**
  3776. * The data type of the texture.
  3777. *
  3778. * @type {number}
  3779. * @default UnsignedByteType
  3780. */
  3781. this.type = type;
  3782. /**
  3783. * How much a single repetition of the texture is offset from the beginning,
  3784. * in each direction U and V. Typical range is `0.0` to `1.0`.
  3785. *
  3786. * @type {Vector2}
  3787. * @default (0,0)
  3788. */
  3789. this.offset = new Vector2( 0, 0 );
  3790. /**
  3791. * How many times the texture is repeated across the surface, in each
  3792. * direction U and V. If repeat is set greater than `1` in either direction,
  3793. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  3794. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  3795. *
  3796. * @type {Vector2}
  3797. * @default (1,1)
  3798. */
  3799. this.repeat = new Vector2( 1, 1 );
  3800. /**
  3801. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  3802. * to the center of the texture. Default is `(0, 0)`, the lower left.
  3803. *
  3804. * @type {Vector2}
  3805. * @default (0,0)
  3806. */
  3807. this.center = new Vector2( 0, 0 );
  3808. /**
  3809. * How much the texture is rotated around the center point, in radians.
  3810. * Positive values are counter-clockwise.
  3811. *
  3812. * @type {number}
  3813. * @default 0
  3814. */
  3815. this.rotation = 0;
  3816. /**
  3817. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  3818. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  3819. * {@link Texture#rotation}, and {@link Texture#center}.
  3820. *
  3821. * Set this to `false` if you are specifying the uv-transform matrix directly.
  3822. *
  3823. * @type {boolean}
  3824. * @default true
  3825. */
  3826. this.matrixAutoUpdate = true;
  3827. /**
  3828. * The uv-transformation matrix of the texture.
  3829. *
  3830. * @type {Matrix3}
  3831. */
  3832. this.matrix = new Matrix3();
  3833. /**
  3834. * Whether to generate mipmaps (if possible) for a texture.
  3835. *
  3836. * Set this to `false` if you are creating mipmaps manually.
  3837. *
  3838. * @type {boolean}
  3839. * @default true
  3840. */
  3841. this.generateMipmaps = true;
  3842. /**
  3843. * If set to `true`, the alpha channel, if present, is multiplied into the
  3844. * color channels when the texture is uploaded to the GPU.
  3845. *
  3846. * Note that this property has no effect when using `ImageBitmap`. You need to
  3847. * configure premultiply alpha on bitmap creation instead.
  3848. *
  3849. * @type {boolean}
  3850. * @default false
  3851. */
  3852. this.premultiplyAlpha = false;
  3853. /**
  3854. * If set to `true`, the texture is flipped along the vertical axis when
  3855. * uploaded to the GPU.
  3856. *
  3857. * Note that this property has no effect when using `ImageBitmap`. You need to
  3858. * configure the flip on bitmap creation instead.
  3859. *
  3860. * @type {boolean}
  3861. * @default true
  3862. */
  3863. this.flipY = true;
  3864. /**
  3865. * Specifies the alignment requirements for the start of each pixel row in memory.
  3866. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  3867. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  3868. *
  3869. * @type {number}
  3870. * @default 4
  3871. */
  3872. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  3873. /**
  3874. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  3875. *
  3876. * @type {string}
  3877. * @default NoColorSpace
  3878. */
  3879. this.colorSpace = colorSpace;
  3880. /**
  3881. * An object that can be used to store custom data about the texture. It
  3882. * should not hold references to functions as these will not be cloned.
  3883. *
  3884. * @type {Object}
  3885. */
  3886. this.userData = {};
  3887. /**
  3888. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  3889. *
  3890. * @type {number}
  3891. * @readonly
  3892. * @default 0
  3893. */
  3894. this.version = 0;
  3895. /**
  3896. * A callback function, called when the texture is updated (e.g., when
  3897. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  3898. *
  3899. * @type {?Function}
  3900. * @default null
  3901. */
  3902. this.onUpdate = null;
  3903. /**
  3904. * An optional back reference to the textures render target.
  3905. *
  3906. * @type {?(RenderTarget|WebGLRenderTarget)}
  3907. * @default null
  3908. */
  3909. this.renderTarget = null;
  3910. /**
  3911. * Indicates whether a texture belongs to a render target or not.
  3912. *
  3913. * @type {boolean}
  3914. * @readonly
  3915. * @default false
  3916. */
  3917. this.isRenderTargetTexture = false;
  3918. /**
  3919. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  3920. * (only relevant for render target textures).
  3921. *
  3922. * @type {number}
  3923. * @readonly
  3924. * @default 0
  3925. */
  3926. this.pmremVersion = 0;
  3927. }
  3928. /**
  3929. * The image object holding the texture data.
  3930. *
  3931. * @type {?Object}
  3932. */
  3933. get image() {
  3934. return this.source.data;
  3935. }
  3936. set image( value = null ) {
  3937. this.source.data = value;
  3938. }
  3939. /**
  3940. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  3941. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  3942. */
  3943. updateMatrix() {
  3944. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  3945. }
  3946. /**
  3947. * Returns a new texture with copied values from this instance.
  3948. *
  3949. * @return {Texture} A clone of this instance.
  3950. */
  3951. clone() {
  3952. return new this.constructor().copy( this );
  3953. }
  3954. /**
  3955. * Copies the values of the given texture to this instance.
  3956. *
  3957. * @param {Texture} source - The texture to copy.
  3958. * @return {Texture} A reference to this instance.
  3959. */
  3960. copy( source ) {
  3961. this.name = source.name;
  3962. this.source = source.source;
  3963. this.mipmaps = source.mipmaps.slice( 0 );
  3964. this.mapping = source.mapping;
  3965. this.channel = source.channel;
  3966. this.wrapS = source.wrapS;
  3967. this.wrapT = source.wrapT;
  3968. this.magFilter = source.magFilter;
  3969. this.minFilter = source.minFilter;
  3970. this.anisotropy = source.anisotropy;
  3971. this.format = source.format;
  3972. this.internalFormat = source.internalFormat;
  3973. this.type = source.type;
  3974. this.offset.copy( source.offset );
  3975. this.repeat.copy( source.repeat );
  3976. this.center.copy( source.center );
  3977. this.rotation = source.rotation;
  3978. this.matrixAutoUpdate = source.matrixAutoUpdate;
  3979. this.matrix.copy( source.matrix );
  3980. this.generateMipmaps = source.generateMipmaps;
  3981. this.premultiplyAlpha = source.premultiplyAlpha;
  3982. this.flipY = source.flipY;
  3983. this.unpackAlignment = source.unpackAlignment;
  3984. this.colorSpace = source.colorSpace;
  3985. this.renderTarget = source.renderTarget;
  3986. this.isRenderTargetTexture = source.isRenderTargetTexture;
  3987. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  3988. this.needsUpdate = true;
  3989. return this;
  3990. }
  3991. /**
  3992. * Serializes the texture into JSON.
  3993. *
  3994. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  3995. * @return {Object} A JSON object representing the serialized texture.
  3996. * @see {@link ObjectLoader#parse}
  3997. */
  3998. toJSON( meta ) {
  3999. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4000. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  4001. return meta.textures[ this.uuid ];
  4002. }
  4003. const output = {
  4004. metadata: {
  4005. version: 4.6,
  4006. type: 'Texture',
  4007. generator: 'Texture.toJSON'
  4008. },
  4009. uuid: this.uuid,
  4010. name: this.name,
  4011. image: this.source.toJSON( meta ).uuid,
  4012. mapping: this.mapping,
  4013. channel: this.channel,
  4014. repeat: [ this.repeat.x, this.repeat.y ],
  4015. offset: [ this.offset.x, this.offset.y ],
  4016. center: [ this.center.x, this.center.y ],
  4017. rotation: this.rotation,
  4018. wrap: [ this.wrapS, this.wrapT ],
  4019. format: this.format,
  4020. internalFormat: this.internalFormat,
  4021. type: this.type,
  4022. colorSpace: this.colorSpace,
  4023. minFilter: this.minFilter,
  4024. magFilter: this.magFilter,
  4025. anisotropy: this.anisotropy,
  4026. flipY: this.flipY,
  4027. generateMipmaps: this.generateMipmaps,
  4028. premultiplyAlpha: this.premultiplyAlpha,
  4029. unpackAlignment: this.unpackAlignment
  4030. };
  4031. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  4032. if ( ! isRootObject ) {
  4033. meta.textures[ this.uuid ] = output;
  4034. }
  4035. return output;
  4036. }
  4037. /**
  4038. * Frees the GPU-related resources allocated by this instance. Call this
  4039. * method whenever this instance is no longer used in your app.
  4040. *
  4041. * @fires Texture#dispose
  4042. */
  4043. dispose() {
  4044. /**
  4045. * Fires when the texture has been disposed of.
  4046. *
  4047. * @event Texture#dispose
  4048. * @type {Object}
  4049. */
  4050. this.dispatchEvent( { type: 'dispose' } );
  4051. }
  4052. /**
  4053. * Transforms the given uv vector with the textures uv transformation matrix.
  4054. *
  4055. * @param {Vector2} uv - The uv vector.
  4056. * @return {Vector2} The transformed uv vector.
  4057. */
  4058. transformUv( uv ) {
  4059. if ( this.mapping !== UVMapping ) return uv;
  4060. uv.applyMatrix3( this.matrix );
  4061. if ( uv.x < 0 || uv.x > 1 ) {
  4062. switch ( this.wrapS ) {
  4063. case RepeatWrapping:
  4064. uv.x = uv.x - Math.floor( uv.x );
  4065. break;
  4066. case ClampToEdgeWrapping:
  4067. uv.x = uv.x < 0 ? 0 : 1;
  4068. break;
  4069. case MirroredRepeatWrapping:
  4070. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  4071. uv.x = Math.ceil( uv.x ) - uv.x;
  4072. } else {
  4073. uv.x = uv.x - Math.floor( uv.x );
  4074. }
  4075. break;
  4076. }
  4077. }
  4078. if ( uv.y < 0 || uv.y > 1 ) {
  4079. switch ( this.wrapT ) {
  4080. case RepeatWrapping:
  4081. uv.y = uv.y - Math.floor( uv.y );
  4082. break;
  4083. case ClampToEdgeWrapping:
  4084. uv.y = uv.y < 0 ? 0 : 1;
  4085. break;
  4086. case MirroredRepeatWrapping:
  4087. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  4088. uv.y = Math.ceil( uv.y ) - uv.y;
  4089. } else {
  4090. uv.y = uv.y - Math.floor( uv.y );
  4091. }
  4092. break;
  4093. }
  4094. }
  4095. if ( this.flipY ) {
  4096. uv.y = 1 - uv.y;
  4097. }
  4098. return uv;
  4099. }
  4100. /**
  4101. * Setting this property to `true` indicates the engine the texture
  4102. * must be updated in the next render. This triggers a texture upload
  4103. * to the GPU and ensures correct texture parameter configuration.
  4104. *
  4105. * @type {boolean}
  4106. * @default false
  4107. * @param {boolean} value
  4108. */
  4109. set needsUpdate( value ) {
  4110. if ( value === true ) {
  4111. this.version ++;
  4112. this.source.needsUpdate = true;
  4113. }
  4114. }
  4115. /**
  4116. * Setting this property to `true` indicates the engine the PMREM
  4117. * must be regenerated.
  4118. *
  4119. * @type {boolean}
  4120. * @default false
  4121. * @param {boolean} value
  4122. */
  4123. set needsPMREMUpdate( value ) {
  4124. if ( value === true ) {
  4125. this.pmremVersion ++;
  4126. }
  4127. }
  4128. }
  4129. /**
  4130. * The default image for all textures.
  4131. *
  4132. * @static
  4133. * @type {?Image}
  4134. * @default null
  4135. */
  4136. Texture.DEFAULT_IMAGE = null;
  4137. /**
  4138. * The default mapping for all textures.
  4139. *
  4140. * @static
  4141. * @type {number}
  4142. * @default UVMapping
  4143. */
  4144. Texture.DEFAULT_MAPPING = UVMapping;
  4145. /**
  4146. * The default anisotropy value for all textures.
  4147. *
  4148. * @static
  4149. * @type {number}
  4150. * @default 1
  4151. */
  4152. Texture.DEFAULT_ANISOTROPY = 1;
  4153. /**
  4154. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  4155. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  4156. *
  4157. * - A point in 4D space.
  4158. * - A direction and length in 4D space. In three.js the length will
  4159. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  4160. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  4161. * - Any arbitrary ordered quadruplet of numbers.
  4162. *
  4163. * There are other things a 4D vector can be used to represent, however these
  4164. * are the most common uses in *three.js*.
  4165. *
  4166. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  4167. * the corresponding order.
  4168. * ```js
  4169. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  4170. *
  4171. * //no arguments; will be initialised to (0, 0, 0, 1)
  4172. * const b = new THREE.Vector4( );
  4173. *
  4174. * const d = a.dot( b );
  4175. * ```
  4176. */
  4177. class Vector4 {
  4178. /**
  4179. * Constructs a new 4D vector.
  4180. *
  4181. * @param {number} [x=0] - The x value of this vector.
  4182. * @param {number} [y=0] - The y value of this vector.
  4183. * @param {number} [z=0] - The z value of this vector.
  4184. * @param {number} [w=1] - The w value of this vector.
  4185. */
  4186. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  4187. /**
  4188. * This flag can be used for type testing.
  4189. *
  4190. * @type {boolean}
  4191. * @readonly
  4192. * @default true
  4193. */
  4194. Vector4.prototype.isVector4 = true;
  4195. /**
  4196. * The x value of this vector.
  4197. *
  4198. * @type {number}
  4199. */
  4200. this.x = x;
  4201. /**
  4202. * The y value of this vector.
  4203. *
  4204. * @type {number}
  4205. */
  4206. this.y = y;
  4207. /**
  4208. * The z value of this vector.
  4209. *
  4210. * @type {number}
  4211. */
  4212. this.z = z;
  4213. /**
  4214. * The w value of this vector.
  4215. *
  4216. * @type {number}
  4217. */
  4218. this.w = w;
  4219. }
  4220. /**
  4221. * Alias for {@link Vector4#z}.
  4222. *
  4223. * @type {number}
  4224. */
  4225. get width() {
  4226. return this.z;
  4227. }
  4228. set width( value ) {
  4229. this.z = value;
  4230. }
  4231. /**
  4232. * Alias for {@link Vector4#w}.
  4233. *
  4234. * @type {number}
  4235. */
  4236. get height() {
  4237. return this.w;
  4238. }
  4239. set height( value ) {
  4240. this.w = value;
  4241. }
  4242. /**
  4243. * Sets the vector components.
  4244. *
  4245. * @param {number} x - The value of the x component.
  4246. * @param {number} y - The value of the y component.
  4247. * @param {number} z - The value of the z component.
  4248. * @param {number} w - The value of the w component.
  4249. * @return {Vector4} A reference to this vector.
  4250. */
  4251. set( x, y, z, w ) {
  4252. this.x = x;
  4253. this.y = y;
  4254. this.z = z;
  4255. this.w = w;
  4256. return this;
  4257. }
  4258. /**
  4259. * Sets the vector components to the same value.
  4260. *
  4261. * @param {number} scalar - The value to set for all vector components.
  4262. * @return {Vector4} A reference to this vector.
  4263. */
  4264. setScalar( scalar ) {
  4265. this.x = scalar;
  4266. this.y = scalar;
  4267. this.z = scalar;
  4268. this.w = scalar;
  4269. return this;
  4270. }
  4271. /**
  4272. * Sets the vector's x component to the given value
  4273. *
  4274. * @param {number} x - The value to set.
  4275. * @return {Vector4} A reference to this vector.
  4276. */
  4277. setX( x ) {
  4278. this.x = x;
  4279. return this;
  4280. }
  4281. /**
  4282. * Sets the vector's y component to the given value
  4283. *
  4284. * @param {number} y - The value to set.
  4285. * @return {Vector4} A reference to this vector.
  4286. */
  4287. setY( y ) {
  4288. this.y = y;
  4289. return this;
  4290. }
  4291. /**
  4292. * Sets the vector's z component to the given value
  4293. *
  4294. * @param {number} z - The value to set.
  4295. * @return {Vector4} A reference to this vector.
  4296. */
  4297. setZ( z ) {
  4298. this.z = z;
  4299. return this;
  4300. }
  4301. /**
  4302. * Sets the vector's w component to the given value
  4303. *
  4304. * @param {number} w - The value to set.
  4305. * @return {Vector4} A reference to this vector.
  4306. */
  4307. setW( w ) {
  4308. this.w = w;
  4309. return this;
  4310. }
  4311. /**
  4312. * Allows to set a vector component with an index.
  4313. *
  4314. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  4315. * `2` equals to z, `3` equals to w.
  4316. * @param {number} value - The value to set.
  4317. * @return {Vector4} A reference to this vector.
  4318. */
  4319. setComponent( index, value ) {
  4320. switch ( index ) {
  4321. case 0: this.x = value; break;
  4322. case 1: this.y = value; break;
  4323. case 2: this.z = value; break;
  4324. case 3: this.w = value; break;
  4325. default: throw new Error( 'index is out of range: ' + index );
  4326. }
  4327. return this;
  4328. }
  4329. /**
  4330. * Returns the value of the vector component which matches the given index.
  4331. *
  4332. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  4333. * `2` equals to z, `3` equals to w.
  4334. * @return {number} A vector component value.
  4335. */
  4336. getComponent( index ) {
  4337. switch ( index ) {
  4338. case 0: return this.x;
  4339. case 1: return this.y;
  4340. case 2: return this.z;
  4341. case 3: return this.w;
  4342. default: throw new Error( 'index is out of range: ' + index );
  4343. }
  4344. }
  4345. /**
  4346. * Returns a new vector with copied values from this instance.
  4347. *
  4348. * @return {Vector4} A clone of this instance.
  4349. */
  4350. clone() {
  4351. return new this.constructor( this.x, this.y, this.z, this.w );
  4352. }
  4353. /**
  4354. * Copies the values of the given vector to this instance.
  4355. *
  4356. * @param {Vector3|Vector4} v - The vector to copy.
  4357. * @return {Vector4} A reference to this vector.
  4358. */
  4359. copy( v ) {
  4360. this.x = v.x;
  4361. this.y = v.y;
  4362. this.z = v.z;
  4363. this.w = ( v.w !== undefined ) ? v.w : 1;
  4364. return this;
  4365. }
  4366. /**
  4367. * Adds the given vector to this instance.
  4368. *
  4369. * @param {Vector4} v - The vector to add.
  4370. * @return {Vector4} A reference to this vector.
  4371. */
  4372. add( v ) {
  4373. this.x += v.x;
  4374. this.y += v.y;
  4375. this.z += v.z;
  4376. this.w += v.w;
  4377. return this;
  4378. }
  4379. /**
  4380. * Adds the given scalar value to all components of this instance.
  4381. *
  4382. * @param {number} s - The scalar to add.
  4383. * @return {Vector4} A reference to this vector.
  4384. */
  4385. addScalar( s ) {
  4386. this.x += s;
  4387. this.y += s;
  4388. this.z += s;
  4389. this.w += s;
  4390. return this;
  4391. }
  4392. /**
  4393. * Adds the given vectors and stores the result in this instance.
  4394. *
  4395. * @param {Vector4} a - The first vector.
  4396. * @param {Vector4} b - The second vector.
  4397. * @return {Vector4} A reference to this vector.
  4398. */
  4399. addVectors( a, b ) {
  4400. this.x = a.x + b.x;
  4401. this.y = a.y + b.y;
  4402. this.z = a.z + b.z;
  4403. this.w = a.w + b.w;
  4404. return this;
  4405. }
  4406. /**
  4407. * Adds the given vector scaled by the given factor to this instance.
  4408. *
  4409. * @param {Vector4} v - The vector.
  4410. * @param {number} s - The factor that scales `v`.
  4411. * @return {Vector4} A reference to this vector.
  4412. */
  4413. addScaledVector( v, s ) {
  4414. this.x += v.x * s;
  4415. this.y += v.y * s;
  4416. this.z += v.z * s;
  4417. this.w += v.w * s;
  4418. return this;
  4419. }
  4420. /**
  4421. * Subtracts the given vector from this instance.
  4422. *
  4423. * @param {Vector4} v - The vector to subtract.
  4424. * @return {Vector4} A reference to this vector.
  4425. */
  4426. sub( v ) {
  4427. this.x -= v.x;
  4428. this.y -= v.y;
  4429. this.z -= v.z;
  4430. this.w -= v.w;
  4431. return this;
  4432. }
  4433. /**
  4434. * Subtracts the given scalar value from all components of this instance.
  4435. *
  4436. * @param {number} s - The scalar to subtract.
  4437. * @return {Vector4} A reference to this vector.
  4438. */
  4439. subScalar( s ) {
  4440. this.x -= s;
  4441. this.y -= s;
  4442. this.z -= s;
  4443. this.w -= s;
  4444. return this;
  4445. }
  4446. /**
  4447. * Subtracts the given vectors and stores the result in this instance.
  4448. *
  4449. * @param {Vector4} a - The first vector.
  4450. * @param {Vector4} b - The second vector.
  4451. * @return {Vector4} A reference to this vector.
  4452. */
  4453. subVectors( a, b ) {
  4454. this.x = a.x - b.x;
  4455. this.y = a.y - b.y;
  4456. this.z = a.z - b.z;
  4457. this.w = a.w - b.w;
  4458. return this;
  4459. }
  4460. /**
  4461. * Multiplies the given vector with this instance.
  4462. *
  4463. * @param {Vector4} v - The vector to multiply.
  4464. * @return {Vector4} A reference to this vector.
  4465. */
  4466. multiply( v ) {
  4467. this.x *= v.x;
  4468. this.y *= v.y;
  4469. this.z *= v.z;
  4470. this.w *= v.w;
  4471. return this;
  4472. }
  4473. /**
  4474. * Multiplies the given scalar value with all components of this instance.
  4475. *
  4476. * @param {number} scalar - The scalar to multiply.
  4477. * @return {Vector4} A reference to this vector.
  4478. */
  4479. multiplyScalar( scalar ) {
  4480. this.x *= scalar;
  4481. this.y *= scalar;
  4482. this.z *= scalar;
  4483. this.w *= scalar;
  4484. return this;
  4485. }
  4486. /**
  4487. * Multiplies this vector with the given 4x4 matrix.
  4488. *
  4489. * @param {Matrix4} m - The 4x4 matrix.
  4490. * @return {Vector4} A reference to this vector.
  4491. */
  4492. applyMatrix4( m ) {
  4493. const x = this.x, y = this.y, z = this.z, w = this.w;
  4494. const e = m.elements;
  4495. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  4496. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  4497. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  4498. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  4499. return this;
  4500. }
  4501. /**
  4502. * Divides this instance by the given vector.
  4503. *
  4504. * @param {Vector4} v - The vector to divide.
  4505. * @return {Vector4} A reference to this vector.
  4506. */
  4507. divide( v ) {
  4508. this.x /= v.x;
  4509. this.y /= v.y;
  4510. this.z /= v.z;
  4511. this.w /= v.w;
  4512. return this;
  4513. }
  4514. /**
  4515. * Divides this vector by the given scalar.
  4516. *
  4517. * @param {number} scalar - The scalar to divide.
  4518. * @return {Vector4} A reference to this vector.
  4519. */
  4520. divideScalar( scalar ) {
  4521. return this.multiplyScalar( 1 / scalar );
  4522. }
  4523. /**
  4524. * Sets the x, y and z components of this
  4525. * vector to the quaternion's axis and w to the angle.
  4526. *
  4527. * @param {Quaternion} q - The Quaternion to set.
  4528. * @return {Vector4} A reference to this vector.
  4529. */
  4530. setAxisAngleFromQuaternion( q ) {
  4531. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  4532. // q is assumed to be normalized
  4533. this.w = 2 * Math.acos( q.w );
  4534. const s = Math.sqrt( 1 - q.w * q.w );
  4535. if ( s < 0.0001 ) {
  4536. this.x = 1;
  4537. this.y = 0;
  4538. this.z = 0;
  4539. } else {
  4540. this.x = q.x / s;
  4541. this.y = q.y / s;
  4542. this.z = q.z / s;
  4543. }
  4544. return this;
  4545. }
  4546. /**
  4547. * Sets the x, y and z components of this
  4548. * vector to the axis of rotation and w to the angle.
  4549. *
  4550. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  4551. * @return {Vector4} A reference to this vector.
  4552. */
  4553. setAxisAngleFromRotationMatrix( m ) {
  4554. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  4555. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4556. let angle, x, y, z; // variables for result
  4557. const epsilon = 0.01, // margin to allow for rounding errors
  4558. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  4559. te = m.elements,
  4560. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  4561. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  4562. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4563. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  4564. ( Math.abs( m13 - m31 ) < epsilon ) &&
  4565. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  4566. // singularity found
  4567. // first check for identity matrix which must have +1 for all terms
  4568. // in leading diagonal and zero in other terms
  4569. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  4570. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  4571. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  4572. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  4573. // this singularity is identity matrix so angle = 0
  4574. this.set( 1, 0, 0, 0 );
  4575. return this; // zero angle, arbitrary axis
  4576. }
  4577. // otherwise this singularity is angle = 180
  4578. angle = Math.PI;
  4579. const xx = ( m11 + 1 ) / 2;
  4580. const yy = ( m22 + 1 ) / 2;
  4581. const zz = ( m33 + 1 ) / 2;
  4582. const xy = ( m12 + m21 ) / 4;
  4583. const xz = ( m13 + m31 ) / 4;
  4584. const yz = ( m23 + m32 ) / 4;
  4585. if ( ( xx > yy ) && ( xx > zz ) ) {
  4586. // m11 is the largest diagonal term
  4587. if ( xx < epsilon ) {
  4588. x = 0;
  4589. y = 0.707106781;
  4590. z = 0.707106781;
  4591. } else {
  4592. x = Math.sqrt( xx );
  4593. y = xy / x;
  4594. z = xz / x;
  4595. }
  4596. } else if ( yy > zz ) {
  4597. // m22 is the largest diagonal term
  4598. if ( yy < epsilon ) {
  4599. x = 0.707106781;
  4600. y = 0;
  4601. z = 0.707106781;
  4602. } else {
  4603. y = Math.sqrt( yy );
  4604. x = xy / y;
  4605. z = yz / y;
  4606. }
  4607. } else {
  4608. // m33 is the largest diagonal term so base result on this
  4609. if ( zz < epsilon ) {
  4610. x = 0.707106781;
  4611. y = 0.707106781;
  4612. z = 0;
  4613. } else {
  4614. z = Math.sqrt( zz );
  4615. x = xz / z;
  4616. y = yz / z;
  4617. }
  4618. }
  4619. this.set( x, y, z, angle );
  4620. return this; // return 180 deg rotation
  4621. }
  4622. // as we have reached here there are no singularities so we can handle normally
  4623. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  4624. ( m13 - m31 ) * ( m13 - m31 ) +
  4625. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  4626. if ( Math.abs( s ) < 0.001 ) s = 1;
  4627. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  4628. // caught by singularity test above, but I've left it in just in case
  4629. this.x = ( m32 - m23 ) / s;
  4630. this.y = ( m13 - m31 ) / s;
  4631. this.z = ( m21 - m12 ) / s;
  4632. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  4633. return this;
  4634. }
  4635. /**
  4636. * Sets the vector components to the position elements of the
  4637. * given transformation matrix.
  4638. *
  4639. * @param {Matrix4} m - The 4x4 matrix.
  4640. * @return {Vector4} A reference to this vector.
  4641. */
  4642. setFromMatrixPosition( m ) {
  4643. const e = m.elements;
  4644. this.x = e[ 12 ];
  4645. this.y = e[ 13 ];
  4646. this.z = e[ 14 ];
  4647. this.w = e[ 15 ];
  4648. return this;
  4649. }
  4650. /**
  4651. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  4652. * value, replace that value with the corresponding min value.
  4653. *
  4654. * @param {Vector4} v - The vector.
  4655. * @return {Vector4} A reference to this vector.
  4656. */
  4657. min( v ) {
  4658. this.x = Math.min( this.x, v.x );
  4659. this.y = Math.min( this.y, v.y );
  4660. this.z = Math.min( this.z, v.z );
  4661. this.w = Math.min( this.w, v.w );
  4662. return this;
  4663. }
  4664. /**
  4665. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  4666. * value, replace that value with the corresponding max value.
  4667. *
  4668. * @param {Vector4} v - The vector.
  4669. * @return {Vector4} A reference to this vector.
  4670. */
  4671. max( v ) {
  4672. this.x = Math.max( this.x, v.x );
  4673. this.y = Math.max( this.y, v.y );
  4674. this.z = Math.max( this.z, v.z );
  4675. this.w = Math.max( this.w, v.w );
  4676. return this;
  4677. }
  4678. /**
  4679. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  4680. * value, it is replaced by the corresponding value.
  4681. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  4682. * it is replaced by the corresponding value.
  4683. *
  4684. * @param {Vector4} min - The minimum x, y and z values.
  4685. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  4686. * @return {Vector4} A reference to this vector.
  4687. */
  4688. clamp( min, max ) {
  4689. // assumes min < max, componentwise
  4690. this.x = clamp( this.x, min.x, max.x );
  4691. this.y = clamp( this.y, min.y, max.y );
  4692. this.z = clamp( this.z, min.z, max.z );
  4693. this.w = clamp( this.w, min.w, max.w );
  4694. return this;
  4695. }
  4696. /**
  4697. * If this vector's x, y, z or w values are greater than the max value, they are
  4698. * replaced by the max value.
  4699. * If this vector's x, y, z or w values are less than the min value, they are
  4700. * replaced by the min value.
  4701. *
  4702. * @param {number} minVal - The minimum value the components will be clamped to.
  4703. * @param {number} maxVal - The maximum value the components will be clamped to.
  4704. * @return {Vector4} A reference to this vector.
  4705. */
  4706. clampScalar( minVal, maxVal ) {
  4707. this.x = clamp( this.x, minVal, maxVal );
  4708. this.y = clamp( this.y, minVal, maxVal );
  4709. this.z = clamp( this.z, minVal, maxVal );
  4710. this.w = clamp( this.w, minVal, maxVal );
  4711. return this;
  4712. }
  4713. /**
  4714. * If this vector's length is greater than the max value, it is replaced by
  4715. * the max value.
  4716. * If this vector's length is less than the min value, it is replaced by the
  4717. * min value.
  4718. *
  4719. * @param {number} min - The minimum value the vector length will be clamped to.
  4720. * @param {number} max - The maximum value the vector length will be clamped to.
  4721. * @return {Vector4} A reference to this vector.
  4722. */
  4723. clampLength( min, max ) {
  4724. const length = this.length();
  4725. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4726. }
  4727. /**
  4728. * The components of this vector are rounded down to the nearest integer value.
  4729. *
  4730. * @return {Vector4} A reference to this vector.
  4731. */
  4732. floor() {
  4733. this.x = Math.floor( this.x );
  4734. this.y = Math.floor( this.y );
  4735. this.z = Math.floor( this.z );
  4736. this.w = Math.floor( this.w );
  4737. return this;
  4738. }
  4739. /**
  4740. * The components of this vector are rounded up to the nearest integer value.
  4741. *
  4742. * @return {Vector4} A reference to this vector.
  4743. */
  4744. ceil() {
  4745. this.x = Math.ceil( this.x );
  4746. this.y = Math.ceil( this.y );
  4747. this.z = Math.ceil( this.z );
  4748. this.w = Math.ceil( this.w );
  4749. return this;
  4750. }
  4751. /**
  4752. * The components of this vector are rounded to the nearest integer value
  4753. *
  4754. * @return {Vector4} A reference to this vector.
  4755. */
  4756. round() {
  4757. this.x = Math.round( this.x );
  4758. this.y = Math.round( this.y );
  4759. this.z = Math.round( this.z );
  4760. this.w = Math.round( this.w );
  4761. return this;
  4762. }
  4763. /**
  4764. * The components of this vector are rounded towards zero (up if negative,
  4765. * down if positive) to an integer value.
  4766. *
  4767. * @return {Vector4} A reference to this vector.
  4768. */
  4769. roundToZero() {
  4770. this.x = Math.trunc( this.x );
  4771. this.y = Math.trunc( this.y );
  4772. this.z = Math.trunc( this.z );
  4773. this.w = Math.trunc( this.w );
  4774. return this;
  4775. }
  4776. /**
  4777. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  4778. *
  4779. * @return {Vector4} A reference to this vector.
  4780. */
  4781. negate() {
  4782. this.x = - this.x;
  4783. this.y = - this.y;
  4784. this.z = - this.z;
  4785. this.w = - this.w;
  4786. return this;
  4787. }
  4788. /**
  4789. * Calculates the dot product of the given vector with this instance.
  4790. *
  4791. * @param {Vector4} v - The vector to compute the dot product with.
  4792. * @return {number} The result of the dot product.
  4793. */
  4794. dot( v ) {
  4795. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  4796. }
  4797. /**
  4798. * Computes the square of the Euclidean length (straight-line length) from
  4799. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  4800. * compare the length squared instead as it is slightly more efficient to calculate.
  4801. *
  4802. * @return {number} The square length of this vector.
  4803. */
  4804. lengthSq() {
  4805. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  4806. }
  4807. /**
  4808. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  4809. *
  4810. * @return {number} The length of this vector.
  4811. */
  4812. length() {
  4813. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  4814. }
  4815. /**
  4816. * Computes the Manhattan length of this vector.
  4817. *
  4818. * @return {number} The length of this vector.
  4819. */
  4820. manhattanLength() {
  4821. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  4822. }
  4823. /**
  4824. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4825. * with the same direction as this one, but with a vector length of `1`.
  4826. *
  4827. * @return {Vector4} A reference to this vector.
  4828. */
  4829. normalize() {
  4830. return this.divideScalar( this.length() || 1 );
  4831. }
  4832. /**
  4833. * Sets this vector to a vector with the same direction as this one, but
  4834. * with the specified length.
  4835. *
  4836. * @param {number} length - The new length of this vector.
  4837. * @return {Vector4} A reference to this vector.
  4838. */
  4839. setLength( length ) {
  4840. return this.normalize().multiplyScalar( length );
  4841. }
  4842. /**
  4843. * Linearly interpolates between the given vector and this instance, where
  4844. * alpha is the percent distance along the line - alpha = 0 will be this
  4845. * vector, and alpha = 1 will be the given one.
  4846. *
  4847. * @param {Vector4} v - The vector to interpolate towards.
  4848. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4849. * @return {Vector4} A reference to this vector.
  4850. */
  4851. lerp( v, alpha ) {
  4852. this.x += ( v.x - this.x ) * alpha;
  4853. this.y += ( v.y - this.y ) * alpha;
  4854. this.z += ( v.z - this.z ) * alpha;
  4855. this.w += ( v.w - this.w ) * alpha;
  4856. return this;
  4857. }
  4858. /**
  4859. * Linearly interpolates between the given vectors, where alpha is the percent
  4860. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4861. * be the second one. The result is stored in this instance.
  4862. *
  4863. * @param {Vector4} v1 - The first vector.
  4864. * @param {Vector4} v2 - The second vector.
  4865. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4866. * @return {Vector4} A reference to this vector.
  4867. */
  4868. lerpVectors( v1, v2, alpha ) {
  4869. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4870. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4871. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4872. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  4873. return this;
  4874. }
  4875. /**
  4876. * Returns `true` if this vector is equal with the given one.
  4877. *
  4878. * @param {Vector4} v - The vector to test for equality.
  4879. * @return {boolean} Whether this vector is equal with the given one.
  4880. */
  4881. equals( v ) {
  4882. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  4883. }
  4884. /**
  4885. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  4886. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  4887. *
  4888. * @param {Array<number>} array - An array holding the vector component values.
  4889. * @param {number} [offset=0] - The offset into the array.
  4890. * @return {Vector4} A reference to this vector.
  4891. */
  4892. fromArray( array, offset = 0 ) {
  4893. this.x = array[ offset ];
  4894. this.y = array[ offset + 1 ];
  4895. this.z = array[ offset + 2 ];
  4896. this.w = array[ offset + 3 ];
  4897. return this;
  4898. }
  4899. /**
  4900. * Writes the components of this vector to the given array. If no array is provided,
  4901. * the method returns a new instance.
  4902. *
  4903. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4904. * @param {number} [offset=0] - Index of the first element in the array.
  4905. * @return {Array<number>} The vector components.
  4906. */
  4907. toArray( array = [], offset = 0 ) {
  4908. array[ offset ] = this.x;
  4909. array[ offset + 1 ] = this.y;
  4910. array[ offset + 2 ] = this.z;
  4911. array[ offset + 3 ] = this.w;
  4912. return array;
  4913. }
  4914. /**
  4915. * Sets the components of this vector from the given buffer attribute.
  4916. *
  4917. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4918. * @param {number} index - The index into the attribute.
  4919. * @return {Vector4} A reference to this vector.
  4920. */
  4921. fromBufferAttribute( attribute, index ) {
  4922. this.x = attribute.getX( index );
  4923. this.y = attribute.getY( index );
  4924. this.z = attribute.getZ( index );
  4925. this.w = attribute.getW( index );
  4926. return this;
  4927. }
  4928. /**
  4929. * Sets each component of this vector to a pseudo-random value between `0` and
  4930. * `1`, excluding `1`.
  4931. *
  4932. * @return {Vector4} A reference to this vector.
  4933. */
  4934. random() {
  4935. this.x = Math.random();
  4936. this.y = Math.random();
  4937. this.z = Math.random();
  4938. this.w = Math.random();
  4939. return this;
  4940. }
  4941. *[ Symbol.iterator ]() {
  4942. yield this.x;
  4943. yield this.y;
  4944. yield this.z;
  4945. yield this.w;
  4946. }
  4947. }
  4948. /**
  4949. * A render target is a buffer where the video card draws pixels for a scene
  4950. * that is being rendered in the background. It is used in different effects,
  4951. * such as applying postprocessing to a rendered image before displaying it
  4952. * on the screen.
  4953. *
  4954. * @augments EventDispatcher
  4955. */
  4956. class RenderTarget extends EventDispatcher {
  4957. /**
  4958. * Render target options.
  4959. *
  4960. * @typedef {Object} RenderTarget~Options
  4961. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  4962. * @property {number} [magFilter=LinearFilter] - The mag filter.
  4963. * @property {number} [minFilter=LinearFilter] - The min filter.
  4964. * @property {number} [format=RGBAFormat] - The texture format.
  4965. * @property {number} [type=UnsignedByteType] - The texture type.
  4966. * @property {?string} [internalFormat=null] - The texture's internal format.
  4967. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  4968. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  4969. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  4970. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  4971. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  4972. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  4973. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  4974. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  4975. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  4976. * @property {number} [samples=0] - The MSAA samples count.
  4977. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  4978. */
  4979. /**
  4980. * Constructs a new render target.
  4981. *
  4982. * @param {number} [width=1] - The width of the render target.
  4983. * @param {number} [height=1] - The height of the render target.
  4984. * @param {RenderTarget~Options} [options] - The configuration object.
  4985. */
  4986. constructor( width = 1, height = 1, options = {} ) {
  4987. super();
  4988. /**
  4989. * This flag can be used for type testing.
  4990. *
  4991. * @type {boolean}
  4992. * @readonly
  4993. * @default true
  4994. */
  4995. this.isRenderTarget = true;
  4996. /**
  4997. * The width of the render target.
  4998. *
  4999. * @type {number}
  5000. * @default 1
  5001. */
  5002. this.width = width;
  5003. /**
  5004. * The height of the render target.
  5005. *
  5006. * @type {number}
  5007. * @default 1
  5008. */
  5009. this.height = height;
  5010. /**
  5011. * The depth of the render target.
  5012. *
  5013. * @type {number}
  5014. * @default 1
  5015. */
  5016. this.depth = 1;
  5017. /**
  5018. * A rectangular area inside the render target's viewport. Fragments that are
  5019. * outside the area will be discarded.
  5020. *
  5021. * @type {Vector4}
  5022. * @default (0,0,width,height)
  5023. */
  5024. this.scissor = new Vector4( 0, 0, width, height );
  5025. /**
  5026. * Indicates whether the scissor test should be enabled when rendering into
  5027. * this render target or not.
  5028. *
  5029. * @type {boolean}
  5030. * @default false
  5031. */
  5032. this.scissorTest = false;
  5033. /**
  5034. * A rectangular area representing the render target's viewport.
  5035. *
  5036. * @type {Vector4}
  5037. * @default (0,0,width,height)
  5038. */
  5039. this.viewport = new Vector4( 0, 0, width, height );
  5040. const image = { width: width, height: height, depth: 1 };
  5041. options = Object.assign( {
  5042. generateMipmaps: false,
  5043. internalFormat: null,
  5044. minFilter: LinearFilter,
  5045. depthBuffer: true,
  5046. stencilBuffer: false,
  5047. resolveDepthBuffer: true,
  5048. resolveStencilBuffer: true,
  5049. depthTexture: null,
  5050. samples: 0,
  5051. count: 1
  5052. }, options );
  5053. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  5054. texture.flipY = false;
  5055. texture.generateMipmaps = options.generateMipmaps;
  5056. texture.internalFormat = options.internalFormat;
  5057. /**
  5058. * An array of textures. Each color attachment is represented as a separate texture.
  5059. * Has at least a single entry for the default color attachment.
  5060. *
  5061. * @type {Array<Texture>}
  5062. */
  5063. this.textures = [];
  5064. const count = options.count;
  5065. for ( let i = 0; i < count; i ++ ) {
  5066. this.textures[ i ] = texture.clone();
  5067. this.textures[ i ].isRenderTargetTexture = true;
  5068. this.textures[ i ].renderTarget = this;
  5069. }
  5070. /**
  5071. * Whether to allocate a depth buffer or not.
  5072. *
  5073. * @type {boolean}
  5074. * @default true
  5075. */
  5076. this.depthBuffer = options.depthBuffer;
  5077. /**
  5078. * Whether to allocate a stencil buffer or not.
  5079. *
  5080. * @type {boolean}
  5081. * @default false
  5082. */
  5083. this.stencilBuffer = options.stencilBuffer;
  5084. /**
  5085. * Whether to resolve the depth buffer or not.
  5086. *
  5087. * @type {boolean}
  5088. * @default true
  5089. */
  5090. this.resolveDepthBuffer = options.resolveDepthBuffer;
  5091. /**
  5092. * Whether to resolve the stencil buffer or not.
  5093. *
  5094. * @type {boolean}
  5095. * @default true
  5096. */
  5097. this.resolveStencilBuffer = options.resolveStencilBuffer;
  5098. this._depthTexture = options.depthTexture;
  5099. /**
  5100. * The number of MSAA samples.
  5101. *
  5102. * A value of `0` disables MSAA.
  5103. *
  5104. * @type {number}
  5105. * @default 0
  5106. */
  5107. this.samples = options.samples;
  5108. }
  5109. /**
  5110. * The texture representing the default color attachment.
  5111. *
  5112. * @type {Texture}
  5113. */
  5114. get texture() {
  5115. return this.textures[ 0 ];
  5116. }
  5117. set texture( value ) {
  5118. this.textures[ 0 ] = value;
  5119. }
  5120. set depthTexture( current ) {
  5121. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  5122. if ( current !== null ) current.renderTarget = this;
  5123. this._depthTexture = current;
  5124. }
  5125. /**
  5126. * Instead of saving the depth in a renderbuffer, a texture
  5127. * can be used instead which is useful for further processing
  5128. * e.g. in context of post-processing.
  5129. *
  5130. * @type {?DepthTexture}
  5131. * @default null
  5132. */
  5133. get depthTexture() {
  5134. return this._depthTexture;
  5135. }
  5136. /**
  5137. * Sets the size of this render target.
  5138. *
  5139. * @param {number} width - The width.
  5140. * @param {number} height - The height.
  5141. * @param {number} [depth=1] - The depth.
  5142. */
  5143. setSize( width, height, depth = 1 ) {
  5144. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  5145. this.width = width;
  5146. this.height = height;
  5147. this.depth = depth;
  5148. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  5149. this.textures[ i ].image.width = width;
  5150. this.textures[ i ].image.height = height;
  5151. this.textures[ i ].image.depth = depth;
  5152. }
  5153. this.dispose();
  5154. }
  5155. this.viewport.set( 0, 0, width, height );
  5156. this.scissor.set( 0, 0, width, height );
  5157. }
  5158. /**
  5159. * Returns a new render target with copied values from this instance.
  5160. *
  5161. * @return {RenderTarget} A clone of this instance.
  5162. */
  5163. clone() {
  5164. return new this.constructor().copy( this );
  5165. }
  5166. /**
  5167. * Copies the settings of the given render target. This is a structural copy so
  5168. * no resources are shared between render targets after the copy. That includes
  5169. * all MRT textures and the depth texture.
  5170. *
  5171. * @param {RenderTarget} source - The render target to copy.
  5172. * @return {RenderTarget} A reference to this instance.
  5173. */
  5174. copy( source ) {
  5175. this.width = source.width;
  5176. this.height = source.height;
  5177. this.depth = source.depth;
  5178. this.scissor.copy( source.scissor );
  5179. this.scissorTest = source.scissorTest;
  5180. this.viewport.copy( source.viewport );
  5181. this.textures.length = 0;
  5182. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  5183. this.textures[ i ] = source.textures[ i ].clone();
  5184. this.textures[ i ].isRenderTargetTexture = true;
  5185. this.textures[ i ].renderTarget = this;
  5186. // ensure image object is not shared, see #20328
  5187. const image = Object.assign( {}, source.textures[ i ].image );
  5188. this.textures[ i ].source = new Source( image );
  5189. }
  5190. this.depthBuffer = source.depthBuffer;
  5191. this.stencilBuffer = source.stencilBuffer;
  5192. this.resolveDepthBuffer = source.resolveDepthBuffer;
  5193. this.resolveStencilBuffer = source.resolveStencilBuffer;
  5194. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  5195. this.samples = source.samples;
  5196. return this;
  5197. }
  5198. /**
  5199. * Frees the GPU-related resources allocated by this instance. Call this
  5200. * method whenever this instance is no longer used in your app.
  5201. *
  5202. * @fires RenderTarget#dispose
  5203. */
  5204. dispose() {
  5205. this.dispatchEvent( { type: 'dispose' } );
  5206. }
  5207. }
  5208. /**
  5209. * A render target used in context of {@link WebGLRenderer}.
  5210. *
  5211. * @augments RenderTarget
  5212. */
  5213. class WebGLRenderTarget extends RenderTarget {
  5214. /**
  5215. * Constructs a new 3D render target.
  5216. *
  5217. * @param {number} [width=1] - The width of the render target.
  5218. * @param {number} [height=1] - The height of the render target.
  5219. * @param {RenderTarget~Options} [options] - The configuration object.
  5220. */
  5221. constructor( width = 1, height = 1, options = {} ) {
  5222. super( width, height, options );
  5223. /**
  5224. * This flag can be used for type testing.
  5225. *
  5226. * @type {boolean}
  5227. * @readonly
  5228. * @default true
  5229. */
  5230. this.isWebGLRenderTarget = true;
  5231. }
  5232. }
  5233. /**
  5234. * Creates an array of textures directly from raw buffer data.
  5235. *
  5236. * @augments Texture
  5237. */
  5238. class DataArrayTexture extends Texture {
  5239. /**
  5240. * Constructs a new data array texture.
  5241. *
  5242. * @param {?TypedArray} [data=null] - The buffer data.
  5243. * @param {number} [width=1] - The width of the texture.
  5244. * @param {number} [height=1] - The height of the texture.
  5245. * @param {number} [depth=1] - The depth of the texture.
  5246. */
  5247. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  5248. super( null );
  5249. /**
  5250. * This flag can be used for type testing.
  5251. *
  5252. * @type {boolean}
  5253. * @readonly
  5254. * @default true
  5255. */
  5256. this.isDataArrayTexture = true;
  5257. /**
  5258. * The image definition of a data texture.
  5259. *
  5260. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  5261. */
  5262. this.image = { data, width, height, depth };
  5263. /**
  5264. * How the texture is sampled when a texel covers more than one pixel.
  5265. *
  5266. * Overwritten and set to `NearestFilter` by default.
  5267. *
  5268. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5269. * @default NearestFilter
  5270. */
  5271. this.magFilter = NearestFilter;
  5272. /**
  5273. * How the texture is sampled when a texel covers less than one pixel.
  5274. *
  5275. * Overwritten and set to `NearestFilter` by default.
  5276. *
  5277. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5278. * @default NearestFilter
  5279. */
  5280. this.minFilter = NearestFilter;
  5281. /**
  5282. * This defines how the texture is wrapped in the depth and corresponds to
  5283. * *W* in UVW mapping.
  5284. *
  5285. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5286. * @default ClampToEdgeWrapping
  5287. */
  5288. this.wrapR = ClampToEdgeWrapping;
  5289. /**
  5290. * Whether to generate mipmaps (if possible) for a texture.
  5291. *
  5292. * Overwritten and set to `false` by default.
  5293. *
  5294. * @type {boolean}
  5295. * @default false
  5296. */
  5297. this.generateMipmaps = false;
  5298. /**
  5299. * If set to `true`, the texture is flipped along the vertical axis when
  5300. * uploaded to the GPU.
  5301. *
  5302. * Overwritten and set to `false` by default.
  5303. *
  5304. * @type {boolean}
  5305. * @default false
  5306. */
  5307. this.flipY = false;
  5308. /**
  5309. * Specifies the alignment requirements for the start of each pixel row in memory.
  5310. *
  5311. * Overwritten and set to `1` by default.
  5312. *
  5313. * @type {boolean}
  5314. * @default 1
  5315. */
  5316. this.unpackAlignment = 1;
  5317. /**
  5318. * A set of all layers which need to be updated in the texture.
  5319. *
  5320. * @type {Set<number>}
  5321. */
  5322. this.layerUpdates = new Set();
  5323. }
  5324. /**
  5325. * Describes that a specific layer of the texture needs to be updated.
  5326. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  5327. * entire data texture array is sent to the GPU. Marking specific
  5328. * layers will only transmit subsets of all mipmaps associated with a
  5329. * specific depth in the array which is often much more performant.
  5330. *
  5331. * @param {number} layerIndex - The layer index that should be updated.
  5332. */
  5333. addLayerUpdate( layerIndex ) {
  5334. this.layerUpdates.add( layerIndex );
  5335. }
  5336. /**
  5337. * Resets the layer updates registry.
  5338. */
  5339. clearLayerUpdates() {
  5340. this.layerUpdates.clear();
  5341. }
  5342. }
  5343. /**
  5344. * An array render target used in context of {@link WebGLRenderer}.
  5345. *
  5346. * @augments WebGLRenderTarget
  5347. */
  5348. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  5349. /**
  5350. * Constructs a new array render target.
  5351. *
  5352. * @param {number} [width=1] - The width of the render target.
  5353. * @param {number} [height=1] - The height of the render target.
  5354. * @param {number} [depth=1] - The height of the render target.
  5355. * @param {RenderTarget~Options} [options] - The configuration object.
  5356. */
  5357. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  5358. super( width, height, options );
  5359. /**
  5360. * This flag can be used for type testing.
  5361. *
  5362. * @type {boolean}
  5363. * @readonly
  5364. * @default true
  5365. */
  5366. this.isWebGLArrayRenderTarget = true;
  5367. this.depth = depth;
  5368. /**
  5369. * Overwritten with a different texture type.
  5370. *
  5371. * @type {DataArrayTexture}
  5372. */
  5373. this.texture = new DataArrayTexture( null, width, height, depth );
  5374. this.texture.isRenderTargetTexture = true;
  5375. }
  5376. }
  5377. /**
  5378. * Creates a three-dimensional texture from raw data, with parameters to
  5379. * divide it into width, height, and depth.
  5380. *
  5381. * @augments Texture
  5382. */
  5383. class Data3DTexture extends Texture {
  5384. /**
  5385. * Constructs a new data array texture.
  5386. *
  5387. * @param {?TypedArray} [data=null] - The buffer data.
  5388. * @param {number} [width=1] - The width of the texture.
  5389. * @param {number} [height=1] - The height of the texture.
  5390. * @param {number} [depth=1] - The depth of the texture.
  5391. */
  5392. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  5393. // We're going to add .setXXX() methods for setting properties later.
  5394. // Users can still set in Data3DTexture directly.
  5395. //
  5396. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  5397. // texture.anisotropy = 16;
  5398. //
  5399. // See #14839
  5400. super( null );
  5401. /**
  5402. * This flag can be used for type testing.
  5403. *
  5404. * @type {boolean}
  5405. * @readonly
  5406. * @default true
  5407. */
  5408. this.isData3DTexture = true;
  5409. /**
  5410. * The image definition of a data texture.
  5411. *
  5412. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  5413. */
  5414. this.image = { data, width, height, depth };
  5415. /**
  5416. * How the texture is sampled when a texel covers more than one pixel.
  5417. *
  5418. * Overwritten and set to `NearestFilter` by default.
  5419. *
  5420. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5421. * @default NearestFilter
  5422. */
  5423. this.magFilter = NearestFilter;
  5424. /**
  5425. * How the texture is sampled when a texel covers less than one pixel.
  5426. *
  5427. * Overwritten and set to `NearestFilter` by default.
  5428. *
  5429. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5430. * @default NearestFilter
  5431. */
  5432. this.minFilter = NearestFilter;
  5433. /**
  5434. * This defines how the texture is wrapped in the depth and corresponds to
  5435. * *W* in UVW mapping.
  5436. *
  5437. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5438. * @default ClampToEdgeWrapping
  5439. */
  5440. this.wrapR = ClampToEdgeWrapping;
  5441. /**
  5442. * Whether to generate mipmaps (if possible) for a texture.
  5443. *
  5444. * Overwritten and set to `false` by default.
  5445. *
  5446. * @type {boolean}
  5447. * @default false
  5448. */
  5449. this.generateMipmaps = false;
  5450. /**
  5451. * If set to `true`, the texture is flipped along the vertical axis when
  5452. * uploaded to the GPU.
  5453. *
  5454. * Overwritten and set to `false` by default.
  5455. *
  5456. * @type {boolean}
  5457. * @default false
  5458. */
  5459. this.flipY = false;
  5460. /**
  5461. * Specifies the alignment requirements for the start of each pixel row in memory.
  5462. *
  5463. * Overwritten and set to `1` by default.
  5464. *
  5465. * @type {boolean}
  5466. * @default 1
  5467. */
  5468. this.unpackAlignment = 1;
  5469. }
  5470. }
  5471. /**
  5472. * A 3D render target used in context of {@link WebGLRenderer}.
  5473. *
  5474. * @augments WebGLRenderTarget
  5475. */
  5476. class WebGL3DRenderTarget extends WebGLRenderTarget {
  5477. /**
  5478. * Constructs a new 3D render target.
  5479. *
  5480. * @param {number} [width=1] - The width of the render target.
  5481. * @param {number} [height=1] - The height of the render target.
  5482. * @param {number} [depth=1] - The height of the render target.
  5483. * @param {RenderTarget~Options} [options] - The configuration object.
  5484. */
  5485. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  5486. super( width, height, options );
  5487. /**
  5488. * This flag can be used for type testing.
  5489. *
  5490. * @type {boolean}
  5491. * @readonly
  5492. * @default true
  5493. */
  5494. this.isWebGL3DRenderTarget = true;
  5495. this.depth = depth;
  5496. /**
  5497. * Overwritten with a different texture type.
  5498. *
  5499. * @type {Data3DTexture}
  5500. */
  5501. this.texture = new Data3DTexture( null, width, height, depth );
  5502. this.texture.isRenderTargetTexture = true;
  5503. }
  5504. }
  5505. /**
  5506. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  5507. *
  5508. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5509. * the corresponding order.
  5510. *
  5511. * Note that three.js expects Quaternions to be normalized.
  5512. * ```js
  5513. * const quaternion = new THREE.Quaternion();
  5514. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  5515. *
  5516. * const vector = new THREE.Vector3( 1, 0, 0 );
  5517. * vector.applyQuaternion( quaternion );
  5518. * ```
  5519. */
  5520. class Quaternion {
  5521. /**
  5522. * Constructs a new quaternion.
  5523. *
  5524. * @param {number} [x=0] - The x value of this quaternion.
  5525. * @param {number} [y=0] - The y value of this quaternion.
  5526. * @param {number} [z=0] - The z value of this quaternion.
  5527. * @param {number} [w=1] - The w value of this quaternion.
  5528. */
  5529. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5530. /**
  5531. * This flag can be used for type testing.
  5532. *
  5533. * @type {boolean}
  5534. * @readonly
  5535. * @default true
  5536. */
  5537. this.isQuaternion = true;
  5538. this._x = x;
  5539. this._y = y;
  5540. this._z = z;
  5541. this._w = w;
  5542. }
  5543. /**
  5544. * Interpolates between two quaternions via SLERP. This implementation assumes the
  5545. * quaternion data are managed in flat arrays.
  5546. *
  5547. * @param {Array<number>} dst - The destination array.
  5548. * @param {number} dstOffset - An offset into the destination array.
  5549. * @param {Array<number>} src0 - The source array of the first quaternion.
  5550. * @param {number} srcOffset0 - An offset into the first source array.
  5551. * @param {Array<number>} src1 - The source array of the second quaternion.
  5552. * @param {number} srcOffset1 - An offset into the second source array.
  5553. * @param {number} t - The interpolation factor in the range `[0,1]`.
  5554. * @see {@link Quaternion#slerp}
  5555. */
  5556. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5557. // fuzz-free, array-based Quaternion SLERP operation
  5558. let x0 = src0[ srcOffset0 + 0 ],
  5559. y0 = src0[ srcOffset0 + 1 ],
  5560. z0 = src0[ srcOffset0 + 2 ],
  5561. w0 = src0[ srcOffset0 + 3 ];
  5562. const x1 = src1[ srcOffset1 + 0 ],
  5563. y1 = src1[ srcOffset1 + 1 ],
  5564. z1 = src1[ srcOffset1 + 2 ],
  5565. w1 = src1[ srcOffset1 + 3 ];
  5566. if ( t === 0 ) {
  5567. dst[ dstOffset + 0 ] = x0;
  5568. dst[ dstOffset + 1 ] = y0;
  5569. dst[ dstOffset + 2 ] = z0;
  5570. dst[ dstOffset + 3 ] = w0;
  5571. return;
  5572. }
  5573. if ( t === 1 ) {
  5574. dst[ dstOffset + 0 ] = x1;
  5575. dst[ dstOffset + 1 ] = y1;
  5576. dst[ dstOffset + 2 ] = z1;
  5577. dst[ dstOffset + 3 ] = w1;
  5578. return;
  5579. }
  5580. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5581. let s = 1 - t;
  5582. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5583. dir = ( cos >= 0 ? 1 : - 1 ),
  5584. sqrSin = 1 - cos * cos;
  5585. // Skip the Slerp for tiny steps to avoid numeric problems:
  5586. if ( sqrSin > Number.EPSILON ) {
  5587. const sin = Math.sqrt( sqrSin ),
  5588. len = Math.atan2( sin, cos * dir );
  5589. s = Math.sin( s * len ) / sin;
  5590. t = Math.sin( t * len ) / sin;
  5591. }
  5592. const tDir = t * dir;
  5593. x0 = x0 * s + x1 * tDir;
  5594. y0 = y0 * s + y1 * tDir;
  5595. z0 = z0 * s + z1 * tDir;
  5596. w0 = w0 * s + w1 * tDir;
  5597. // Normalize in case we just did a lerp:
  5598. if ( s === 1 - t ) {
  5599. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5600. x0 *= f;
  5601. y0 *= f;
  5602. z0 *= f;
  5603. w0 *= f;
  5604. }
  5605. }
  5606. dst[ dstOffset ] = x0;
  5607. dst[ dstOffset + 1 ] = y0;
  5608. dst[ dstOffset + 2 ] = z0;
  5609. dst[ dstOffset + 3 ] = w0;
  5610. }
  5611. /**
  5612. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  5613. * in flat arrays.
  5614. *
  5615. * @param {Array<number>} dst - The destination array.
  5616. * @param {number} dstOffset - An offset into the destination array.
  5617. * @param {Array<number>} src0 - The source array of the first quaternion.
  5618. * @param {number} srcOffset0 - An offset into the first source array.
  5619. * @param {Array<number>} src1 - The source array of the second quaternion.
  5620. * @param {number} srcOffset1 - An offset into the second source array.
  5621. * @return {Array<number>} The destination array.
  5622. * @see {@link Quaternion#multiplyQuaternions}.
  5623. */
  5624. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  5625. const x0 = src0[ srcOffset0 ];
  5626. const y0 = src0[ srcOffset0 + 1 ];
  5627. const z0 = src0[ srcOffset0 + 2 ];
  5628. const w0 = src0[ srcOffset0 + 3 ];
  5629. const x1 = src1[ srcOffset1 ];
  5630. const y1 = src1[ srcOffset1 + 1 ];
  5631. const z1 = src1[ srcOffset1 + 2 ];
  5632. const w1 = src1[ srcOffset1 + 3 ];
  5633. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  5634. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  5635. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  5636. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  5637. return dst;
  5638. }
  5639. /**
  5640. * The x value of this quaternion.
  5641. *
  5642. * @type {number}
  5643. * @default 0
  5644. */
  5645. get x() {
  5646. return this._x;
  5647. }
  5648. set x( value ) {
  5649. this._x = value;
  5650. this._onChangeCallback();
  5651. }
  5652. /**
  5653. * The y value of this quaternion.
  5654. *
  5655. * @type {number}
  5656. * @default 0
  5657. */
  5658. get y() {
  5659. return this._y;
  5660. }
  5661. set y( value ) {
  5662. this._y = value;
  5663. this._onChangeCallback();
  5664. }
  5665. /**
  5666. * The z value of this quaternion.
  5667. *
  5668. * @type {number}
  5669. * @default 0
  5670. */
  5671. get z() {
  5672. return this._z;
  5673. }
  5674. set z( value ) {
  5675. this._z = value;
  5676. this._onChangeCallback();
  5677. }
  5678. /**
  5679. * The w value of this quaternion.
  5680. *
  5681. * @type {number}
  5682. * @default 1
  5683. */
  5684. get w() {
  5685. return this._w;
  5686. }
  5687. set w( value ) {
  5688. this._w = value;
  5689. this._onChangeCallback();
  5690. }
  5691. /**
  5692. * Sets the quaternion components.
  5693. *
  5694. * @param {number} x - The x value of this quaternion.
  5695. * @param {number} y - The y value of this quaternion.
  5696. * @param {number} z - The z value of this quaternion.
  5697. * @param {number} w - The w value of this quaternion.
  5698. * @return {Quaternion} A reference to this quaternion.
  5699. */
  5700. set( x, y, z, w ) {
  5701. this._x = x;
  5702. this._y = y;
  5703. this._z = z;
  5704. this._w = w;
  5705. this._onChangeCallback();
  5706. return this;
  5707. }
  5708. /**
  5709. * Returns a new quaternion with copied values from this instance.
  5710. *
  5711. * @return {Quaternion} A clone of this instance.
  5712. */
  5713. clone() {
  5714. return new this.constructor( this._x, this._y, this._z, this._w );
  5715. }
  5716. /**
  5717. * Copies the values of the given quaternion to this instance.
  5718. *
  5719. * @param {Quaternion} quaternion - The quaternion to copy.
  5720. * @return {Quaternion} A reference to this quaternion.
  5721. */
  5722. copy( quaternion ) {
  5723. this._x = quaternion.x;
  5724. this._y = quaternion.y;
  5725. this._z = quaternion.z;
  5726. this._w = quaternion.w;
  5727. this._onChangeCallback();
  5728. return this;
  5729. }
  5730. /**
  5731. * Sets this quaternion from the rotation specified by the given
  5732. * Euler angles.
  5733. *
  5734. * @param {Euler} euler - The Euler angles.
  5735. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  5736. * @return {Quaternion} A reference to this quaternion.
  5737. */
  5738. setFromEuler( euler, update = true ) {
  5739. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  5740. // http://www.mathworks.com/matlabcentral/fileexchange/
  5741. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5742. // content/SpinCalc.m
  5743. const cos = Math.cos;
  5744. const sin = Math.sin;
  5745. const c1 = cos( x / 2 );
  5746. const c2 = cos( y / 2 );
  5747. const c3 = cos( z / 2 );
  5748. const s1 = sin( x / 2 );
  5749. const s2 = sin( y / 2 );
  5750. const s3 = sin( z / 2 );
  5751. switch ( order ) {
  5752. case 'XYZ':
  5753. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5754. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5755. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5756. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5757. break;
  5758. case 'YXZ':
  5759. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5760. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5761. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5762. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5763. break;
  5764. case 'ZXY':
  5765. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5766. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5767. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5768. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5769. break;
  5770. case 'ZYX':
  5771. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5772. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5773. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5774. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5775. break;
  5776. case 'YZX':
  5777. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5778. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5779. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5780. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5781. break;
  5782. case 'XZY':
  5783. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5784. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5785. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5786. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5787. break;
  5788. default:
  5789. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  5790. }
  5791. if ( update === true ) this._onChangeCallback();
  5792. return this;
  5793. }
  5794. /**
  5795. * Sets this quaternion from the given axis and angle.
  5796. *
  5797. * @param {Vector3} axis - The normalized axis.
  5798. * @param {number} angle - The angle in radians.
  5799. * @return {Quaternion} A reference to this quaternion.
  5800. */
  5801. setFromAxisAngle( axis, angle ) {
  5802. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5803. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  5804. this._x = axis.x * s;
  5805. this._y = axis.y * s;
  5806. this._z = axis.z * s;
  5807. this._w = Math.cos( halfAngle );
  5808. this._onChangeCallback();
  5809. return this;
  5810. }
  5811. /**
  5812. * Sets this quaternion from the given rotation matrix.
  5813. *
  5814. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  5815. * @return {Quaternion} A reference to this quaternion.
  5816. */
  5817. setFromRotationMatrix( m ) {
  5818. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5819. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5820. const te = m.elements,
  5821. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5822. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5823. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5824. trace = m11 + m22 + m33;
  5825. if ( trace > 0 ) {
  5826. const s = 0.5 / Math.sqrt( trace + 1.0 );
  5827. this._w = 0.25 / s;
  5828. this._x = ( m32 - m23 ) * s;
  5829. this._y = ( m13 - m31 ) * s;
  5830. this._z = ( m21 - m12 ) * s;
  5831. } else if ( m11 > m22 && m11 > m33 ) {
  5832. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5833. this._w = ( m32 - m23 ) / s;
  5834. this._x = 0.25 * s;
  5835. this._y = ( m12 + m21 ) / s;
  5836. this._z = ( m13 + m31 ) / s;
  5837. } else if ( m22 > m33 ) {
  5838. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5839. this._w = ( m13 - m31 ) / s;
  5840. this._x = ( m12 + m21 ) / s;
  5841. this._y = 0.25 * s;
  5842. this._z = ( m23 + m32 ) / s;
  5843. } else {
  5844. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5845. this._w = ( m21 - m12 ) / s;
  5846. this._x = ( m13 + m31 ) / s;
  5847. this._y = ( m23 + m32 ) / s;
  5848. this._z = 0.25 * s;
  5849. }
  5850. this._onChangeCallback();
  5851. return this;
  5852. }
  5853. /**
  5854. * Sets this quaternion to the rotation required to rotate the direction vector
  5855. * `vFrom` to the direction vector `vTo`.
  5856. *
  5857. * @param {Vector3} vFrom - The first (normalized) direction vector.
  5858. * @param {Vector3} vTo - The second (normalized) direction vector.
  5859. * @return {Quaternion} A reference to this quaternion.
  5860. */
  5861. setFromUnitVectors( vFrom, vTo ) {
  5862. // assumes direction vectors vFrom and vTo are normalized
  5863. let r = vFrom.dot( vTo ) + 1;
  5864. if ( r < Number.EPSILON ) {
  5865. // vFrom and vTo point in opposite directions
  5866. r = 0;
  5867. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5868. this._x = - vFrom.y;
  5869. this._y = vFrom.x;
  5870. this._z = 0;
  5871. this._w = r;
  5872. } else {
  5873. this._x = 0;
  5874. this._y = - vFrom.z;
  5875. this._z = vFrom.y;
  5876. this._w = r;
  5877. }
  5878. } else {
  5879. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  5880. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  5881. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  5882. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  5883. this._w = r;
  5884. }
  5885. return this.normalize();
  5886. }
  5887. /**
  5888. * Returns the angle between this quaternion and the given one in radians.
  5889. *
  5890. * @param {Quaternion} q - The quaternion to compute the angle with.
  5891. * @return {number} The angle in radians.
  5892. */
  5893. angleTo( q ) {
  5894. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  5895. }
  5896. /**
  5897. * Rotates this quaternion by a given angular step to the given quaternion.
  5898. * The method ensures that the final quaternion will not overshoot `q`.
  5899. *
  5900. * @param {Quaternion} q - The target quaternion.
  5901. * @param {number} step - The angular step in radians.
  5902. * @return {Quaternion} A reference to this quaternion.
  5903. */
  5904. rotateTowards( q, step ) {
  5905. const angle = this.angleTo( q );
  5906. if ( angle === 0 ) return this;
  5907. const t = Math.min( 1, step / angle );
  5908. this.slerp( q, t );
  5909. return this;
  5910. }
  5911. /**
  5912. * Sets this quaternion to the identity quaternion; that is, to the
  5913. * quaternion that represents "no rotation".
  5914. *
  5915. * @return {Quaternion} A reference to this quaternion.
  5916. */
  5917. identity() {
  5918. return this.set( 0, 0, 0, 1 );
  5919. }
  5920. /**
  5921. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  5922. * quaternion is assumed to have unit length.
  5923. *
  5924. * @return {Quaternion} A reference to this quaternion.
  5925. */
  5926. invert() {
  5927. return this.conjugate();
  5928. }
  5929. /**
  5930. * Returns the rotational conjugate of this quaternion. The conjugate of a
  5931. * quaternion represents the same rotation in the opposite direction about
  5932. * the rotational axis.
  5933. *
  5934. * @return {Quaternion} A reference to this quaternion.
  5935. */
  5936. conjugate() {
  5937. this._x *= - 1;
  5938. this._y *= - 1;
  5939. this._z *= - 1;
  5940. this._onChangeCallback();
  5941. return this;
  5942. }
  5943. /**
  5944. * Calculates the dot product of this quaternion and the given one.
  5945. *
  5946. * @param {Quaternion} v - The quaternion to compute the dot product with.
  5947. * @return {number} The result of the dot product.
  5948. */
  5949. dot( v ) {
  5950. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5951. }
  5952. /**
  5953. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  5954. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  5955. * lengths of two quaternions, as this is a slightly more efficient calculation than
  5956. * {@link Quaternion#length}.
  5957. *
  5958. * @return {number} The squared Euclidean length.
  5959. */
  5960. lengthSq() {
  5961. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5962. }
  5963. /**
  5964. * Computes the Euclidean length (straight-line length) of this quaternion,
  5965. * considered as a 4 dimensional vector.
  5966. *
  5967. * @return {number} The Euclidean length.
  5968. */
  5969. length() {
  5970. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5971. }
  5972. /**
  5973. * Normalizes this quaternion - that is, calculated the quaternion that performs
  5974. * the same rotation as this one, but has a length equal to `1`.
  5975. *
  5976. * @return {Quaternion} A reference to this quaternion.
  5977. */
  5978. normalize() {
  5979. let l = this.length();
  5980. if ( l === 0 ) {
  5981. this._x = 0;
  5982. this._y = 0;
  5983. this._z = 0;
  5984. this._w = 1;
  5985. } else {
  5986. l = 1 / l;
  5987. this._x = this._x * l;
  5988. this._y = this._y * l;
  5989. this._z = this._z * l;
  5990. this._w = this._w * l;
  5991. }
  5992. this._onChangeCallback();
  5993. return this;
  5994. }
  5995. /**
  5996. * Multiplies this quaternion by the given one.
  5997. *
  5998. * @param {Quaternion} q - The quaternion.
  5999. * @return {Quaternion} A reference to this quaternion.
  6000. */
  6001. multiply( q ) {
  6002. return this.multiplyQuaternions( this, q );
  6003. }
  6004. /**
  6005. * Pre-multiplies this quaternion by the given one.
  6006. *
  6007. * @param {Quaternion} q - The quaternion.
  6008. * @return {Quaternion} A reference to this quaternion.
  6009. */
  6010. premultiply( q ) {
  6011. return this.multiplyQuaternions( q, this );
  6012. }
  6013. /**
  6014. * Multiplies the given quaternions and stores the result in this instance.
  6015. *
  6016. * @param {Quaternion} a - The first quaternion.
  6017. * @param {Quaternion} b - The second quaternion.
  6018. * @return {Quaternion} A reference to this quaternion.
  6019. */
  6020. multiplyQuaternions( a, b ) {
  6021. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  6022. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  6023. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  6024. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  6025. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  6026. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  6027. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  6028. this._onChangeCallback();
  6029. return this;
  6030. }
  6031. /**
  6032. * Performs a spherical linear interpolation between quaternions.
  6033. *
  6034. * @param {Quaternion} qb - The target quaternion.
  6035. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  6036. * @return {Quaternion} A reference to this quaternion.
  6037. */
  6038. slerp( qb, t ) {
  6039. if ( t === 0 ) return this;
  6040. if ( t === 1 ) return this.copy( qb );
  6041. const x = this._x, y = this._y, z = this._z, w = this._w;
  6042. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  6043. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  6044. if ( cosHalfTheta < 0 ) {
  6045. this._w = - qb._w;
  6046. this._x = - qb._x;
  6047. this._y = - qb._y;
  6048. this._z = - qb._z;
  6049. cosHalfTheta = - cosHalfTheta;
  6050. } else {
  6051. this.copy( qb );
  6052. }
  6053. if ( cosHalfTheta >= 1.0 ) {
  6054. this._w = w;
  6055. this._x = x;
  6056. this._y = y;
  6057. this._z = z;
  6058. return this;
  6059. }
  6060. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  6061. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  6062. const s = 1 - t;
  6063. this._w = s * w + t * this._w;
  6064. this._x = s * x + t * this._x;
  6065. this._y = s * y + t * this._y;
  6066. this._z = s * z + t * this._z;
  6067. this.normalize(); // normalize calls _onChangeCallback()
  6068. return this;
  6069. }
  6070. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  6071. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  6072. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  6073. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  6074. this._w = ( w * ratioA + this._w * ratioB );
  6075. this._x = ( x * ratioA + this._x * ratioB );
  6076. this._y = ( y * ratioA + this._y * ratioB );
  6077. this._z = ( z * ratioA + this._z * ratioB );
  6078. this._onChangeCallback();
  6079. return this;
  6080. }
  6081. /**
  6082. * Performs a spherical linear interpolation between the given quaternions
  6083. * and stores the result in this quaternion.
  6084. *
  6085. * @param {Quaternion} qa - The source quaternion.
  6086. * @param {Quaternion} qb - The target quaternion.
  6087. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  6088. * @return {Quaternion} A reference to this quaternion.
  6089. */
  6090. slerpQuaternions( qa, qb, t ) {
  6091. return this.copy( qa ).slerp( qb, t );
  6092. }
  6093. /**
  6094. * Sets this quaternion to a uniformly random, normalized quaternion.
  6095. *
  6096. * @return {Quaternion} A reference to this quaternion.
  6097. */
  6098. random() {
  6099. // Ken Shoemake
  6100. // Uniform random rotations
  6101. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  6102. const theta1 = 2 * Math.PI * Math.random();
  6103. const theta2 = 2 * Math.PI * Math.random();
  6104. const x0 = Math.random();
  6105. const r1 = Math.sqrt( 1 - x0 );
  6106. const r2 = Math.sqrt( x0 );
  6107. return this.set(
  6108. r1 * Math.sin( theta1 ),
  6109. r1 * Math.cos( theta1 ),
  6110. r2 * Math.sin( theta2 ),
  6111. r2 * Math.cos( theta2 ),
  6112. );
  6113. }
  6114. /**
  6115. * Returns `true` if this quaternion is equal with the given one.
  6116. *
  6117. * @param {Quaternion} quaternion - The quaternion to test for equality.
  6118. * @return {boolean} Whether this quaternion is equal with the given one.
  6119. */
  6120. equals( quaternion ) {
  6121. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  6122. }
  6123. /**
  6124. * Sets this quaternion's components from the given array.
  6125. *
  6126. * @param {Array<number>} array - An array holding the quaternion component values.
  6127. * @param {number} [offset=0] - The offset into the array.
  6128. * @return {Quaternion} A reference to this quaternion.
  6129. */
  6130. fromArray( array, offset = 0 ) {
  6131. this._x = array[ offset ];
  6132. this._y = array[ offset + 1 ];
  6133. this._z = array[ offset + 2 ];
  6134. this._w = array[ offset + 3 ];
  6135. this._onChangeCallback();
  6136. return this;
  6137. }
  6138. /**
  6139. * Writes the components of this quaternion to the given array. If no array is provided,
  6140. * the method returns a new instance.
  6141. *
  6142. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  6143. * @param {number} [offset=0] - Index of the first element in the array.
  6144. * @return {Array<number>} The quaternion components.
  6145. */
  6146. toArray( array = [], offset = 0 ) {
  6147. array[ offset ] = this._x;
  6148. array[ offset + 1 ] = this._y;
  6149. array[ offset + 2 ] = this._z;
  6150. array[ offset + 3 ] = this._w;
  6151. return array;
  6152. }
  6153. /**
  6154. * Sets the components of this quaternion from the given buffer attribute.
  6155. *
  6156. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  6157. * @param {number} index - The index into the attribute.
  6158. * @return {Quaternion} A reference to this quaternion.
  6159. */
  6160. fromBufferAttribute( attribute, index ) {
  6161. this._x = attribute.getX( index );
  6162. this._y = attribute.getY( index );
  6163. this._z = attribute.getZ( index );
  6164. this._w = attribute.getW( index );
  6165. this._onChangeCallback();
  6166. return this;
  6167. }
  6168. /**
  6169. * This methods defines the serialization result of this class. Returns the
  6170. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  6171. *
  6172. * @return {Array<number>} The serialized quaternion.
  6173. */
  6174. toJSON() {
  6175. return this.toArray();
  6176. }
  6177. _onChange( callback ) {
  6178. this._onChangeCallback = callback;
  6179. return this;
  6180. }
  6181. _onChangeCallback() {}
  6182. *[ Symbol.iterator ]() {
  6183. yield this._x;
  6184. yield this._y;
  6185. yield this._z;
  6186. yield this._w;
  6187. }
  6188. }
  6189. /**
  6190. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  6191. * (labeled x, y and z), which can be used to represent a number of things, such as:
  6192. *
  6193. * - A point in 3D space.
  6194. * - A direction and length in 3D space. In three.js the length will
  6195. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  6196. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  6197. * - Any arbitrary ordered triplet of numbers.
  6198. *
  6199. * There are other things a 3D vector can be used to represent, such as
  6200. * momentum vectors and so on, however these are the most
  6201. * common uses in three.js.
  6202. *
  6203. * Iterating through a vector instance will yield its components `(x, y, z)` in
  6204. * the corresponding order.
  6205. * ```js
  6206. * const a = new THREE.Vector3( 0, 1, 0 );
  6207. *
  6208. * //no arguments; will be initialised to (0, 0, 0)
  6209. * const b = new THREE.Vector3( );
  6210. *
  6211. * const d = a.distanceTo( b );
  6212. * ```
  6213. */
  6214. class Vector3 {
  6215. /**
  6216. * Constructs a new 3D vector.
  6217. *
  6218. * @param {number} [x=0] - The x value of this vector.
  6219. * @param {number} [y=0] - The y value of this vector.
  6220. * @param {number} [z=0] - The z value of this vector.
  6221. */
  6222. constructor( x = 0, y = 0, z = 0 ) {
  6223. /**
  6224. * This flag can be used for type testing.
  6225. *
  6226. * @type {boolean}
  6227. * @readonly
  6228. * @default true
  6229. */
  6230. Vector3.prototype.isVector3 = true;
  6231. /**
  6232. * The x value of this vector.
  6233. *
  6234. * @type {number}
  6235. */
  6236. this.x = x;
  6237. /**
  6238. * The y value of this vector.
  6239. *
  6240. * @type {number}
  6241. */
  6242. this.y = y;
  6243. /**
  6244. * The z value of this vector.
  6245. *
  6246. * @type {number}
  6247. */
  6248. this.z = z;
  6249. }
  6250. /**
  6251. * Sets the vector components.
  6252. *
  6253. * @param {number} x - The value of the x component.
  6254. * @param {number} y - The value of the y component.
  6255. * @param {number} z - The value of the z component.
  6256. * @return {Vector3} A reference to this vector.
  6257. */
  6258. set( x, y, z ) {
  6259. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  6260. this.x = x;
  6261. this.y = y;
  6262. this.z = z;
  6263. return this;
  6264. }
  6265. /**
  6266. * Sets the vector components to the same value.
  6267. *
  6268. * @param {number} scalar - The value to set for all vector components.
  6269. * @return {Vector3} A reference to this vector.
  6270. */
  6271. setScalar( scalar ) {
  6272. this.x = scalar;
  6273. this.y = scalar;
  6274. this.z = scalar;
  6275. return this;
  6276. }
  6277. /**
  6278. * Sets the vector's x component to the given value
  6279. *
  6280. * @param {number} x - The value to set.
  6281. * @return {Vector3} A reference to this vector.
  6282. */
  6283. setX( x ) {
  6284. this.x = x;
  6285. return this;
  6286. }
  6287. /**
  6288. * Sets the vector's y component to the given value
  6289. *
  6290. * @param {number} y - The value to set.
  6291. * @return {Vector3} A reference to this vector.
  6292. */
  6293. setY( y ) {
  6294. this.y = y;
  6295. return this;
  6296. }
  6297. /**
  6298. * Sets the vector's z component to the given value
  6299. *
  6300. * @param {number} z - The value to set.
  6301. * @return {Vector3} A reference to this vector.
  6302. */
  6303. setZ( z ) {
  6304. this.z = z;
  6305. return this;
  6306. }
  6307. /**
  6308. * Allows to set a vector component with an index.
  6309. *
  6310. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  6311. * @param {number} value - The value to set.
  6312. * @return {Vector3} A reference to this vector.
  6313. */
  6314. setComponent( index, value ) {
  6315. switch ( index ) {
  6316. case 0: this.x = value; break;
  6317. case 1: this.y = value; break;
  6318. case 2: this.z = value; break;
  6319. default: throw new Error( 'index is out of range: ' + index );
  6320. }
  6321. return this;
  6322. }
  6323. /**
  6324. * Returns the value of the vector component which matches the given index.
  6325. *
  6326. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  6327. * @return {number} A vector component value.
  6328. */
  6329. getComponent( index ) {
  6330. switch ( index ) {
  6331. case 0: return this.x;
  6332. case 1: return this.y;
  6333. case 2: return this.z;
  6334. default: throw new Error( 'index is out of range: ' + index );
  6335. }
  6336. }
  6337. /**
  6338. * Returns a new vector with copied values from this instance.
  6339. *
  6340. * @return {Vector3} A clone of this instance.
  6341. */
  6342. clone() {
  6343. return new this.constructor( this.x, this.y, this.z );
  6344. }
  6345. /**
  6346. * Copies the values of the given vector to this instance.
  6347. *
  6348. * @param {Vector3} v - The vector to copy.
  6349. * @return {Vector3} A reference to this vector.
  6350. */
  6351. copy( v ) {
  6352. this.x = v.x;
  6353. this.y = v.y;
  6354. this.z = v.z;
  6355. return this;
  6356. }
  6357. /**
  6358. * Adds the given vector to this instance.
  6359. *
  6360. * @param {Vector3} v - The vector to add.
  6361. * @return {Vector3} A reference to this vector.
  6362. */
  6363. add( v ) {
  6364. this.x += v.x;
  6365. this.y += v.y;
  6366. this.z += v.z;
  6367. return this;
  6368. }
  6369. /**
  6370. * Adds the given scalar value to all components of this instance.
  6371. *
  6372. * @param {number} s - The scalar to add.
  6373. * @return {Vector3} A reference to this vector.
  6374. */
  6375. addScalar( s ) {
  6376. this.x += s;
  6377. this.y += s;
  6378. this.z += s;
  6379. return this;
  6380. }
  6381. /**
  6382. * Adds the given vectors and stores the result in this instance.
  6383. *
  6384. * @param {Vector3} a - The first vector.
  6385. * @param {Vector3} b - The second vector.
  6386. * @return {Vector3} A reference to this vector.
  6387. */
  6388. addVectors( a, b ) {
  6389. this.x = a.x + b.x;
  6390. this.y = a.y + b.y;
  6391. this.z = a.z + b.z;
  6392. return this;
  6393. }
  6394. /**
  6395. * Adds the given vector scaled by the given factor to this instance.
  6396. *
  6397. * @param {Vector3|Vector4} v - The vector.
  6398. * @param {number} s - The factor that scales `v`.
  6399. * @return {Vector3} A reference to this vector.
  6400. */
  6401. addScaledVector( v, s ) {
  6402. this.x += v.x * s;
  6403. this.y += v.y * s;
  6404. this.z += v.z * s;
  6405. return this;
  6406. }
  6407. /**
  6408. * Subtracts the given vector from this instance.
  6409. *
  6410. * @param {Vector3} v - The vector to subtract.
  6411. * @return {Vector3} A reference to this vector.
  6412. */
  6413. sub( v ) {
  6414. this.x -= v.x;
  6415. this.y -= v.y;
  6416. this.z -= v.z;
  6417. return this;
  6418. }
  6419. /**
  6420. * Subtracts the given scalar value from all components of this instance.
  6421. *
  6422. * @param {number} s - The scalar to subtract.
  6423. * @return {Vector3} A reference to this vector.
  6424. */
  6425. subScalar( s ) {
  6426. this.x -= s;
  6427. this.y -= s;
  6428. this.z -= s;
  6429. return this;
  6430. }
  6431. /**
  6432. * Subtracts the given vectors and stores the result in this instance.
  6433. *
  6434. * @param {Vector3} a - The first vector.
  6435. * @param {Vector3} b - The second vector.
  6436. * @return {Vector3} A reference to this vector.
  6437. */
  6438. subVectors( a, b ) {
  6439. this.x = a.x - b.x;
  6440. this.y = a.y - b.y;
  6441. this.z = a.z - b.z;
  6442. return this;
  6443. }
  6444. /**
  6445. * Multiplies the given vector with this instance.
  6446. *
  6447. * @param {Vector3} v - The vector to multiply.
  6448. * @return {Vector3} A reference to this vector.
  6449. */
  6450. multiply( v ) {
  6451. this.x *= v.x;
  6452. this.y *= v.y;
  6453. this.z *= v.z;
  6454. return this;
  6455. }
  6456. /**
  6457. * Multiplies the given scalar value with all components of this instance.
  6458. *
  6459. * @param {number} scalar - The scalar to multiply.
  6460. * @return {Vector3} A reference to this vector.
  6461. */
  6462. multiplyScalar( scalar ) {
  6463. this.x *= scalar;
  6464. this.y *= scalar;
  6465. this.z *= scalar;
  6466. return this;
  6467. }
  6468. /**
  6469. * Multiplies the given vectors and stores the result in this instance.
  6470. *
  6471. * @param {Vector3} a - The first vector.
  6472. * @param {Vector3} b - The second vector.
  6473. * @return {Vector3} A reference to this vector.
  6474. */
  6475. multiplyVectors( a, b ) {
  6476. this.x = a.x * b.x;
  6477. this.y = a.y * b.y;
  6478. this.z = a.z * b.z;
  6479. return this;
  6480. }
  6481. /**
  6482. * Applies the given Euler rotation to this vector.
  6483. *
  6484. * @param {Euler} euler - The Euler angles.
  6485. * @return {Vector3} A reference to this vector.
  6486. */
  6487. applyEuler( euler ) {
  6488. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  6489. }
  6490. /**
  6491. * Applies a rotation specified by an axis and an angle to this vector.
  6492. *
  6493. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  6494. * @param {number} angle - The angle in radians.
  6495. * @return {Vector3} A reference to this vector.
  6496. */
  6497. applyAxisAngle( axis, angle ) {
  6498. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  6499. }
  6500. /**
  6501. * Multiplies this vector with the given 3x3 matrix.
  6502. *
  6503. * @param {Matrix3} m - The 3x3 matrix.
  6504. * @return {Vector3} A reference to this vector.
  6505. */
  6506. applyMatrix3( m ) {
  6507. const x = this.x, y = this.y, z = this.z;
  6508. const e = m.elements;
  6509. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6510. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6511. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6512. return this;
  6513. }
  6514. /**
  6515. * Multiplies this vector by the given normal matrix and normalizes
  6516. * the result.
  6517. *
  6518. * @param {Matrix3} m - The normal matrix.
  6519. * @return {Vector3} A reference to this vector.
  6520. */
  6521. applyNormalMatrix( m ) {
  6522. return this.applyMatrix3( m ).normalize();
  6523. }
  6524. /**
  6525. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  6526. * divides by perspective.
  6527. *
  6528. * @param {Matrix4} m - The matrix to apply.
  6529. * @return {Vector3} A reference to this vector.
  6530. */
  6531. applyMatrix4( m ) {
  6532. const x = this.x, y = this.y, z = this.z;
  6533. const e = m.elements;
  6534. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6535. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6536. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6537. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6538. return this;
  6539. }
  6540. /**
  6541. * Applies the given Quaternion to this vector.
  6542. *
  6543. * @param {Quaternion} q - The Quaternion.
  6544. * @return {Vector3} A reference to this vector.
  6545. */
  6546. applyQuaternion( q ) {
  6547. // quaternion q is assumed to have unit length
  6548. const vx = this.x, vy = this.y, vz = this.z;
  6549. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6550. // t = 2 * cross( q.xyz, v );
  6551. const tx = 2 * ( qy * vz - qz * vy );
  6552. const ty = 2 * ( qz * vx - qx * vz );
  6553. const tz = 2 * ( qx * vy - qy * vx );
  6554. // v + q.w * t + cross( q.xyz, t );
  6555. this.x = vx + qw * tx + qy * tz - qz * ty;
  6556. this.y = vy + qw * ty + qz * tx - qx * tz;
  6557. this.z = vz + qw * tz + qx * ty - qy * tx;
  6558. return this;
  6559. }
  6560. /**
  6561. * Projects this vector from world space into the camera's normalized
  6562. * device coordinate (NDC) space.
  6563. *
  6564. * @param {Camera} camera - The camera.
  6565. * @return {Vector3} A reference to this vector.
  6566. */
  6567. project( camera ) {
  6568. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  6569. }
  6570. /**
  6571. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  6572. * space into world space.
  6573. *
  6574. * @param {Camera} camera - The camera.
  6575. * @return {Vector3} A reference to this vector.
  6576. */
  6577. unproject( camera ) {
  6578. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  6579. }
  6580. /**
  6581. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  6582. * subset of the given 4x4 matrix and then normalizes the result.
  6583. *
  6584. * @param {Matrix4} m - The matrix.
  6585. * @return {Vector3} A reference to this vector.
  6586. */
  6587. transformDirection( m ) {
  6588. // input: THREE.Matrix4 affine matrix
  6589. // vector interpreted as a direction
  6590. const x = this.x, y = this.y, z = this.z;
  6591. const e = m.elements;
  6592. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6593. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6594. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6595. return this.normalize();
  6596. }
  6597. /**
  6598. * Divides this instance by the given vector.
  6599. *
  6600. * @param {Vector3} v - The vector to divide.
  6601. * @return {Vector3} A reference to this vector.
  6602. */
  6603. divide( v ) {
  6604. this.x /= v.x;
  6605. this.y /= v.y;
  6606. this.z /= v.z;
  6607. return this;
  6608. }
  6609. /**
  6610. * Divides this vector by the given scalar.
  6611. *
  6612. * @param {number} scalar - The scalar to divide.
  6613. * @return {Vector3} A reference to this vector.
  6614. */
  6615. divideScalar( scalar ) {
  6616. return this.multiplyScalar( 1 / scalar );
  6617. }
  6618. /**
  6619. * If this vector's x, y or z value is greater than the given vector's x, y or z
  6620. * value, replace that value with the corresponding min value.
  6621. *
  6622. * @param {Vector3} v - The vector.
  6623. * @return {Vector3} A reference to this vector.
  6624. */
  6625. min( v ) {
  6626. this.x = Math.min( this.x, v.x );
  6627. this.y = Math.min( this.y, v.y );
  6628. this.z = Math.min( this.z, v.z );
  6629. return this;
  6630. }
  6631. /**
  6632. * If this vector's x, y or z value is less than the given vector's x, y or z
  6633. * value, replace that value with the corresponding max value.
  6634. *
  6635. * @param {Vector3} v - The vector.
  6636. * @return {Vector3} A reference to this vector.
  6637. */
  6638. max( v ) {
  6639. this.x = Math.max( this.x, v.x );
  6640. this.y = Math.max( this.y, v.y );
  6641. this.z = Math.max( this.z, v.z );
  6642. return this;
  6643. }
  6644. /**
  6645. * If this vector's x, y or z value is greater than the max vector's x, y or z
  6646. * value, it is replaced by the corresponding value.
  6647. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  6648. * it is replaced by the corresponding value.
  6649. *
  6650. * @param {Vector3} min - The minimum x, y and z values.
  6651. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  6652. * @return {Vector3} A reference to this vector.
  6653. */
  6654. clamp( min, max ) {
  6655. // assumes min < max, componentwise
  6656. this.x = clamp( this.x, min.x, max.x );
  6657. this.y = clamp( this.y, min.y, max.y );
  6658. this.z = clamp( this.z, min.z, max.z );
  6659. return this;
  6660. }
  6661. /**
  6662. * If this vector's x, y or z values are greater than the max value, they are
  6663. * replaced by the max value.
  6664. * If this vector's x, y or z values are less than the min value, they are
  6665. * replaced by the min value.
  6666. *
  6667. * @param {number} minVal - The minimum value the components will be clamped to.
  6668. * @param {number} maxVal - The maximum value the components will be clamped to.
  6669. * @return {Vector3} A reference to this vector.
  6670. */
  6671. clampScalar( minVal, maxVal ) {
  6672. this.x = clamp( this.x, minVal, maxVal );
  6673. this.y = clamp( this.y, minVal, maxVal );
  6674. this.z = clamp( this.z, minVal, maxVal );
  6675. return this;
  6676. }
  6677. /**
  6678. * If this vector's length is greater than the max value, it is replaced by
  6679. * the max value.
  6680. * If this vector's length is less than the min value, it is replaced by the
  6681. * min value.
  6682. *
  6683. * @param {number} min - The minimum value the vector length will be clamped to.
  6684. * @param {number} max - The maximum value the vector length will be clamped to.
  6685. * @return {Vector3} A reference to this vector.
  6686. */
  6687. clampLength( min, max ) {
  6688. const length = this.length();
  6689. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6690. }
  6691. /**
  6692. * The components of this vector are rounded down to the nearest integer value.
  6693. *
  6694. * @return {Vector3} A reference to this vector.
  6695. */
  6696. floor() {
  6697. this.x = Math.floor( this.x );
  6698. this.y = Math.floor( this.y );
  6699. this.z = Math.floor( this.z );
  6700. return this;
  6701. }
  6702. /**
  6703. * The components of this vector are rounded up to the nearest integer value.
  6704. *
  6705. * @return {Vector3} A reference to this vector.
  6706. */
  6707. ceil() {
  6708. this.x = Math.ceil( this.x );
  6709. this.y = Math.ceil( this.y );
  6710. this.z = Math.ceil( this.z );
  6711. return this;
  6712. }
  6713. /**
  6714. * The components of this vector are rounded to the nearest integer value
  6715. *
  6716. * @return {Vector3} A reference to this vector.
  6717. */
  6718. round() {
  6719. this.x = Math.round( this.x );
  6720. this.y = Math.round( this.y );
  6721. this.z = Math.round( this.z );
  6722. return this;
  6723. }
  6724. /**
  6725. * The components of this vector are rounded towards zero (up if negative,
  6726. * down if positive) to an integer value.
  6727. *
  6728. * @return {Vector3} A reference to this vector.
  6729. */
  6730. roundToZero() {
  6731. this.x = Math.trunc( this.x );
  6732. this.y = Math.trunc( this.y );
  6733. this.z = Math.trunc( this.z );
  6734. return this;
  6735. }
  6736. /**
  6737. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  6738. *
  6739. * @return {Vector3} A reference to this vector.
  6740. */
  6741. negate() {
  6742. this.x = - this.x;
  6743. this.y = - this.y;
  6744. this.z = - this.z;
  6745. return this;
  6746. }
  6747. /**
  6748. * Calculates the dot product of the given vector with this instance.
  6749. *
  6750. * @param {Vector3} v - The vector to compute the dot product with.
  6751. * @return {number} The result of the dot product.
  6752. */
  6753. dot( v ) {
  6754. return this.x * v.x + this.y * v.y + this.z * v.z;
  6755. }
  6756. // TODO lengthSquared?
  6757. /**
  6758. * Computes the square of the Euclidean length (straight-line length) from
  6759. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  6760. * compare the length squared instead as it is slightly more efficient to calculate.
  6761. *
  6762. * @return {number} The square length of this vector.
  6763. */
  6764. lengthSq() {
  6765. return this.x * this.x + this.y * this.y + this.z * this.z;
  6766. }
  6767. /**
  6768. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  6769. *
  6770. * @return {number} The length of this vector.
  6771. */
  6772. length() {
  6773. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6774. }
  6775. /**
  6776. * Computes the Manhattan length of this vector.
  6777. *
  6778. * @return {number} The length of this vector.
  6779. */
  6780. manhattanLength() {
  6781. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6782. }
  6783. /**
  6784. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6785. * with the same direction as this one, but with a vector length of `1`.
  6786. *
  6787. * @return {Vector3} A reference to this vector.
  6788. */
  6789. normalize() {
  6790. return this.divideScalar( this.length() || 1 );
  6791. }
  6792. /**
  6793. * Sets this vector to a vector with the same direction as this one, but
  6794. * with the specified length.
  6795. *
  6796. * @param {number} length - The new length of this vector.
  6797. * @return {Vector3} A reference to this vector.
  6798. */
  6799. setLength( length ) {
  6800. return this.normalize().multiplyScalar( length );
  6801. }
  6802. /**
  6803. * Linearly interpolates between the given vector and this instance, where
  6804. * alpha is the percent distance along the line - alpha = 0 will be this
  6805. * vector, and alpha = 1 will be the given one.
  6806. *
  6807. * @param {Vector3} v - The vector to interpolate towards.
  6808. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6809. * @return {Vector3} A reference to this vector.
  6810. */
  6811. lerp( v, alpha ) {
  6812. this.x += ( v.x - this.x ) * alpha;
  6813. this.y += ( v.y - this.y ) * alpha;
  6814. this.z += ( v.z - this.z ) * alpha;
  6815. return this;
  6816. }
  6817. /**
  6818. * Linearly interpolates between the given vectors, where alpha is the percent
  6819. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6820. * be the second one. The result is stored in this instance.
  6821. *
  6822. * @param {Vector3} v1 - The first vector.
  6823. * @param {Vector3} v2 - The second vector.
  6824. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6825. * @return {Vector3} A reference to this vector.
  6826. */
  6827. lerpVectors( v1, v2, alpha ) {
  6828. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6829. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6830. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6831. return this;
  6832. }
  6833. /**
  6834. * Calculates the cross product of the given vector with this instance.
  6835. *
  6836. * @param {Vector3} v - The vector to compute the cross product with.
  6837. * @return {Vector3} The result of the cross product.
  6838. */
  6839. cross( v ) {
  6840. return this.crossVectors( this, v );
  6841. }
  6842. /**
  6843. * Calculates the cross product of the given vectors and stores the result
  6844. * in this instance.
  6845. *
  6846. * @param {Vector3} a - The first vector.
  6847. * @param {Vector3} b - The second vector.
  6848. * @return {Vector3} A reference to this vector.
  6849. */
  6850. crossVectors( a, b ) {
  6851. const ax = a.x, ay = a.y, az = a.z;
  6852. const bx = b.x, by = b.y, bz = b.z;
  6853. this.x = ay * bz - az * by;
  6854. this.y = az * bx - ax * bz;
  6855. this.z = ax * by - ay * bx;
  6856. return this;
  6857. }
  6858. /**
  6859. * Projects this vector onto the given one.
  6860. *
  6861. * @param {Vector3} v - The vector to project to.
  6862. * @return {Vector3} A reference to this vector.
  6863. */
  6864. projectOnVector( v ) {
  6865. const denominator = v.lengthSq();
  6866. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  6867. const scalar = v.dot( this ) / denominator;
  6868. return this.copy( v ).multiplyScalar( scalar );
  6869. }
  6870. /**
  6871. * Projects this vector onto a plane by subtracting this
  6872. * vector projected onto the plane's normal from this vector.
  6873. *
  6874. * @param {Vector3} planeNormal - The plane normal.
  6875. * @return {Vector3} A reference to this vector.
  6876. */
  6877. projectOnPlane( planeNormal ) {
  6878. _vector$c.copy( this ).projectOnVector( planeNormal );
  6879. return this.sub( _vector$c );
  6880. }
  6881. /**
  6882. * Reflects this vector off a plane orthogonal to the given normal vector.
  6883. *
  6884. * @param {Vector3} normal - The (normalized) normal vector.
  6885. * @return {Vector3} A reference to this vector.
  6886. */
  6887. reflect( normal ) {
  6888. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6889. }
  6890. /**
  6891. * Returns the angle between the given vector and this instance in radians.
  6892. *
  6893. * @param {Vector3} v - The vector to compute the angle with.
  6894. * @return {number} The angle in radians.
  6895. */
  6896. angleTo( v ) {
  6897. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  6898. if ( denominator === 0 ) return Math.PI / 2;
  6899. const theta = this.dot( v ) / denominator;
  6900. // clamp, to handle numerical problems
  6901. return Math.acos( clamp( theta, - 1, 1 ) );
  6902. }
  6903. /**
  6904. * Computes the distance from the given vector to this instance.
  6905. *
  6906. * @param {Vector3} v - The vector to compute the distance to.
  6907. * @return {number} The distance.
  6908. */
  6909. distanceTo( v ) {
  6910. return Math.sqrt( this.distanceToSquared( v ) );
  6911. }
  6912. /**
  6913. * Computes the squared distance from the given vector to this instance.
  6914. * If you are just comparing the distance with another distance, you should compare
  6915. * the distance squared instead as it is slightly more efficient to calculate.
  6916. *
  6917. * @param {Vector3} v - The vector to compute the squared distance to.
  6918. * @return {number} The squared distance.
  6919. */
  6920. distanceToSquared( v ) {
  6921. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6922. return dx * dx + dy * dy + dz * dz;
  6923. }
  6924. /**
  6925. * Computes the Manhattan distance from the given vector to this instance.
  6926. *
  6927. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  6928. * @return {number} The Manhattan distance.
  6929. */
  6930. manhattanDistanceTo( v ) {
  6931. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6932. }
  6933. /**
  6934. * Sets the vector components from the given spherical coordinates.
  6935. *
  6936. * @param {Spherical} s - The spherical coordinates.
  6937. * @return {Vector3} A reference to this vector.
  6938. */
  6939. setFromSpherical( s ) {
  6940. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  6941. }
  6942. /**
  6943. * Sets the vector components from the given spherical coordinates.
  6944. *
  6945. * @param {number} radius - The radius.
  6946. * @param {number} phi - The phi angle in radians.
  6947. * @param {number} theta - The theta angle in radians.
  6948. * @return {Vector3} A reference to this vector.
  6949. */
  6950. setFromSphericalCoords( radius, phi, theta ) {
  6951. const sinPhiRadius = Math.sin( phi ) * radius;
  6952. this.x = sinPhiRadius * Math.sin( theta );
  6953. this.y = Math.cos( phi ) * radius;
  6954. this.z = sinPhiRadius * Math.cos( theta );
  6955. return this;
  6956. }
  6957. /**
  6958. * Sets the vector components from the given cylindrical coordinates.
  6959. *
  6960. * @param {Cylindrical} c - The cylindrical coordinates.
  6961. * @return {Vector3} A reference to this vector.
  6962. */
  6963. setFromCylindrical( c ) {
  6964. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  6965. }
  6966. /**
  6967. * Sets the vector components from the given cylindrical coordinates.
  6968. *
  6969. * @param {number} radius - The radius.
  6970. * @param {number} theta - The theta angle in radians.
  6971. * @param {number} y - The y value.
  6972. * @return {Vector3} A reference to this vector.
  6973. */
  6974. setFromCylindricalCoords( radius, theta, y ) {
  6975. this.x = radius * Math.sin( theta );
  6976. this.y = y;
  6977. this.z = radius * Math.cos( theta );
  6978. return this;
  6979. }
  6980. /**
  6981. * Sets the vector components to the position elements of the
  6982. * given transformation matrix.
  6983. *
  6984. * @param {Matrix4} m - The 4x4 matrix.
  6985. * @return {Vector3} A reference to this vector.
  6986. */
  6987. setFromMatrixPosition( m ) {
  6988. const e = m.elements;
  6989. this.x = e[ 12 ];
  6990. this.y = e[ 13 ];
  6991. this.z = e[ 14 ];
  6992. return this;
  6993. }
  6994. /**
  6995. * Sets the vector components to the scale elements of the
  6996. * given transformation matrix.
  6997. *
  6998. * @param {Matrix4} m - The 4x4 matrix.
  6999. * @return {Vector3} A reference to this vector.
  7000. */
  7001. setFromMatrixScale( m ) {
  7002. const sx = this.setFromMatrixColumn( m, 0 ).length();
  7003. const sy = this.setFromMatrixColumn( m, 1 ).length();
  7004. const sz = this.setFromMatrixColumn( m, 2 ).length();
  7005. this.x = sx;
  7006. this.y = sy;
  7007. this.z = sz;
  7008. return this;
  7009. }
  7010. /**
  7011. * Sets the vector components from the specified matrix column.
  7012. *
  7013. * @param {Matrix4} m - The 4x4 matrix.
  7014. * @param {number} index - The column index.
  7015. * @return {Vector3} A reference to this vector.
  7016. */
  7017. setFromMatrixColumn( m, index ) {
  7018. return this.fromArray( m.elements, index * 4 );
  7019. }
  7020. /**
  7021. * Sets the vector components from the specified matrix column.
  7022. *
  7023. * @param {Matrix3} m - The 3x3 matrix.
  7024. * @param {number} index - The column index.
  7025. * @return {Vector3} A reference to this vector.
  7026. */
  7027. setFromMatrix3Column( m, index ) {
  7028. return this.fromArray( m.elements, index * 3 );
  7029. }
  7030. /**
  7031. * Sets the vector components from the given Euler angles.
  7032. *
  7033. * @param {Euler} e - The Euler angles to set.
  7034. * @return {Vector3} A reference to this vector.
  7035. */
  7036. setFromEuler( e ) {
  7037. this.x = e._x;
  7038. this.y = e._y;
  7039. this.z = e._z;
  7040. return this;
  7041. }
  7042. /**
  7043. * Sets the vector components from the RGB components of the
  7044. * given color.
  7045. *
  7046. * @param {Color} c - The color to set.
  7047. * @return {Vector3} A reference to this vector.
  7048. */
  7049. setFromColor( c ) {
  7050. this.x = c.r;
  7051. this.y = c.g;
  7052. this.z = c.b;
  7053. return this;
  7054. }
  7055. /**
  7056. * Returns `true` if this vector is equal with the given one.
  7057. *
  7058. * @param {Vector3} v - The vector to test for equality.
  7059. * @return {boolean} Whether this vector is equal with the given one.
  7060. */
  7061. equals( v ) {
  7062. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  7063. }
  7064. /**
  7065. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  7066. * and z value to be `array[ offset + 2 ]`.
  7067. *
  7068. * @param {Array<number>} array - An array holding the vector component values.
  7069. * @param {number} [offset=0] - The offset into the array.
  7070. * @return {Vector3} A reference to this vector.
  7071. */
  7072. fromArray( array, offset = 0 ) {
  7073. this.x = array[ offset ];
  7074. this.y = array[ offset + 1 ];
  7075. this.z = array[ offset + 2 ];
  7076. return this;
  7077. }
  7078. /**
  7079. * Writes the components of this vector to the given array. If no array is provided,
  7080. * the method returns a new instance.
  7081. *
  7082. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  7083. * @param {number} [offset=0] - Index of the first element in the array.
  7084. * @return {Array<number>} The vector components.
  7085. */
  7086. toArray( array = [], offset = 0 ) {
  7087. array[ offset ] = this.x;
  7088. array[ offset + 1 ] = this.y;
  7089. array[ offset + 2 ] = this.z;
  7090. return array;
  7091. }
  7092. /**
  7093. * Sets the components of this vector from the given buffer attribute.
  7094. *
  7095. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  7096. * @param {number} index - The index into the attribute.
  7097. * @return {Vector3} A reference to this vector.
  7098. */
  7099. fromBufferAttribute( attribute, index ) {
  7100. this.x = attribute.getX( index );
  7101. this.y = attribute.getY( index );
  7102. this.z = attribute.getZ( index );
  7103. return this;
  7104. }
  7105. /**
  7106. * Sets each component of this vector to a pseudo-random value between `0` and
  7107. * `1`, excluding `1`.
  7108. *
  7109. * @return {Vector3} A reference to this vector.
  7110. */
  7111. random() {
  7112. this.x = Math.random();
  7113. this.y = Math.random();
  7114. this.z = Math.random();
  7115. return this;
  7116. }
  7117. /**
  7118. * Sets this vector to a uniformly random point on a unit sphere.
  7119. *
  7120. * @return {Vector3} A reference to this vector.
  7121. */
  7122. randomDirection() {
  7123. // https://mathworld.wolfram.com/SpherePointPicking.html
  7124. const theta = Math.random() * Math.PI * 2;
  7125. const u = Math.random() * 2 - 1;
  7126. const c = Math.sqrt( 1 - u * u );
  7127. this.x = c * Math.cos( theta );
  7128. this.y = u;
  7129. this.z = c * Math.sin( theta );
  7130. return this;
  7131. }
  7132. *[ Symbol.iterator ]() {
  7133. yield this.x;
  7134. yield this.y;
  7135. yield this.z;
  7136. }
  7137. }
  7138. const _vector$c = /*@__PURE__*/ new Vector3();
  7139. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  7140. /**
  7141. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7142. */
  7143. class Box3 {
  7144. /**
  7145. * Constructs a new bounding box.
  7146. *
  7147. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7148. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7149. */
  7150. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7151. /**
  7152. * This flag can be used for type testing.
  7153. *
  7154. * @type {boolean}
  7155. * @readonly
  7156. * @default true
  7157. */
  7158. this.isBox3 = true;
  7159. /**
  7160. * The lower boundary of the box.
  7161. *
  7162. * @type {Vector3}
  7163. */
  7164. this.min = min;
  7165. /**
  7166. * The upper boundary of the box.
  7167. *
  7168. * @type {Vector3}
  7169. */
  7170. this.max = max;
  7171. }
  7172. /**
  7173. * Sets the lower and upper boundaries of this box.
  7174. * Please note that this method only copies the values from the given objects.
  7175. *
  7176. * @param {Vector3} min - The lower boundary of the box.
  7177. * @param {Vector3} max - The upper boundary of the box.
  7178. * @return {Box3} A reference to this bounding box.
  7179. */
  7180. set( min, max ) {
  7181. this.min.copy( min );
  7182. this.max.copy( max );
  7183. return this;
  7184. }
  7185. /**
  7186. * Sets the upper and lower bounds of this box so it encloses the position data
  7187. * in the given array.
  7188. *
  7189. * @param {Array<number>} array - An array holding 3D position data.
  7190. * @return {Box3} A reference to this bounding box.
  7191. */
  7192. setFromArray( array ) {
  7193. this.makeEmpty();
  7194. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7195. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7196. }
  7197. return this;
  7198. }
  7199. /**
  7200. * Sets the upper and lower bounds of this box so it encloses the position data
  7201. * in the given buffer attribute.
  7202. *
  7203. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7204. * @return {Box3} A reference to this bounding box.
  7205. */
  7206. setFromBufferAttribute( attribute ) {
  7207. this.makeEmpty();
  7208. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7209. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7210. }
  7211. return this;
  7212. }
  7213. /**
  7214. * Sets the upper and lower bounds of this box so it encloses the position data
  7215. * in the given array.
  7216. *
  7217. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7218. * @return {Box3} A reference to this bounding box.
  7219. */
  7220. setFromPoints( points ) {
  7221. this.makeEmpty();
  7222. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7223. this.expandByPoint( points[ i ] );
  7224. }
  7225. return this;
  7226. }
  7227. /**
  7228. * Centers this box on the given center vector and sets this box's width, height and
  7229. * depth to the given size values.
  7230. *
  7231. * @param {Vector3} center - The center of the box.
  7232. * @param {Vector3} size - The x, y and z dimensions of the box.
  7233. * @return {Box3} A reference to this bounding box.
  7234. */
  7235. setFromCenterAndSize( center, size ) {
  7236. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7237. this.min.copy( center ).sub( halfSize );
  7238. this.max.copy( center ).add( halfSize );
  7239. return this;
  7240. }
  7241. /**
  7242. * Computes the world-axis-aligned bounding box for the given 3D object
  7243. * (including its children), accounting for the object's, and children's,
  7244. * world transforms. The function may result in a larger box than strictly necessary.
  7245. *
  7246. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7247. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7248. * world-axis-aligned bounding box at the expense of more computation.
  7249. * @return {Box3} A reference to this bounding box.
  7250. */
  7251. setFromObject( object, precise = false ) {
  7252. this.makeEmpty();
  7253. return this.expandByObject( object, precise );
  7254. }
  7255. /**
  7256. * Returns a new box with copied values from this instance.
  7257. *
  7258. * @return {Box3} A clone of this instance.
  7259. */
  7260. clone() {
  7261. return new this.constructor().copy( this );
  7262. }
  7263. /**
  7264. * Copies the values of the given box to this instance.
  7265. *
  7266. * @param {Box3} box - The box to copy.
  7267. * @return {Box3} A reference to this bounding box.
  7268. */
  7269. copy( box ) {
  7270. this.min.copy( box.min );
  7271. this.max.copy( box.max );
  7272. return this;
  7273. }
  7274. /**
  7275. * Makes this box empty which means in encloses a zero space in 3D.
  7276. *
  7277. * @return {Box3} A reference to this bounding box.
  7278. */
  7279. makeEmpty() {
  7280. this.min.x = this.min.y = this.min.z = + Infinity;
  7281. this.max.x = this.max.y = this.max.z = - Infinity;
  7282. return this;
  7283. }
  7284. /**
  7285. * Returns true if this box includes zero points within its bounds.
  7286. * Note that a box with equal lower and upper bounds still includes one
  7287. * point, the one both bounds share.
  7288. *
  7289. * @return {boolean} Whether this box is empty or not.
  7290. */
  7291. isEmpty() {
  7292. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7293. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7294. }
  7295. /**
  7296. * Returns the center point of this box.
  7297. *
  7298. * @param {Vector3} target - The target vector that is used to store the method's result.
  7299. * @return {Vector3} The center point.
  7300. */
  7301. getCenter( target ) {
  7302. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7303. }
  7304. /**
  7305. * Returns the dimensions of this box.
  7306. *
  7307. * @param {Vector3} target - The target vector that is used to store the method's result.
  7308. * @return {Vector3} The size.
  7309. */
  7310. getSize( target ) {
  7311. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7312. }
  7313. /**
  7314. * Expands the boundaries of this box to include the given point.
  7315. *
  7316. * @param {Vector3} point - The point that should be included by the bounding box.
  7317. * @return {Box3} A reference to this bounding box.
  7318. */
  7319. expandByPoint( point ) {
  7320. this.min.min( point );
  7321. this.max.max( point );
  7322. return this;
  7323. }
  7324. /**
  7325. * Expands this box equilaterally by the given vector. The width of this
  7326. * box will be expanded by the x component of the vector in both
  7327. * directions. The height of this box will be expanded by the y component of
  7328. * the vector in both directions. The depth of this box will be
  7329. * expanded by the z component of the vector in both directions.
  7330. *
  7331. * @param {Vector3} vector - The vector that should expand the bounding box.
  7332. * @return {Box3} A reference to this bounding box.
  7333. */
  7334. expandByVector( vector ) {
  7335. this.min.sub( vector );
  7336. this.max.add( vector );
  7337. return this;
  7338. }
  7339. /**
  7340. * Expands each dimension of the box by the given scalar. If negative, the
  7341. * dimensions of the box will be contracted.
  7342. *
  7343. * @param {number} scalar - The scalar value that should expand the bounding box.
  7344. * @return {Box3} A reference to this bounding box.
  7345. */
  7346. expandByScalar( scalar ) {
  7347. this.min.addScalar( - scalar );
  7348. this.max.addScalar( scalar );
  7349. return this;
  7350. }
  7351. /**
  7352. * Expands the boundaries of this box to include the given 3D object and
  7353. * its children, accounting for the object's, and children's, world
  7354. * transforms. The function may result in a larger box than strictly
  7355. * necessary (unless the precise parameter is set to true).
  7356. *
  7357. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7358. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7359. * as little as necessary at the expense of more computation.
  7360. * @return {Box3} A reference to this bounding box.
  7361. */
  7362. expandByObject( object, precise = false ) {
  7363. // Computes the world-axis-aligned bounding box of an object (including its children),
  7364. // accounting for both the object's, and children's, world transforms
  7365. object.updateWorldMatrix( false, false );
  7366. const geometry = object.geometry;
  7367. if ( geometry !== undefined ) {
  7368. const positionAttribute = geometry.getAttribute( 'position' );
  7369. // precise AABB computation based on vertex data requires at least a position attribute.
  7370. // instancing isn't supported so far and uses the normal (conservative) code path.
  7371. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7372. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7373. if ( object.isMesh === true ) {
  7374. object.getVertexPosition( i, _vector$b );
  7375. } else {
  7376. _vector$b.fromBufferAttribute( positionAttribute, i );
  7377. }
  7378. _vector$b.applyMatrix4( object.matrixWorld );
  7379. this.expandByPoint( _vector$b );
  7380. }
  7381. } else {
  7382. if ( object.boundingBox !== undefined ) {
  7383. // object-level bounding box
  7384. if ( object.boundingBox === null ) {
  7385. object.computeBoundingBox();
  7386. }
  7387. _box$4.copy( object.boundingBox );
  7388. } else {
  7389. // geometry-level bounding box
  7390. if ( geometry.boundingBox === null ) {
  7391. geometry.computeBoundingBox();
  7392. }
  7393. _box$4.copy( geometry.boundingBox );
  7394. }
  7395. _box$4.applyMatrix4( object.matrixWorld );
  7396. this.union( _box$4 );
  7397. }
  7398. }
  7399. const children = object.children;
  7400. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7401. this.expandByObject( children[ i ], precise );
  7402. }
  7403. return this;
  7404. }
  7405. /**
  7406. * Returns `true` if the given point lies within or on the boundaries of this box.
  7407. *
  7408. * @param {Vector3} point - The point to test.
  7409. * @return {boolean} Whether the bounding box contains the given point or not.
  7410. */
  7411. containsPoint( point ) {
  7412. return point.x >= this.min.x && point.x <= this.max.x &&
  7413. point.y >= this.min.y && point.y <= this.max.y &&
  7414. point.z >= this.min.z && point.z <= this.max.z;
  7415. }
  7416. /**
  7417. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7418. * If this box and the given one are identical, this function also returns `true`.
  7419. *
  7420. * @param {Box3} box - The bounding box to test.
  7421. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7422. */
  7423. containsBox( box ) {
  7424. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7425. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7426. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7427. }
  7428. /**
  7429. * Returns a point as a proportion of this box's width, height and depth.
  7430. *
  7431. * @param {Vector3} point - A point in 3D space.
  7432. * @param {Vector3} target - The target vector that is used to store the method's result.
  7433. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7434. */
  7435. getParameter( point, target ) {
  7436. // This can potentially have a divide by zero if the box
  7437. // has a size dimension of 0.
  7438. return target.set(
  7439. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7440. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7441. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7442. );
  7443. }
  7444. /**
  7445. * Returns `true` if the given bounding box intersects with this bounding box.
  7446. *
  7447. * @param {Box3} box - The bounding box to test.
  7448. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7449. */
  7450. intersectsBox( box ) {
  7451. // using 6 splitting planes to rule out intersections.
  7452. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7453. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7454. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7455. }
  7456. /**
  7457. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7458. *
  7459. * @param {Sphere} sphere - The bounding sphere to test.
  7460. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7461. */
  7462. intersectsSphere( sphere ) {
  7463. // Find the point on the AABB closest to the sphere center.
  7464. this.clampPoint( sphere.center, _vector$b );
  7465. // If that point is inside the sphere, the AABB and sphere intersect.
  7466. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7467. }
  7468. /**
  7469. * Returns `true` if the given plane intersects with this bounding box.
  7470. *
  7471. * @param {Plane} plane - The plane to test.
  7472. * @return {boolean} Whether the given plane intersects with this bounding box.
  7473. */
  7474. intersectsPlane( plane ) {
  7475. // We compute the minimum and maximum dot product values. If those values
  7476. // are on the same side (back or front) of the plane, then there is no intersection.
  7477. let min, max;
  7478. if ( plane.normal.x > 0 ) {
  7479. min = plane.normal.x * this.min.x;
  7480. max = plane.normal.x * this.max.x;
  7481. } else {
  7482. min = plane.normal.x * this.max.x;
  7483. max = plane.normal.x * this.min.x;
  7484. }
  7485. if ( plane.normal.y > 0 ) {
  7486. min += plane.normal.y * this.min.y;
  7487. max += plane.normal.y * this.max.y;
  7488. } else {
  7489. min += plane.normal.y * this.max.y;
  7490. max += plane.normal.y * this.min.y;
  7491. }
  7492. if ( plane.normal.z > 0 ) {
  7493. min += plane.normal.z * this.min.z;
  7494. max += plane.normal.z * this.max.z;
  7495. } else {
  7496. min += plane.normal.z * this.max.z;
  7497. max += plane.normal.z * this.min.z;
  7498. }
  7499. return ( min <= - plane.constant && max >= - plane.constant );
  7500. }
  7501. /**
  7502. * Returns `true` if the given triangle intersects with this bounding box.
  7503. *
  7504. * @param {Triangle} triangle - The triangle to test.
  7505. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7506. */
  7507. intersectsTriangle( triangle ) {
  7508. if ( this.isEmpty() ) {
  7509. return false;
  7510. }
  7511. // compute box center and extents
  7512. this.getCenter( _center );
  7513. _extents.subVectors( this.max, _center );
  7514. // translate triangle to aabb origin
  7515. _v0$3.subVectors( triangle.a, _center );
  7516. _v1$7.subVectors( triangle.b, _center );
  7517. _v2$4.subVectors( triangle.c, _center );
  7518. // compute edge vectors for triangle
  7519. _f0.subVectors( _v1$7, _v0$3 );
  7520. _f1.subVectors( _v2$4, _v1$7 );
  7521. _f2.subVectors( _v0$3, _v2$4 );
  7522. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7523. // 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
  7524. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7525. let axes = [
  7526. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7527. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7528. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7529. ];
  7530. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7531. return false;
  7532. }
  7533. // test 3 face normals from the aabb
  7534. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7535. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7536. return false;
  7537. }
  7538. // finally testing the face normal of the triangle
  7539. // use already existing triangle edge vectors here
  7540. _triangleNormal.crossVectors( _f0, _f1 );
  7541. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7542. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7543. }
  7544. /**
  7545. * Clamps the given point within the bounds of this box.
  7546. *
  7547. * @param {Vector3} point - The point to clamp.
  7548. * @param {Vector3} target - The target vector that is used to store the method's result.
  7549. * @return {Vector3} The clamped point.
  7550. */
  7551. clampPoint( point, target ) {
  7552. return target.copy( point ).clamp( this.min, this.max );
  7553. }
  7554. /**
  7555. * Returns the euclidean distance from any edge of this box to the specified point. If
  7556. * the given point lies inside of this box, the distance will be `0`.
  7557. *
  7558. * @param {Vector3} point - The point to compute the distance to.
  7559. * @return {number} The euclidean distance.
  7560. */
  7561. distanceToPoint( point ) {
  7562. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7563. }
  7564. /**
  7565. * Returns a bounding sphere that encloses this bounding box.
  7566. *
  7567. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7568. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7569. */
  7570. getBoundingSphere( target ) {
  7571. if ( this.isEmpty() ) {
  7572. target.makeEmpty();
  7573. } else {
  7574. this.getCenter( target.center );
  7575. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7576. }
  7577. return target;
  7578. }
  7579. /**
  7580. * Computes the intersection of this bounding box and the given one, setting the upper
  7581. * bound of this box to the lesser of the two boxes' upper bounds and the
  7582. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7583. * there's no overlap, makes this box empty.
  7584. *
  7585. * @param {Box3} box - The bounding box to intersect with.
  7586. * @return {Box3} A reference to this bounding box.
  7587. */
  7588. intersect( box ) {
  7589. this.min.max( box.min );
  7590. this.max.min( box.max );
  7591. // 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.
  7592. if ( this.isEmpty() ) this.makeEmpty();
  7593. return this;
  7594. }
  7595. /**
  7596. * Computes the union of this box and another and the given one, setting the upper
  7597. * bound of this box to the greater of the two boxes' upper bounds and the
  7598. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7599. *
  7600. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7601. * @return {Box3} A reference to this bounding box.
  7602. */
  7603. union( box ) {
  7604. this.min.min( box.min );
  7605. this.max.max( box.max );
  7606. return this;
  7607. }
  7608. /**
  7609. * Transforms this bounding box by the given 4x4 transformation matrix.
  7610. *
  7611. * @param {Matrix4} matrix - The transformation matrix.
  7612. * @return {Box3} A reference to this bounding box.
  7613. */
  7614. applyMatrix4( matrix ) {
  7615. // transform of empty box is an empty box.
  7616. if ( this.isEmpty() ) return this;
  7617. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7618. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7619. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7620. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7621. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7622. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7623. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7624. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7625. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7626. this.setFromPoints( _points );
  7627. return this;
  7628. }
  7629. /**
  7630. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7631. * effectively moving it in 3D space.
  7632. *
  7633. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7634. * @return {Box3} A reference to this bounding box.
  7635. */
  7636. translate( offset ) {
  7637. this.min.add( offset );
  7638. this.max.add( offset );
  7639. return this;
  7640. }
  7641. /**
  7642. * Returns `true` if this bounding box is equal with the given one.
  7643. *
  7644. * @param {Box3} box - The box to test for equality.
  7645. * @return {boolean} Whether this bounding box is equal with the given one.
  7646. */
  7647. equals( box ) {
  7648. return box.min.equals( this.min ) && box.max.equals( this.max );
  7649. }
  7650. }
  7651. const _points = [
  7652. /*@__PURE__*/ new Vector3(),
  7653. /*@__PURE__*/ new Vector3(),
  7654. /*@__PURE__*/ new Vector3(),
  7655. /*@__PURE__*/ new Vector3(),
  7656. /*@__PURE__*/ new Vector3(),
  7657. /*@__PURE__*/ new Vector3(),
  7658. /*@__PURE__*/ new Vector3(),
  7659. /*@__PURE__*/ new Vector3()
  7660. ];
  7661. const _vector$b = /*@__PURE__*/ new Vector3();
  7662. const _box$4 = /*@__PURE__*/ new Box3();
  7663. // triangle centered vertices
  7664. const _v0$3 = /*@__PURE__*/ new Vector3();
  7665. const _v1$7 = /*@__PURE__*/ new Vector3();
  7666. const _v2$4 = /*@__PURE__*/ new Vector3();
  7667. // triangle edge vectors
  7668. const _f0 = /*@__PURE__*/ new Vector3();
  7669. const _f1 = /*@__PURE__*/ new Vector3();
  7670. const _f2 = /*@__PURE__*/ new Vector3();
  7671. const _center = /*@__PURE__*/ new Vector3();
  7672. const _extents = /*@__PURE__*/ new Vector3();
  7673. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7674. const _testAxis = /*@__PURE__*/ new Vector3();
  7675. function satForAxes( axes, v0, v1, v2, extents ) {
  7676. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7677. _testAxis.fromArray( axes, i );
  7678. // project the aabb onto the separating axis
  7679. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7680. // project all 3 vertices of the triangle onto the separating axis
  7681. const p0 = v0.dot( _testAxis );
  7682. const p1 = v1.dot( _testAxis );
  7683. const p2 = v2.dot( _testAxis );
  7684. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7685. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7686. // points of the projected triangle are outside the projected half-length of the aabb
  7687. // the axis is separating and we can exit
  7688. return false;
  7689. }
  7690. }
  7691. return true;
  7692. }
  7693. const _box$3 = /*@__PURE__*/ new Box3();
  7694. const _v1$6 = /*@__PURE__*/ new Vector3();
  7695. const _v2$3 = /*@__PURE__*/ new Vector3();
  7696. /**
  7697. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7698. * used as a Bounding Sphere for 3D objects.
  7699. */
  7700. class Sphere {
  7701. /**
  7702. * Constructs a new sphere.
  7703. *
  7704. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7705. * @param {number} [radius=-1] - The radius of the sphere.
  7706. */
  7707. constructor( center = new Vector3(), radius = - 1 ) {
  7708. /**
  7709. * This flag can be used for type testing.
  7710. *
  7711. * @type {boolean}
  7712. * @readonly
  7713. * @default true
  7714. */
  7715. this.isSphere = true;
  7716. /**
  7717. * The center of the sphere
  7718. *
  7719. * @type {Vector3}
  7720. */
  7721. this.center = center;
  7722. /**
  7723. * The radius of the sphere.
  7724. *
  7725. * @type {number}
  7726. */
  7727. this.radius = radius;
  7728. }
  7729. /**
  7730. * Sets the sphere's components by copying the given values.
  7731. *
  7732. * @param {Vector3} center - The center.
  7733. * @param {number} radius - The radius.
  7734. * @return {Sphere} A reference to this sphere.
  7735. */
  7736. set( center, radius ) {
  7737. this.center.copy( center );
  7738. this.radius = radius;
  7739. return this;
  7740. }
  7741. /**
  7742. * Computes the minimum bounding sphere for list of points.
  7743. * If the optional center point is given, it is used as the sphere's
  7744. * center. Otherwise, the center of the axis-aligned bounding box
  7745. * encompassing the points is calculated.
  7746. *
  7747. * @param {Array<Vector3>} points - A list of points in 3D space.
  7748. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7749. * @return {Sphere} A reference to this sphere.
  7750. */
  7751. setFromPoints( points, optionalCenter ) {
  7752. const center = this.center;
  7753. if ( optionalCenter !== undefined ) {
  7754. center.copy( optionalCenter );
  7755. } else {
  7756. _box$3.setFromPoints( points ).getCenter( center );
  7757. }
  7758. let maxRadiusSq = 0;
  7759. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7760. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7761. }
  7762. this.radius = Math.sqrt( maxRadiusSq );
  7763. return this;
  7764. }
  7765. /**
  7766. * Copies the values of the given sphere to this instance.
  7767. *
  7768. * @param {Sphere} sphere - The sphere to copy.
  7769. * @return {Sphere} A reference to this sphere.
  7770. */
  7771. copy( sphere ) {
  7772. this.center.copy( sphere.center );
  7773. this.radius = sphere.radius;
  7774. return this;
  7775. }
  7776. /**
  7777. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7778. *
  7779. * Spheres with a radius of `0` contain only their center point and are not
  7780. * considered to be empty.
  7781. *
  7782. * @return {boolean} Whether this sphere is empty or not.
  7783. */
  7784. isEmpty() {
  7785. return ( this.radius < 0 );
  7786. }
  7787. /**
  7788. * Makes this sphere empty which means in encloses a zero space in 3D.
  7789. *
  7790. * @return {Sphere} A reference to this sphere.
  7791. */
  7792. makeEmpty() {
  7793. this.center.set( 0, 0, 0 );
  7794. this.radius = - 1;
  7795. return this;
  7796. }
  7797. /**
  7798. * Returns `true` if this sphere contains the given point inclusive of
  7799. * the surface of the sphere.
  7800. *
  7801. * @param {Vector3} point - The point to check.
  7802. * @return {boolean} Whether this sphere contains the given point or not.
  7803. */
  7804. containsPoint( point ) {
  7805. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7806. }
  7807. /**
  7808. * Returns the closest distance from the boundary of the sphere to the
  7809. * given point. If the sphere contains the point, the distance will
  7810. * be negative.
  7811. *
  7812. * @param {Vector3} point - The point to compute the distance to.
  7813. * @return {number} The distance to the point.
  7814. */
  7815. distanceToPoint( point ) {
  7816. return ( point.distanceTo( this.center ) - this.radius );
  7817. }
  7818. /**
  7819. * Returns `true` if this sphere intersects with the given one.
  7820. *
  7821. * @param {Sphere} sphere - The sphere to test.
  7822. * @return {boolean} Whether this sphere intersects with the given one or not.
  7823. */
  7824. intersectsSphere( sphere ) {
  7825. const radiusSum = this.radius + sphere.radius;
  7826. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7827. }
  7828. /**
  7829. * Returns `true` if this sphere intersects with the given box.
  7830. *
  7831. * @param {Box3} box - The box to test.
  7832. * @return {boolean} Whether this sphere intersects with the given box or not.
  7833. */
  7834. intersectsBox( box ) {
  7835. return box.intersectsSphere( this );
  7836. }
  7837. /**
  7838. * Returns `true` if this sphere intersects with the given plane.
  7839. *
  7840. * @param {Plane} plane - The plane to test.
  7841. * @return {boolean} Whether this sphere intersects with the given plane or not.
  7842. */
  7843. intersectsPlane( plane ) {
  7844. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  7845. }
  7846. /**
  7847. * Clamps a point within the sphere. If the point is outside the sphere, it
  7848. * will clamp it to the closest point on the edge of the sphere. Points
  7849. * already inside the sphere will not be affected.
  7850. *
  7851. * @param {Vector3} point - The plane to clamp.
  7852. * @param {Vector3} target - The target vector that is used to store the method's result.
  7853. * @return {Vector3} The clamped point.
  7854. */
  7855. clampPoint( point, target ) {
  7856. const deltaLengthSq = this.center.distanceToSquared( point );
  7857. target.copy( point );
  7858. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  7859. target.sub( this.center ).normalize();
  7860. target.multiplyScalar( this.radius ).add( this.center );
  7861. }
  7862. return target;
  7863. }
  7864. /**
  7865. * Returns a bounding box that encloses this sphere.
  7866. *
  7867. * @param {Box3} target - The target box that is used to store the method's result.
  7868. * @return {Box3} The bounding box that encloses this sphere.
  7869. */
  7870. getBoundingBox( target ) {
  7871. if ( this.isEmpty() ) {
  7872. // Empty sphere produces empty bounding box
  7873. target.makeEmpty();
  7874. return target;
  7875. }
  7876. target.set( this.center, this.center );
  7877. target.expandByScalar( this.radius );
  7878. return target;
  7879. }
  7880. /**
  7881. * Transforms this sphere with the given 4x4 transformation matrix.
  7882. *
  7883. * @param {Matrix4} matrix - The transformation matrix.
  7884. * @return {Sphere} A reference to this sphere.
  7885. */
  7886. applyMatrix4( matrix ) {
  7887. this.center.applyMatrix4( matrix );
  7888. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  7889. return this;
  7890. }
  7891. /**
  7892. * Translates the sphere's center by the given offset.
  7893. *
  7894. * @param {Vector3} offset - The offset.
  7895. * @return {Sphere} A reference to this sphere.
  7896. */
  7897. translate( offset ) {
  7898. this.center.add( offset );
  7899. return this;
  7900. }
  7901. /**
  7902. * Expands the boundaries of this sphere to include the given point.
  7903. *
  7904. * @param {Vector3} point - The point to include.
  7905. * @return {Sphere} A reference to this sphere.
  7906. */
  7907. expandByPoint( point ) {
  7908. if ( this.isEmpty() ) {
  7909. this.center.copy( point );
  7910. this.radius = 0;
  7911. return this;
  7912. }
  7913. _v1$6.subVectors( point, this.center );
  7914. const lengthSq = _v1$6.lengthSq();
  7915. if ( lengthSq > ( this.radius * this.radius ) ) {
  7916. // calculate the minimal sphere
  7917. const length = Math.sqrt( lengthSq );
  7918. const delta = ( length - this.radius ) * 0.5;
  7919. this.center.addScaledVector( _v1$6, delta / length );
  7920. this.radius += delta;
  7921. }
  7922. return this;
  7923. }
  7924. /**
  7925. * Expands this sphere to enclose both the original sphere and the given sphere.
  7926. *
  7927. * @param {Sphere} sphere - The sphere to include.
  7928. * @return {Sphere} A reference to this sphere.
  7929. */
  7930. union( sphere ) {
  7931. if ( sphere.isEmpty() ) {
  7932. return this;
  7933. }
  7934. if ( this.isEmpty() ) {
  7935. this.copy( sphere );
  7936. return this;
  7937. }
  7938. if ( this.center.equals( sphere.center ) === true ) {
  7939. this.radius = Math.max( this.radius, sphere.radius );
  7940. } else {
  7941. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  7942. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  7943. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  7944. }
  7945. return this;
  7946. }
  7947. /**
  7948. * Returns `true` if this sphere is equal with the given one.
  7949. *
  7950. * @param {Sphere} sphere - The sphere to test for equality.
  7951. * @return {boolean} Whether this bounding sphere is equal with the given one.
  7952. */
  7953. equals( sphere ) {
  7954. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  7955. }
  7956. /**
  7957. * Returns a new sphere with copied values from this instance.
  7958. *
  7959. * @return {Sphere} A clone of this instance.
  7960. */
  7961. clone() {
  7962. return new this.constructor().copy( this );
  7963. }
  7964. }
  7965. const _vector$a = /*@__PURE__*/ new Vector3();
  7966. const _segCenter = /*@__PURE__*/ new Vector3();
  7967. const _segDir = /*@__PURE__*/ new Vector3();
  7968. const _diff = /*@__PURE__*/ new Vector3();
  7969. const _edge1 = /*@__PURE__*/ new Vector3();
  7970. const _edge2 = /*@__PURE__*/ new Vector3();
  7971. const _normal$1 = /*@__PURE__*/ new Vector3();
  7972. /**
  7973. * A ray that emits from an origin in a certain direction. The class is used by
  7974. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  7975. * mouse picking (working out what objects in the 3D space the mouse is over)
  7976. * amongst other things.
  7977. */
  7978. class Ray {
  7979. /**
  7980. * Constructs a new ray.
  7981. *
  7982. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  7983. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  7984. */
  7985. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  7986. /**
  7987. * The origin of the ray.
  7988. *
  7989. * @type {Vector3}
  7990. */
  7991. this.origin = origin;
  7992. /**
  7993. * The (normalized) direction of the ray.
  7994. *
  7995. * @type {Vector3}
  7996. */
  7997. this.direction = direction;
  7998. }
  7999. /**
  8000. * Sets the ray's components by copying the given values.
  8001. *
  8002. * @param {Vector3} origin - The origin.
  8003. * @param {Vector3} direction - The direction.
  8004. * @return {Ray} A reference to this ray.
  8005. */
  8006. set( origin, direction ) {
  8007. this.origin.copy( origin );
  8008. this.direction.copy( direction );
  8009. return this;
  8010. }
  8011. /**
  8012. * Copies the values of the given ray to this instance.
  8013. *
  8014. * @param {Ray} ray - The ray to copy.
  8015. * @return {Ray} A reference to this ray.
  8016. */
  8017. copy( ray ) {
  8018. this.origin.copy( ray.origin );
  8019. this.direction.copy( ray.direction );
  8020. return this;
  8021. }
  8022. /**
  8023. * Returns a vector that is located at a given distance along this ray.
  8024. *
  8025. * @param {number} t - The distance along the ray to retrieve a position for.
  8026. * @param {Vector3} target - The target vector that is used to store the method's result.
  8027. * @return {Vector3} A position on the ray.
  8028. */
  8029. at( t, target ) {
  8030. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8031. }
  8032. /**
  8033. * Adjusts the direction of the ray to point at the given vector in world space.
  8034. *
  8035. * @param {Vector3} v - The target position.
  8036. * @return {Ray} A reference to this ray.
  8037. */
  8038. lookAt( v ) {
  8039. this.direction.copy( v ).sub( this.origin ).normalize();
  8040. return this;
  8041. }
  8042. /**
  8043. * Shift the origin of this ray along its direction by the given distance.
  8044. *
  8045. * @param {number} t - The distance along the ray to interpolate.
  8046. * @return {Ray} A reference to this ray.
  8047. */
  8048. recast( t ) {
  8049. this.origin.copy( this.at( t, _vector$a ) );
  8050. return this;
  8051. }
  8052. /**
  8053. * Returns the point along this ray that is closest to the given point.
  8054. *
  8055. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8056. * @param {Vector3} target - The target vector that is used to store the method's result.
  8057. * @return {Vector3} The closest point on this ray.
  8058. */
  8059. closestPointToPoint( point, target ) {
  8060. target.subVectors( point, this.origin );
  8061. const directionDistance = target.dot( this.direction );
  8062. if ( directionDistance < 0 ) {
  8063. return target.copy( this.origin );
  8064. }
  8065. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8066. }
  8067. /**
  8068. * Returns the distance of the closest approach between this ray and the given point.
  8069. *
  8070. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8071. * @return {number} The distance.
  8072. */
  8073. distanceToPoint( point ) {
  8074. return Math.sqrt( this.distanceSqToPoint( point ) );
  8075. }
  8076. /**
  8077. * Returns the squared distance of the closest approach between this ray and the given point.
  8078. *
  8079. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8080. * @return {number} The squared distance.
  8081. */
  8082. distanceSqToPoint( point ) {
  8083. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8084. // point behind the ray
  8085. if ( directionDistance < 0 ) {
  8086. return this.origin.distanceToSquared( point );
  8087. }
  8088. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8089. return _vector$a.distanceToSquared( point );
  8090. }
  8091. /**
  8092. * Returns the squared distance between this ray and the given line segment.
  8093. *
  8094. * @param {Vector3} v0 - The start point of the line segment.
  8095. * @param {Vector3} v1 - The end point of the line segment.
  8096. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8097. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8098. * @return {number} The squared distance.
  8099. */
  8100. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8101. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8102. // It returns the min distance between the ray and the segment
  8103. // defined by v0 and v1
  8104. // It can also set two optional targets :
  8105. // - The closest point on the ray
  8106. // - The closest point on the segment
  8107. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8108. _segDir.copy( v1 ).sub( v0 ).normalize();
  8109. _diff.copy( this.origin ).sub( _segCenter );
  8110. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8111. const a01 = - this.direction.dot( _segDir );
  8112. const b0 = _diff.dot( this.direction );
  8113. const b1 = - _diff.dot( _segDir );
  8114. const c = _diff.lengthSq();
  8115. const det = Math.abs( 1 - a01 * a01 );
  8116. let s0, s1, sqrDist, extDet;
  8117. if ( det > 0 ) {
  8118. // The ray and segment are not parallel.
  8119. s0 = a01 * b1 - b0;
  8120. s1 = a01 * b0 - b1;
  8121. extDet = segExtent * det;
  8122. if ( s0 >= 0 ) {
  8123. if ( s1 >= - extDet ) {
  8124. if ( s1 <= extDet ) {
  8125. // region 0
  8126. // Minimum at interior points of ray and segment.
  8127. const invDet = 1 / det;
  8128. s0 *= invDet;
  8129. s1 *= invDet;
  8130. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8131. } else {
  8132. // region 1
  8133. s1 = segExtent;
  8134. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8135. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8136. }
  8137. } else {
  8138. // region 5
  8139. s1 = - segExtent;
  8140. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8141. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8142. }
  8143. } else {
  8144. if ( s1 <= - extDet ) {
  8145. // region 4
  8146. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8147. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8148. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8149. } else if ( s1 <= extDet ) {
  8150. // region 3
  8151. s0 = 0;
  8152. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8153. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8154. } else {
  8155. // region 2
  8156. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8157. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8158. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8159. }
  8160. }
  8161. } else {
  8162. // Ray and segment are parallel.
  8163. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8164. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8165. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8166. }
  8167. if ( optionalPointOnRay ) {
  8168. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8169. }
  8170. if ( optionalPointOnSegment ) {
  8171. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8172. }
  8173. return sqrDist;
  8174. }
  8175. /**
  8176. * Intersects this ray with the given sphere, returning the intersection
  8177. * point or `null` if there is no intersection.
  8178. *
  8179. * @param {Sphere} sphere - The sphere to intersect.
  8180. * @param {Vector3} target - The target vector that is used to store the method's result.
  8181. * @return {?Vector3} The intersection point.
  8182. */
  8183. intersectSphere( sphere, target ) {
  8184. _vector$a.subVectors( sphere.center, this.origin );
  8185. const tca = _vector$a.dot( this.direction );
  8186. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8187. const radius2 = sphere.radius * sphere.radius;
  8188. if ( d2 > radius2 ) return null;
  8189. const thc = Math.sqrt( radius2 - d2 );
  8190. // t0 = first intersect point - entrance on front of sphere
  8191. const t0 = tca - thc;
  8192. // t1 = second intersect point - exit point on back of sphere
  8193. const t1 = tca + thc;
  8194. // test to see if t1 is behind the ray - if so, return null
  8195. if ( t1 < 0 ) return null;
  8196. // test to see if t0 is behind the ray:
  8197. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8198. // in order to always return an intersect point that is in front of the ray.
  8199. if ( t0 < 0 ) return this.at( t1, target );
  8200. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8201. return this.at( t0, target );
  8202. }
  8203. /**
  8204. * Returns `true` if this ray intersects with the given sphere.
  8205. *
  8206. * @param {Sphere} sphere - The sphere to intersect.
  8207. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8208. */
  8209. intersectsSphere( sphere ) {
  8210. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8211. }
  8212. /**
  8213. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8214. * does not intersect with the plane.
  8215. *
  8216. * @param {Plane} plane - The plane to compute the distance to.
  8217. * @return {?number} Whether this ray intersects with the given sphere or not.
  8218. */
  8219. distanceToPlane( plane ) {
  8220. const denominator = plane.normal.dot( this.direction );
  8221. if ( denominator === 0 ) {
  8222. // line is coplanar, return origin
  8223. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8224. return 0;
  8225. }
  8226. // Null is preferable to undefined since undefined means.... it is undefined
  8227. return null;
  8228. }
  8229. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8230. // Return if the ray never intersects the plane
  8231. return t >= 0 ? t : null;
  8232. }
  8233. /**
  8234. * Intersects this ray with the given plane, returning the intersection
  8235. * point or `null` if there is no intersection.
  8236. *
  8237. * @param {Plane} plane - The plane to intersect.
  8238. * @param {Vector3} target - The target vector that is used to store the method's result.
  8239. * @return {?Vector3} The intersection point.
  8240. */
  8241. intersectPlane( plane, target ) {
  8242. const t = this.distanceToPlane( plane );
  8243. if ( t === null ) {
  8244. return null;
  8245. }
  8246. return this.at( t, target );
  8247. }
  8248. /**
  8249. * Returns `true` if this ray intersects with the given plane.
  8250. *
  8251. * @param {Plane} plane - The plane to intersect.
  8252. * @return {boolean} Whether this ray intersects with the given plane or not.
  8253. */
  8254. intersectsPlane( plane ) {
  8255. // check if the ray lies on the plane first
  8256. const distToPoint = plane.distanceToPoint( this.origin );
  8257. if ( distToPoint === 0 ) {
  8258. return true;
  8259. }
  8260. const denominator = plane.normal.dot( this.direction );
  8261. if ( denominator * distToPoint < 0 ) {
  8262. return true;
  8263. }
  8264. // ray origin is behind the plane (and is pointing behind it)
  8265. return false;
  8266. }
  8267. /**
  8268. * Intersects this ray with the given bounding box, returning the intersection
  8269. * point or `null` if there is no intersection.
  8270. *
  8271. * @param {Box3} box - The box to intersect.
  8272. * @param {Vector3} target - The target vector that is used to store the method's result.
  8273. * @return {?Vector3} The intersection point.
  8274. */
  8275. intersectBox( box, target ) {
  8276. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8277. const invdirx = 1 / this.direction.x,
  8278. invdiry = 1 / this.direction.y,
  8279. invdirz = 1 / this.direction.z;
  8280. const origin = this.origin;
  8281. if ( invdirx >= 0 ) {
  8282. tmin = ( box.min.x - origin.x ) * invdirx;
  8283. tmax = ( box.max.x - origin.x ) * invdirx;
  8284. } else {
  8285. tmin = ( box.max.x - origin.x ) * invdirx;
  8286. tmax = ( box.min.x - origin.x ) * invdirx;
  8287. }
  8288. if ( invdiry >= 0 ) {
  8289. tymin = ( box.min.y - origin.y ) * invdiry;
  8290. tymax = ( box.max.y - origin.y ) * invdiry;
  8291. } else {
  8292. tymin = ( box.max.y - origin.y ) * invdiry;
  8293. tymax = ( box.min.y - origin.y ) * invdiry;
  8294. }
  8295. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8296. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8297. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8298. if ( invdirz >= 0 ) {
  8299. tzmin = ( box.min.z - origin.z ) * invdirz;
  8300. tzmax = ( box.max.z - origin.z ) * invdirz;
  8301. } else {
  8302. tzmin = ( box.max.z - origin.z ) * invdirz;
  8303. tzmax = ( box.min.z - origin.z ) * invdirz;
  8304. }
  8305. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8306. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8307. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8308. //return point closest to the ray (positive side)
  8309. if ( tmax < 0 ) return null;
  8310. return this.at( tmin >= 0 ? tmin : tmax, target );
  8311. }
  8312. /**
  8313. * Returns `true` if this ray intersects with the given box.
  8314. *
  8315. * @param {Box3} box - The box to intersect.
  8316. * @return {boolean} Whether this ray intersects with the given box or not.
  8317. */
  8318. intersectsBox( box ) {
  8319. return this.intersectBox( box, _vector$a ) !== null;
  8320. }
  8321. /**
  8322. * Intersects this ray with the given triangle, returning the intersection
  8323. * point or `null` if there is no intersection.
  8324. *
  8325. * @param {Vector3} a - The first vertex of the triangle.
  8326. * @param {Vector3} b - The second vertex of the triangle.
  8327. * @param {Vector3} c - The third vertex of the triangle.
  8328. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8329. * @param {Vector3} target - The target vector that is used to store the method's result.
  8330. * @return {?Vector3} The intersection point.
  8331. */
  8332. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8333. // Compute the offset origin, edges, and normal.
  8334. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8335. _edge1.subVectors( b, a );
  8336. _edge2.subVectors( c, a );
  8337. _normal$1.crossVectors( _edge1, _edge2 );
  8338. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8339. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8340. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8341. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8342. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8343. let DdN = this.direction.dot( _normal$1 );
  8344. let sign;
  8345. if ( DdN > 0 ) {
  8346. if ( backfaceCulling ) return null;
  8347. sign = 1;
  8348. } else if ( DdN < 0 ) {
  8349. sign = - 1;
  8350. DdN = - DdN;
  8351. } else {
  8352. return null;
  8353. }
  8354. _diff.subVectors( this.origin, a );
  8355. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8356. // b1 < 0, no intersection
  8357. if ( DdQxE2 < 0 ) {
  8358. return null;
  8359. }
  8360. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8361. // b2 < 0, no intersection
  8362. if ( DdE1xQ < 0 ) {
  8363. return null;
  8364. }
  8365. // b1+b2 > 1, no intersection
  8366. if ( DdQxE2 + DdE1xQ > DdN ) {
  8367. return null;
  8368. }
  8369. // Line intersects triangle, check if ray does.
  8370. const QdN = - sign * _diff.dot( _normal$1 );
  8371. // t < 0, no intersection
  8372. if ( QdN < 0 ) {
  8373. return null;
  8374. }
  8375. // Ray intersects triangle.
  8376. return this.at( QdN / DdN, target );
  8377. }
  8378. /**
  8379. * Transforms this ray with the given 4x4 transformation matrix.
  8380. *
  8381. * @param {Matrix4} matrix4 - The transformation matrix.
  8382. * @return {Ray} A reference to this ray.
  8383. */
  8384. applyMatrix4( matrix4 ) {
  8385. this.origin.applyMatrix4( matrix4 );
  8386. this.direction.transformDirection( matrix4 );
  8387. return this;
  8388. }
  8389. /**
  8390. * Returns `true` if this ray is equal with the given one.
  8391. *
  8392. * @param {Ray} ray - The ray to test for equality.
  8393. * @return {boolean} Whether this ray is equal with the given one.
  8394. */
  8395. equals( ray ) {
  8396. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8397. }
  8398. /**
  8399. * Returns a new ray with copied values from this instance.
  8400. *
  8401. * @return {Ray} A clone of this instance.
  8402. */
  8403. clone() {
  8404. return new this.constructor().copy( this );
  8405. }
  8406. }
  8407. /**
  8408. * Represents a 4x4 matrix.
  8409. *
  8410. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8411. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial]{@link https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices}
  8412. *
  8413. * This allows a 3D vector representing a point in 3D space to undergo
  8414. * transformations such as translation, rotation, shear, scale, reflection,
  8415. * orthogonal or perspective projection and so on, by being multiplied by the
  8416. * matrix. This is known as `applying` the matrix to the vector.
  8417. *
  8418. * A Note on Row-Major and Column-Major Ordering:
  8419. *
  8420. * The constructor and {@link Matrix3#set} method take arguments in
  8421. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8422. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8423. * This means that calling:
  8424. * ```js
  8425. * const m = new THREE.Matrix4();
  8426. * m.set( 11, 12, 13, 14,
  8427. * 21, 22, 23, 24,
  8428. * 31, 32, 33, 34,
  8429. * 41, 42, 43, 44 );
  8430. * ```
  8431. * will result in the elements array containing:
  8432. * ```js
  8433. * m.elements = [ 11, 21, 31, 41,
  8434. * 12, 22, 32, 42,
  8435. * 13, 23, 33, 43,
  8436. * 14, 24, 34, 44 ];
  8437. * ```
  8438. * and internally all calculations are performed using column-major ordering.
  8439. * However, as the actual ordering makes no difference mathematically and
  8440. * most people are used to thinking about matrices in row-major order, the
  8441. * three.js documentation shows matrices in row-major order. Just bear in
  8442. * mind that if you are reading the source code, you'll have to take the
  8443. * transpose of any matrices outlined here to make sense of the calculations.
  8444. */
  8445. class Matrix4 {
  8446. /**
  8447. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8448. * in row-major order. If no arguments are provided, the constructor
  8449. * initializes the matrix as an identity matrix.
  8450. *
  8451. * @param {number} [n11] - 1-1 matrix element.
  8452. * @param {number} [n12] - 1-2 matrix element.
  8453. * @param {number} [n13] - 1-3 matrix element.
  8454. * @param {number} [n14] - 1-4 matrix element.
  8455. * @param {number} [n21] - 2-1 matrix element.
  8456. * @param {number} [n22] - 2-2 matrix element.
  8457. * @param {number} [n23] - 2-3 matrix element.
  8458. * @param {number} [n24] - 2-4 matrix element.
  8459. * @param {number} [n31] - 3-1 matrix element.
  8460. * @param {number} [n32] - 3-2 matrix element.
  8461. * @param {number} [n33] - 3-3 matrix element.
  8462. * @param {number} [n34] - 3-4 matrix element.
  8463. * @param {number} [n41] - 4-1 matrix element.
  8464. * @param {number} [n42] - 4-2 matrix element.
  8465. * @param {number} [n43] - 4-3 matrix element.
  8466. * @param {number} [n44] - 4-4 matrix element.
  8467. */
  8468. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8469. /**
  8470. * This flag can be used for type testing.
  8471. *
  8472. * @type {boolean}
  8473. * @readonly
  8474. * @default true
  8475. */
  8476. Matrix4.prototype.isMatrix4 = true;
  8477. /**
  8478. * A column-major list of matrix values.
  8479. *
  8480. * @type {Array<number>}
  8481. */
  8482. this.elements = [
  8483. 1, 0, 0, 0,
  8484. 0, 1, 0, 0,
  8485. 0, 0, 1, 0,
  8486. 0, 0, 0, 1
  8487. ];
  8488. if ( n11 !== undefined ) {
  8489. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8490. }
  8491. }
  8492. /**
  8493. * Sets the elements of the matrix.The arguments are supposed to be
  8494. * in row-major order.
  8495. *
  8496. * @param {number} [n11] - 1-1 matrix element.
  8497. * @param {number} [n12] - 1-2 matrix element.
  8498. * @param {number} [n13] - 1-3 matrix element.
  8499. * @param {number} [n14] - 1-4 matrix element.
  8500. * @param {number} [n21] - 2-1 matrix element.
  8501. * @param {number} [n22] - 2-2 matrix element.
  8502. * @param {number} [n23] - 2-3 matrix element.
  8503. * @param {number} [n24] - 2-4 matrix element.
  8504. * @param {number} [n31] - 3-1 matrix element.
  8505. * @param {number} [n32] - 3-2 matrix element.
  8506. * @param {number} [n33] - 3-3 matrix element.
  8507. * @param {number} [n34] - 3-4 matrix element.
  8508. * @param {number} [n41] - 4-1 matrix element.
  8509. * @param {number} [n42] - 4-2 matrix element.
  8510. * @param {number} [n43] - 4-3 matrix element.
  8511. * @param {number} [n44] - 4-4 matrix element.
  8512. * @return {Matrix4} A reference to this matrix.
  8513. */
  8514. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8515. const te = this.elements;
  8516. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8517. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8518. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8519. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8520. return this;
  8521. }
  8522. /**
  8523. * Sets this matrix to the 4x4 identity matrix.
  8524. *
  8525. * @return {Matrix4} A reference to this matrix.
  8526. */
  8527. identity() {
  8528. this.set(
  8529. 1, 0, 0, 0,
  8530. 0, 1, 0, 0,
  8531. 0, 0, 1, 0,
  8532. 0, 0, 0, 1
  8533. );
  8534. return this;
  8535. }
  8536. /**
  8537. * Returns a matrix with copied values from this instance.
  8538. *
  8539. * @return {Matrix4} A clone of this instance.
  8540. */
  8541. clone() {
  8542. return new Matrix4().fromArray( this.elements );
  8543. }
  8544. /**
  8545. * Copies the values of the given matrix to this instance.
  8546. *
  8547. * @param {Matrix4} m - The matrix to copy.
  8548. * @return {Matrix4} A reference to this matrix.
  8549. */
  8550. copy( m ) {
  8551. const te = this.elements;
  8552. const me = m.elements;
  8553. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8554. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8555. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8556. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8557. return this;
  8558. }
  8559. /**
  8560. * Copies the translation component of the given matrix
  8561. * into this matrix's translation component.
  8562. *
  8563. * @param {Matrix4} m - The matrix to copy the translation component.
  8564. * @return {Matrix4} A reference to this matrix.
  8565. */
  8566. copyPosition( m ) {
  8567. const te = this.elements, me = m.elements;
  8568. te[ 12 ] = me[ 12 ];
  8569. te[ 13 ] = me[ 13 ];
  8570. te[ 14 ] = me[ 14 ];
  8571. return this;
  8572. }
  8573. /**
  8574. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8575. *
  8576. * @param {Matrix3} m - The 3x3 matrix.
  8577. * @return {Matrix4} A reference to this matrix.
  8578. */
  8579. setFromMatrix3( m ) {
  8580. const me = m.elements;
  8581. this.set(
  8582. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8583. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8584. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8585. 0, 0, 0, 1
  8586. );
  8587. return this;
  8588. }
  8589. /**
  8590. * Extracts the basis of this matrix into the three axis vectors provided.
  8591. *
  8592. * @param {Vector3} xAxis - The basis's x axis.
  8593. * @param {Vector3} yAxis - The basis's y axis.
  8594. * @param {Vector3} zAxis - The basis's z axis.
  8595. * @return {Matrix4} A reference to this matrix.
  8596. */
  8597. extractBasis( xAxis, yAxis, zAxis ) {
  8598. xAxis.setFromMatrixColumn( this, 0 );
  8599. yAxis.setFromMatrixColumn( this, 1 );
  8600. zAxis.setFromMatrixColumn( this, 2 );
  8601. return this;
  8602. }
  8603. /**
  8604. * Sets the given basis vectors to this matrix.
  8605. *
  8606. * @param {Vector3} xAxis - The basis's x axis.
  8607. * @param {Vector3} yAxis - The basis's y axis.
  8608. * @param {Vector3} zAxis - The basis's z axis.
  8609. * @return {Matrix4} A reference to this matrix.
  8610. */
  8611. makeBasis( xAxis, yAxis, zAxis ) {
  8612. this.set(
  8613. xAxis.x, yAxis.x, zAxis.x, 0,
  8614. xAxis.y, yAxis.y, zAxis.y, 0,
  8615. xAxis.z, yAxis.z, zAxis.z, 0,
  8616. 0, 0, 0, 1
  8617. );
  8618. return this;
  8619. }
  8620. /**
  8621. * Extracts the rotation component of the given matrix
  8622. * into this matrix's rotation component.
  8623. *
  8624. * Note: This method does not support reflection matrices.
  8625. *
  8626. * @param {Matrix4} m - The matrix.
  8627. * @return {Matrix4} A reference to this matrix.
  8628. */
  8629. extractRotation( m ) {
  8630. const te = this.elements;
  8631. const me = m.elements;
  8632. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8633. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8634. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8635. te[ 0 ] = me[ 0 ] * scaleX;
  8636. te[ 1 ] = me[ 1 ] * scaleX;
  8637. te[ 2 ] = me[ 2 ] * scaleX;
  8638. te[ 3 ] = 0;
  8639. te[ 4 ] = me[ 4 ] * scaleY;
  8640. te[ 5 ] = me[ 5 ] * scaleY;
  8641. te[ 6 ] = me[ 6 ] * scaleY;
  8642. te[ 7 ] = 0;
  8643. te[ 8 ] = me[ 8 ] * scaleZ;
  8644. te[ 9 ] = me[ 9 ] * scaleZ;
  8645. te[ 10 ] = me[ 10 ] * scaleZ;
  8646. te[ 11 ] = 0;
  8647. te[ 12 ] = 0;
  8648. te[ 13 ] = 0;
  8649. te[ 14 ] = 0;
  8650. te[ 15 ] = 1;
  8651. return this;
  8652. }
  8653. /**
  8654. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8655. * the rotation specified by the given Euler angles. The rest of
  8656. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8657. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8658. * for a complete list.
  8659. *
  8660. * @param {Euler} euler - The Euler angles.
  8661. * @return {Matrix4} A reference to this matrix.
  8662. */
  8663. makeRotationFromEuler( euler ) {
  8664. const te = this.elements;
  8665. const x = euler.x, y = euler.y, z = euler.z;
  8666. const a = Math.cos( x ), b = Math.sin( x );
  8667. const c = Math.cos( y ), d = Math.sin( y );
  8668. const e = Math.cos( z ), f = Math.sin( z );
  8669. if ( euler.order === 'XYZ' ) {
  8670. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8671. te[ 0 ] = c * e;
  8672. te[ 4 ] = - c * f;
  8673. te[ 8 ] = d;
  8674. te[ 1 ] = af + be * d;
  8675. te[ 5 ] = ae - bf * d;
  8676. te[ 9 ] = - b * c;
  8677. te[ 2 ] = bf - ae * d;
  8678. te[ 6 ] = be + af * d;
  8679. te[ 10 ] = a * c;
  8680. } else if ( euler.order === 'YXZ' ) {
  8681. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8682. te[ 0 ] = ce + df * b;
  8683. te[ 4 ] = de * b - cf;
  8684. te[ 8 ] = a * d;
  8685. te[ 1 ] = a * f;
  8686. te[ 5 ] = a * e;
  8687. te[ 9 ] = - b;
  8688. te[ 2 ] = cf * b - de;
  8689. te[ 6 ] = df + ce * b;
  8690. te[ 10 ] = a * c;
  8691. } else if ( euler.order === 'ZXY' ) {
  8692. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8693. te[ 0 ] = ce - df * b;
  8694. te[ 4 ] = - a * f;
  8695. te[ 8 ] = de + cf * b;
  8696. te[ 1 ] = cf + de * b;
  8697. te[ 5 ] = a * e;
  8698. te[ 9 ] = df - ce * b;
  8699. te[ 2 ] = - a * d;
  8700. te[ 6 ] = b;
  8701. te[ 10 ] = a * c;
  8702. } else if ( euler.order === 'ZYX' ) {
  8703. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8704. te[ 0 ] = c * e;
  8705. te[ 4 ] = be * d - af;
  8706. te[ 8 ] = ae * d + bf;
  8707. te[ 1 ] = c * f;
  8708. te[ 5 ] = bf * d + ae;
  8709. te[ 9 ] = af * d - be;
  8710. te[ 2 ] = - d;
  8711. te[ 6 ] = b * c;
  8712. te[ 10 ] = a * c;
  8713. } else if ( euler.order === 'YZX' ) {
  8714. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8715. te[ 0 ] = c * e;
  8716. te[ 4 ] = bd - ac * f;
  8717. te[ 8 ] = bc * f + ad;
  8718. te[ 1 ] = f;
  8719. te[ 5 ] = a * e;
  8720. te[ 9 ] = - b * e;
  8721. te[ 2 ] = - d * e;
  8722. te[ 6 ] = ad * f + bc;
  8723. te[ 10 ] = ac - bd * f;
  8724. } else if ( euler.order === 'XZY' ) {
  8725. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8726. te[ 0 ] = c * e;
  8727. te[ 4 ] = - f;
  8728. te[ 8 ] = d * e;
  8729. te[ 1 ] = ac * f + bd;
  8730. te[ 5 ] = a * e;
  8731. te[ 9 ] = ad * f - bc;
  8732. te[ 2 ] = bc * f - ad;
  8733. te[ 6 ] = b * e;
  8734. te[ 10 ] = bd * f + ac;
  8735. }
  8736. // bottom row
  8737. te[ 3 ] = 0;
  8738. te[ 7 ] = 0;
  8739. te[ 11 ] = 0;
  8740. // last column
  8741. te[ 12 ] = 0;
  8742. te[ 13 ] = 0;
  8743. te[ 14 ] = 0;
  8744. te[ 15 ] = 1;
  8745. return this;
  8746. }
  8747. /**
  8748. * Sets the rotation component of this matrix to the rotation specified by
  8749. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8750. * The rest of the matrix is set to the identity.
  8751. *
  8752. * @param {Quaternion} q - The Quaternion.
  8753. * @return {Matrix4} A reference to this matrix.
  8754. */
  8755. makeRotationFromQuaternion( q ) {
  8756. return this.compose( _zero, q, _one );
  8757. }
  8758. /**
  8759. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8760. * `target`, and oriented by the up-direction.
  8761. *
  8762. * @param {Vector3} eye - The eye vector.
  8763. * @param {Vector3} target - The target vector.
  8764. * @param {Vector3} up - The up vector.
  8765. * @return {Matrix4} A reference to this matrix.
  8766. */
  8767. lookAt( eye, target, up ) {
  8768. const te = this.elements;
  8769. _z.subVectors( eye, target );
  8770. if ( _z.lengthSq() === 0 ) {
  8771. // eye and target are in the same position
  8772. _z.z = 1;
  8773. }
  8774. _z.normalize();
  8775. _x.crossVectors( up, _z );
  8776. if ( _x.lengthSq() === 0 ) {
  8777. // up and z are parallel
  8778. if ( Math.abs( up.z ) === 1 ) {
  8779. _z.x += 0.0001;
  8780. } else {
  8781. _z.z += 0.0001;
  8782. }
  8783. _z.normalize();
  8784. _x.crossVectors( up, _z );
  8785. }
  8786. _x.normalize();
  8787. _y.crossVectors( _z, _x );
  8788. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8789. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8790. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8791. return this;
  8792. }
  8793. /**
  8794. * Post-multiplies this matrix by the given 4x4 matrix.
  8795. *
  8796. * @param {Matrix4} m - The matrix to multiply with.
  8797. * @return {Matrix4} A reference to this matrix.
  8798. */
  8799. multiply( m ) {
  8800. return this.multiplyMatrices( this, m );
  8801. }
  8802. /**
  8803. * Pre-multiplies this matrix by the given 4x4 matrix.
  8804. *
  8805. * @param {Matrix4} m - The matrix to multiply with.
  8806. * @return {Matrix4} A reference to this matrix.
  8807. */
  8808. premultiply( m ) {
  8809. return this.multiplyMatrices( m, this );
  8810. }
  8811. /**
  8812. * Multiples the given 4x4 matrices and stores the result
  8813. * in this matrix.
  8814. *
  8815. * @param {Matrix4} a - The first matrix.
  8816. * @param {Matrix4} b - The second matrix.
  8817. * @return {Matrix4} A reference to this matrix.
  8818. */
  8819. multiplyMatrices( a, b ) {
  8820. const ae = a.elements;
  8821. const be = b.elements;
  8822. const te = this.elements;
  8823. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8824. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8825. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8826. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8827. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8828. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8829. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8830. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8831. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8832. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8833. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8834. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8835. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8836. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8837. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8838. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8839. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8840. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8841. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8842. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8843. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8844. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8845. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8846. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8847. return this;
  8848. }
  8849. /**
  8850. * Multiplies every component of the matrix by the given scalar.
  8851. *
  8852. * @param {number} s - The scalar.
  8853. * @return {Matrix4} A reference to this matrix.
  8854. */
  8855. multiplyScalar( s ) {
  8856. const te = this.elements;
  8857. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8858. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8859. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8860. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8861. return this;
  8862. }
  8863. /**
  8864. * Computes and returns the determinant of this matrix.
  8865. *
  8866. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  8867. *
  8868. * @return {number} The determinant.
  8869. */
  8870. determinant() {
  8871. const te = this.elements;
  8872. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8873. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8874. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8875. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8876. //TODO: make this more efficient
  8877. return (
  8878. n41 * (
  8879. + n14 * n23 * n32
  8880. - n13 * n24 * n32
  8881. - n14 * n22 * n33
  8882. + n12 * n24 * n33
  8883. + n13 * n22 * n34
  8884. - n12 * n23 * n34
  8885. ) +
  8886. n42 * (
  8887. + n11 * n23 * n34
  8888. - n11 * n24 * n33
  8889. + n14 * n21 * n33
  8890. - n13 * n21 * n34
  8891. + n13 * n24 * n31
  8892. - n14 * n23 * n31
  8893. ) +
  8894. n43 * (
  8895. + n11 * n24 * n32
  8896. - n11 * n22 * n34
  8897. - n14 * n21 * n32
  8898. + n12 * n21 * n34
  8899. + n14 * n22 * n31
  8900. - n12 * n24 * n31
  8901. ) +
  8902. n44 * (
  8903. - n13 * n22 * n31
  8904. - n11 * n23 * n32
  8905. + n11 * n22 * n33
  8906. + n13 * n21 * n32
  8907. - n12 * n21 * n33
  8908. + n12 * n23 * n31
  8909. )
  8910. );
  8911. }
  8912. /**
  8913. * Transposes this matrix in place.
  8914. *
  8915. * @return {Matrix4} A reference to this matrix.
  8916. */
  8917. transpose() {
  8918. const te = this.elements;
  8919. let tmp;
  8920. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8921. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8922. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8923. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8924. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8925. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8926. return this;
  8927. }
  8928. /**
  8929. * Sets the position component for this matrix from the given vector,
  8930. * without affecting the rest of the matrix.
  8931. *
  8932. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8933. * @param {number} y - The y component of the vector.
  8934. * @param {number} z - The z component of the vector.
  8935. * @return {Matrix4} A reference to this matrix.
  8936. */
  8937. setPosition( x, y, z ) {
  8938. const te = this.elements;
  8939. if ( x.isVector3 ) {
  8940. te[ 12 ] = x.x;
  8941. te[ 13 ] = x.y;
  8942. te[ 14 ] = x.z;
  8943. } else {
  8944. te[ 12 ] = x;
  8945. te[ 13 ] = y;
  8946. te[ 14 ] = z;
  8947. }
  8948. return this;
  8949. }
  8950. /**
  8951. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  8952. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8953. * a zero matrix instead.
  8954. *
  8955. * @return {Matrix4} A reference to this matrix.
  8956. */
  8957. invert() {
  8958. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  8959. const te = this.elements,
  8960. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8961. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8962. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8963. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8964. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  8965. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  8966. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  8967. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  8968. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  8969. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8970. const detInv = 1 / det;
  8971. te[ 0 ] = t11 * detInv;
  8972. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  8973. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  8974. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  8975. te[ 4 ] = t12 * detInv;
  8976. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  8977. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  8978. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  8979. te[ 8 ] = t13 * detInv;
  8980. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  8981. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  8982. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  8983. te[ 12 ] = t14 * detInv;
  8984. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  8985. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  8986. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  8987. return this;
  8988. }
  8989. /**
  8990. * Multiplies the columns of this matrix by the given vector.
  8991. *
  8992. * @param {Vector3} v - The scale vector.
  8993. * @return {Matrix4} A reference to this matrix.
  8994. */
  8995. scale( v ) {
  8996. const te = this.elements;
  8997. const x = v.x, y = v.y, z = v.z;
  8998. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8999. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9000. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9001. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9002. return this;
  9003. }
  9004. /**
  9005. * Gets the maximum scale value of the three axes.
  9006. *
  9007. * @return {number} The maximum scale.
  9008. */
  9009. getMaxScaleOnAxis() {
  9010. const te = this.elements;
  9011. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9012. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9013. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9014. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9015. }
  9016. /**
  9017. * Sets this matrix as a translation transform from the given vector.
  9018. *
  9019. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9020. * @param {number} y - The amount to translate in the Y axis.
  9021. * @param {number} z - The amount to translate in the z axis.
  9022. * @return {Matrix4} A reference to this matrix.
  9023. */
  9024. makeTranslation( x, y, z ) {
  9025. if ( x.isVector3 ) {
  9026. this.set(
  9027. 1, 0, 0, x.x,
  9028. 0, 1, 0, x.y,
  9029. 0, 0, 1, x.z,
  9030. 0, 0, 0, 1
  9031. );
  9032. } else {
  9033. this.set(
  9034. 1, 0, 0, x,
  9035. 0, 1, 0, y,
  9036. 0, 0, 1, z,
  9037. 0, 0, 0, 1
  9038. );
  9039. }
  9040. return this;
  9041. }
  9042. /**
  9043. * Sets this matrix as a rotational transformation around the X axis by
  9044. * the given angle.
  9045. *
  9046. * @param {number} theta - The rotation in radians.
  9047. * @return {Matrix4} A reference to this matrix.
  9048. */
  9049. makeRotationX( theta ) {
  9050. const c = Math.cos( theta ), s = Math.sin( theta );
  9051. this.set(
  9052. 1, 0, 0, 0,
  9053. 0, c, - s, 0,
  9054. 0, s, c, 0,
  9055. 0, 0, 0, 1
  9056. );
  9057. return this;
  9058. }
  9059. /**
  9060. * Sets this matrix as a rotational transformation around the Y axis by
  9061. * the given angle.
  9062. *
  9063. * @param {number} theta - The rotation in radians.
  9064. * @return {Matrix4} A reference to this matrix.
  9065. */
  9066. makeRotationY( theta ) {
  9067. const c = Math.cos( theta ), s = Math.sin( theta );
  9068. this.set(
  9069. c, 0, s, 0,
  9070. 0, 1, 0, 0,
  9071. - s, 0, c, 0,
  9072. 0, 0, 0, 1
  9073. );
  9074. return this;
  9075. }
  9076. /**
  9077. * Sets this matrix as a rotational transformation around the Z axis by
  9078. * the given angle.
  9079. *
  9080. * @param {number} theta - The rotation in radians.
  9081. * @return {Matrix4} A reference to this matrix.
  9082. */
  9083. makeRotationZ( theta ) {
  9084. const c = Math.cos( theta ), s = Math.sin( theta );
  9085. this.set(
  9086. c, - s, 0, 0,
  9087. s, c, 0, 0,
  9088. 0, 0, 1, 0,
  9089. 0, 0, 0, 1
  9090. );
  9091. return this;
  9092. }
  9093. /**
  9094. * Sets this matrix as a rotational transformation around the given axis by
  9095. * the given angle.
  9096. *
  9097. * This is a somewhat controversial but mathematically sound alternative to
  9098. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9099. *
  9100. * @param {Vector3} axis - The normalized rotation axis.
  9101. * @param {number} angle - The rotation in radians.
  9102. * @return {Matrix4} A reference to this matrix.
  9103. */
  9104. makeRotationAxis( axis, angle ) {
  9105. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9106. const c = Math.cos( angle );
  9107. const s = Math.sin( angle );
  9108. const t = 1 - c;
  9109. const x = axis.x, y = axis.y, z = axis.z;
  9110. const tx = t * x, ty = t * y;
  9111. this.set(
  9112. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9113. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9114. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9115. 0, 0, 0, 1
  9116. );
  9117. return this;
  9118. }
  9119. /**
  9120. * Sets this matrix as a scale transformation.
  9121. *
  9122. * @param {number} x - The amount to scale in the X axis.
  9123. * @param {number} y - The amount to scale in the Y axis.
  9124. * @param {number} z - The amount to scale in the Z axis.
  9125. * @return {Matrix4} A reference to this matrix.
  9126. */
  9127. makeScale( x, y, z ) {
  9128. this.set(
  9129. x, 0, 0, 0,
  9130. 0, y, 0, 0,
  9131. 0, 0, z, 0,
  9132. 0, 0, 0, 1
  9133. );
  9134. return this;
  9135. }
  9136. /**
  9137. * Sets this matrix as a shear transformation.
  9138. *
  9139. * @param {number} xy - The amount to shear X by Y.
  9140. * @param {number} xz - The amount to shear X by Z.
  9141. * @param {number} yx - The amount to shear Y by X.
  9142. * @param {number} yz - The amount to shear Y by Z.
  9143. * @param {number} zx - The amount to shear Z by X.
  9144. * @param {number} zy - The amount to shear Z by Y.
  9145. * @return {Matrix4} A reference to this matrix.
  9146. */
  9147. makeShear( xy, xz, yx, yz, zx, zy ) {
  9148. this.set(
  9149. 1, yx, zx, 0,
  9150. xy, 1, zy, 0,
  9151. xz, yz, 1, 0,
  9152. 0, 0, 0, 1
  9153. );
  9154. return this;
  9155. }
  9156. /**
  9157. * Sets this matrix to the transformation composed of the given position,
  9158. * rotation (Quaternion) and scale.
  9159. *
  9160. * @param {Vector3} position - The position vector.
  9161. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9162. * @param {Vector3} scale - The scale vector.
  9163. * @return {Matrix4} A reference to this matrix.
  9164. */
  9165. compose( position, quaternion, scale ) {
  9166. const te = this.elements;
  9167. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9168. const x2 = x + x, y2 = y + y, z2 = z + z;
  9169. const xx = x * x2, xy = x * y2, xz = x * z2;
  9170. const yy = y * y2, yz = y * z2, zz = z * z2;
  9171. const wx = w * x2, wy = w * y2, wz = w * z2;
  9172. const sx = scale.x, sy = scale.y, sz = scale.z;
  9173. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9174. te[ 1 ] = ( xy + wz ) * sx;
  9175. te[ 2 ] = ( xz - wy ) * sx;
  9176. te[ 3 ] = 0;
  9177. te[ 4 ] = ( xy - wz ) * sy;
  9178. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9179. te[ 6 ] = ( yz + wx ) * sy;
  9180. te[ 7 ] = 0;
  9181. te[ 8 ] = ( xz + wy ) * sz;
  9182. te[ 9 ] = ( yz - wx ) * sz;
  9183. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9184. te[ 11 ] = 0;
  9185. te[ 12 ] = position.x;
  9186. te[ 13 ] = position.y;
  9187. te[ 14 ] = position.z;
  9188. te[ 15 ] = 1;
  9189. return this;
  9190. }
  9191. /**
  9192. * Decomposes this matrix into its position, rotation and scale components
  9193. * and provides the result in the given objects.
  9194. *
  9195. * Note: Not all matrices are decomposable in this way. For example, if an
  9196. * object has a non-uniformly scaled parent, then the object's world matrix
  9197. * may not be decomposable, and this method may not be appropriate.
  9198. *
  9199. * @param {Vector3} position - The position vector.
  9200. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9201. * @param {Vector3} scale - The scale vector.
  9202. * @return {Matrix4} A reference to this matrix.
  9203. */
  9204. decompose( position, quaternion, scale ) {
  9205. const te = this.elements;
  9206. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9207. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9208. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9209. // if determine is negative, we need to invert one scale
  9210. const det = this.determinant();
  9211. if ( det < 0 ) sx = - sx;
  9212. position.x = te[ 12 ];
  9213. position.y = te[ 13 ];
  9214. position.z = te[ 14 ];
  9215. // scale the rotation part
  9216. _m1$4.copy( this );
  9217. const invSX = 1 / sx;
  9218. const invSY = 1 / sy;
  9219. const invSZ = 1 / sz;
  9220. _m1$4.elements[ 0 ] *= invSX;
  9221. _m1$4.elements[ 1 ] *= invSX;
  9222. _m1$4.elements[ 2 ] *= invSX;
  9223. _m1$4.elements[ 4 ] *= invSY;
  9224. _m1$4.elements[ 5 ] *= invSY;
  9225. _m1$4.elements[ 6 ] *= invSY;
  9226. _m1$4.elements[ 8 ] *= invSZ;
  9227. _m1$4.elements[ 9 ] *= invSZ;
  9228. _m1$4.elements[ 10 ] *= invSZ;
  9229. quaternion.setFromRotationMatrix( _m1$4 );
  9230. scale.x = sx;
  9231. scale.y = sy;
  9232. scale.z = sz;
  9233. return this;
  9234. }
  9235. /**
  9236. * Creates a perspective projection matrix. This is used internally by
  9237. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9238. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9239. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9240. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9241. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9242. * @param {number} near - The distance from the camera to the near plane.
  9243. * @param {number} far - The distance from the camera to the far plane.
  9244. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9245. * @return {Matrix4} A reference to this matrix.
  9246. */
  9247. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9248. const te = this.elements;
  9249. const x = 2 * near / ( right - left );
  9250. const y = 2 * near / ( top - bottom );
  9251. const a = ( right + left ) / ( right - left );
  9252. const b = ( top + bottom ) / ( top - bottom );
  9253. let c, d;
  9254. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9255. c = - ( far + near ) / ( far - near );
  9256. d = ( - 2 * far * near ) / ( far - near );
  9257. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9258. c = - far / ( far - near );
  9259. d = ( - far * near ) / ( far - near );
  9260. } else {
  9261. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9262. }
  9263. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9264. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9265. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9266. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  9267. return this;
  9268. }
  9269. /**
  9270. * Creates a orthographic projection matrix. This is used internally by
  9271. * {@link OrthographicCamera#updateProjectionMatrix}.
  9272. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9273. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9274. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9275. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9276. * @param {number} near - The distance from the camera to the near plane.
  9277. * @param {number} far - The distance from the camera to the far plane.
  9278. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9279. * @return {Matrix4} A reference to this matrix.
  9280. */
  9281. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  9282. const te = this.elements;
  9283. const w = 1.0 / ( right - left );
  9284. const h = 1.0 / ( top - bottom );
  9285. const p = 1.0 / ( far - near );
  9286. const x = ( right + left ) * w;
  9287. const y = ( top + bottom ) * h;
  9288. let z, zInv;
  9289. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9290. z = ( far + near ) * p;
  9291. zInv = - 2 * p;
  9292. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9293. z = near * p;
  9294. zInv = - 1 * p;
  9295. } else {
  9296. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9297. }
  9298. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  9299. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  9300. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  9301. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9302. return this;
  9303. }
  9304. /**
  9305. * Returns `true` if this matrix is equal with the given one.
  9306. *
  9307. * @param {Matrix4} matrix - The matrix to test for equality.
  9308. * @return {boolean} Whether this matrix is equal with the given one.
  9309. */
  9310. equals( matrix ) {
  9311. const te = this.elements;
  9312. const me = matrix.elements;
  9313. for ( let i = 0; i < 16; i ++ ) {
  9314. if ( te[ i ] !== me[ i ] ) return false;
  9315. }
  9316. return true;
  9317. }
  9318. /**
  9319. * Sets the elements of the matrix from the given array.
  9320. *
  9321. * @param {Array<number>} array - The matrix elements in column-major order.
  9322. * @param {number} [offset=0] - Index of the first element in the array.
  9323. * @return {Matrix4} A reference to this matrix.
  9324. */
  9325. fromArray( array, offset = 0 ) {
  9326. for ( let i = 0; i < 16; i ++ ) {
  9327. this.elements[ i ] = array[ i + offset ];
  9328. }
  9329. return this;
  9330. }
  9331. /**
  9332. * Writes the elements of this matrix to the given array. If no array is provided,
  9333. * the method returns a new instance.
  9334. *
  9335. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9336. * @param {number} [offset=0] - Index of the first element in the array.
  9337. * @return {Array<number>} The matrix elements in column-major order.
  9338. */
  9339. toArray( array = [], offset = 0 ) {
  9340. const te = this.elements;
  9341. array[ offset ] = te[ 0 ];
  9342. array[ offset + 1 ] = te[ 1 ];
  9343. array[ offset + 2 ] = te[ 2 ];
  9344. array[ offset + 3 ] = te[ 3 ];
  9345. array[ offset + 4 ] = te[ 4 ];
  9346. array[ offset + 5 ] = te[ 5 ];
  9347. array[ offset + 6 ] = te[ 6 ];
  9348. array[ offset + 7 ] = te[ 7 ];
  9349. array[ offset + 8 ] = te[ 8 ];
  9350. array[ offset + 9 ] = te[ 9 ];
  9351. array[ offset + 10 ] = te[ 10 ];
  9352. array[ offset + 11 ] = te[ 11 ];
  9353. array[ offset + 12 ] = te[ 12 ];
  9354. array[ offset + 13 ] = te[ 13 ];
  9355. array[ offset + 14 ] = te[ 14 ];
  9356. array[ offset + 15 ] = te[ 15 ];
  9357. return array;
  9358. }
  9359. }
  9360. const _v1$5 = /*@__PURE__*/ new Vector3();
  9361. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9362. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9363. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9364. const _x = /*@__PURE__*/ new Vector3();
  9365. const _y = /*@__PURE__*/ new Vector3();
  9366. const _z = /*@__PURE__*/ new Vector3();
  9367. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9368. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9369. /**
  9370. * A class representing Euler angles.
  9371. *
  9372. * Euler angles describe a rotational transformation by rotating an object on
  9373. * its various axes in specified amounts per axis, and a specified axis
  9374. * order.
  9375. *
  9376. * Iterating through an instance will yield its components (x, y, z,
  9377. * order) in the corresponding order.
  9378. *
  9379. * ```js
  9380. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9381. * const b = new THREE.Vector3( 1, 0, 1 );
  9382. * b.applyEuler(a);
  9383. * ```
  9384. */
  9385. class Euler {
  9386. /**
  9387. * Constructs a new euler instance.
  9388. *
  9389. * @param {number} [x=0] - The angle of the x axis in radians.
  9390. * @param {number} [y=0] - The angle of the y axis in radians.
  9391. * @param {number} [z=0] - The angle of the z axis in radians.
  9392. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9393. */
  9394. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9395. /**
  9396. * This flag can be used for type testing.
  9397. *
  9398. * @type {boolean}
  9399. * @readonly
  9400. * @default true
  9401. */
  9402. this.isEuler = true;
  9403. this._x = x;
  9404. this._y = y;
  9405. this._z = z;
  9406. this._order = order;
  9407. }
  9408. /**
  9409. * The angle of the x axis in radians.
  9410. *
  9411. * @type {number}
  9412. * @default 0
  9413. */
  9414. get x() {
  9415. return this._x;
  9416. }
  9417. set x( value ) {
  9418. this._x = value;
  9419. this._onChangeCallback();
  9420. }
  9421. /**
  9422. * The angle of the y axis in radians.
  9423. *
  9424. * @type {number}
  9425. * @default 0
  9426. */
  9427. get y() {
  9428. return this._y;
  9429. }
  9430. set y( value ) {
  9431. this._y = value;
  9432. this._onChangeCallback();
  9433. }
  9434. /**
  9435. * The angle of the z axis in radians.
  9436. *
  9437. * @type {number}
  9438. * @default 0
  9439. */
  9440. get z() {
  9441. return this._z;
  9442. }
  9443. set z( value ) {
  9444. this._z = value;
  9445. this._onChangeCallback();
  9446. }
  9447. /**
  9448. * A string representing the order that the rotations are applied.
  9449. *
  9450. * @type {string}
  9451. * @default 'XYZ'
  9452. */
  9453. get order() {
  9454. return this._order;
  9455. }
  9456. set order( value ) {
  9457. this._order = value;
  9458. this._onChangeCallback();
  9459. }
  9460. /**
  9461. * Sets the Euler components.
  9462. *
  9463. * @param {number} x - The angle of the x axis in radians.
  9464. * @param {number} y - The angle of the y axis in radians.
  9465. * @param {number} z - The angle of the z axis in radians.
  9466. * @param {string} [order] - A string representing the order that the rotations are applied.
  9467. * @return {Euler} A reference to this Euler instance.
  9468. */
  9469. set( x, y, z, order = this._order ) {
  9470. this._x = x;
  9471. this._y = y;
  9472. this._z = z;
  9473. this._order = order;
  9474. this._onChangeCallback();
  9475. return this;
  9476. }
  9477. /**
  9478. * Returns a new Euler instance with copied values from this instance.
  9479. *
  9480. * @return {Euler} A clone of this instance.
  9481. */
  9482. clone() {
  9483. return new this.constructor( this._x, this._y, this._z, this._order );
  9484. }
  9485. /**
  9486. * Copies the values of the given Euler instance to this instance.
  9487. *
  9488. * @param {Euler} euler - The Euler instance to copy.
  9489. * @return {Euler} A reference to this Euler instance.
  9490. */
  9491. copy( euler ) {
  9492. this._x = euler._x;
  9493. this._y = euler._y;
  9494. this._z = euler._z;
  9495. this._order = euler._order;
  9496. this._onChangeCallback();
  9497. return this;
  9498. }
  9499. /**
  9500. * Sets the angles of this Euler instance from a pure rotation matrix.
  9501. *
  9502. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9503. * @param {string} [order] - A string representing the order that the rotations are applied.
  9504. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9505. * @return {Euler} A reference to this Euler instance.
  9506. */
  9507. setFromRotationMatrix( m, order = this._order, update = true ) {
  9508. const te = m.elements;
  9509. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9510. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9511. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9512. switch ( order ) {
  9513. case 'XYZ':
  9514. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  9515. if ( Math.abs( m13 ) < 0.9999999 ) {
  9516. this._x = Math.atan2( - m23, m33 );
  9517. this._z = Math.atan2( - m12, m11 );
  9518. } else {
  9519. this._x = Math.atan2( m32, m22 );
  9520. this._z = 0;
  9521. }
  9522. break;
  9523. case 'YXZ':
  9524. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  9525. if ( Math.abs( m23 ) < 0.9999999 ) {
  9526. this._y = Math.atan2( m13, m33 );
  9527. this._z = Math.atan2( m21, m22 );
  9528. } else {
  9529. this._y = Math.atan2( - m31, m11 );
  9530. this._z = 0;
  9531. }
  9532. break;
  9533. case 'ZXY':
  9534. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  9535. if ( Math.abs( m32 ) < 0.9999999 ) {
  9536. this._y = Math.atan2( - m31, m33 );
  9537. this._z = Math.atan2( - m12, m22 );
  9538. } else {
  9539. this._y = 0;
  9540. this._z = Math.atan2( m21, m11 );
  9541. }
  9542. break;
  9543. case 'ZYX':
  9544. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  9545. if ( Math.abs( m31 ) < 0.9999999 ) {
  9546. this._x = Math.atan2( m32, m33 );
  9547. this._z = Math.atan2( m21, m11 );
  9548. } else {
  9549. this._x = 0;
  9550. this._z = Math.atan2( - m12, m22 );
  9551. }
  9552. break;
  9553. case 'YZX':
  9554. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  9555. if ( Math.abs( m21 ) < 0.9999999 ) {
  9556. this._x = Math.atan2( - m23, m22 );
  9557. this._y = Math.atan2( - m31, m11 );
  9558. } else {
  9559. this._x = 0;
  9560. this._y = Math.atan2( m13, m33 );
  9561. }
  9562. break;
  9563. case 'XZY':
  9564. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  9565. if ( Math.abs( m12 ) < 0.9999999 ) {
  9566. this._x = Math.atan2( m32, m22 );
  9567. this._y = Math.atan2( m13, m11 );
  9568. } else {
  9569. this._x = Math.atan2( - m23, m33 );
  9570. this._y = 0;
  9571. }
  9572. break;
  9573. default:
  9574. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9575. }
  9576. this._order = order;
  9577. if ( update === true ) this._onChangeCallback();
  9578. return this;
  9579. }
  9580. /**
  9581. * Sets the angles of this Euler instance from a normalized quaternion.
  9582. *
  9583. * @param {Quaternion} q - A normalized Quaternion.
  9584. * @param {string} [order] - A string representing the order that the rotations are applied.
  9585. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9586. * @return {Euler} A reference to this Euler instance.
  9587. */
  9588. setFromQuaternion( q, order, update ) {
  9589. _matrix$2.makeRotationFromQuaternion( q );
  9590. return this.setFromRotationMatrix( _matrix$2, order, update );
  9591. }
  9592. /**
  9593. * Sets the angles of this Euler instance from the given vector.
  9594. *
  9595. * @param {Vector3} v - The vector.
  9596. * @param {string} [order] - A string representing the order that the rotations are applied.
  9597. * @return {Euler} A reference to this Euler instance.
  9598. */
  9599. setFromVector3( v, order = this._order ) {
  9600. return this.set( v.x, v.y, v.z, order );
  9601. }
  9602. /**
  9603. * Resets the euler angle with a new order by creating a quaternion from this
  9604. * euler angle and then setting this euler angle with the quaternion and the
  9605. * new order.
  9606. *
  9607. * Warning: This discards revolution information.
  9608. *
  9609. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9610. * @return {Euler} A reference to this Euler instance.
  9611. */
  9612. reorder( newOrder ) {
  9613. _quaternion$3.setFromEuler( this );
  9614. return this.setFromQuaternion( _quaternion$3, newOrder );
  9615. }
  9616. /**
  9617. * Returns `true` if this Euler instance is equal with the given one.
  9618. *
  9619. * @param {Euler} euler - The Euler instance to test for equality.
  9620. * @return {boolean} Whether this Euler instance is equal with the given one.
  9621. */
  9622. equals( euler ) {
  9623. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9624. }
  9625. /**
  9626. * Sets this Euler instance's components to values from the given array. The first three
  9627. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9628. * defines the Euler order.
  9629. *
  9630. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9631. * @return {Euler} A reference to this Euler instance.
  9632. */
  9633. fromArray( array ) {
  9634. this._x = array[ 0 ];
  9635. this._y = array[ 1 ];
  9636. this._z = array[ 2 ];
  9637. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9638. this._onChangeCallback();
  9639. return this;
  9640. }
  9641. /**
  9642. * Writes the components of this Euler instance to the given array. If no array is provided,
  9643. * the method returns a new instance.
  9644. *
  9645. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9646. * @param {number} [offset=0] - Index of the first element in the array.
  9647. * @return {Array<number,number,number,string>} The Euler components.
  9648. */
  9649. toArray( array = [], offset = 0 ) {
  9650. array[ offset ] = this._x;
  9651. array[ offset + 1 ] = this._y;
  9652. array[ offset + 2 ] = this._z;
  9653. array[ offset + 3 ] = this._order;
  9654. return array;
  9655. }
  9656. _onChange( callback ) {
  9657. this._onChangeCallback = callback;
  9658. return this;
  9659. }
  9660. _onChangeCallback() {}
  9661. *[ Symbol.iterator ]() {
  9662. yield this._x;
  9663. yield this._y;
  9664. yield this._z;
  9665. yield this._order;
  9666. }
  9667. }
  9668. /**
  9669. * The default Euler angle order.
  9670. *
  9671. * @static
  9672. * @type {string}
  9673. * @default 'XYZ'
  9674. */
  9675. Euler.DEFAULT_ORDER = 'XYZ';
  9676. /**
  9677. * A layers object assigns an 3D object to 1 or more of 32
  9678. * layers numbered `0` to `31` - internally the layers are stored as a
  9679. * bit mask], and by default all 3D objects are a member of layer `0`.
  9680. *
  9681. * This can be used to control visibility - an object must share a layer with
  9682. * a camera to be visible when that camera's view is
  9683. * rendered.
  9684. *
  9685. * All classes that inherit from {@link Object3D} have an `layers` property which
  9686. * is an instance of this class.
  9687. */
  9688. class Layers {
  9689. /**
  9690. * Constructs a new layers instance, with membership
  9691. * initially set to layer `0`.
  9692. */
  9693. constructor() {
  9694. /**
  9695. * A bit mask storing which of the 32 layers this layers object is currently
  9696. * a member of.
  9697. *
  9698. * @type {number}
  9699. */
  9700. this.mask = 1 | 0;
  9701. }
  9702. /**
  9703. * Sets membership to the given layer, and remove membership all other layers.
  9704. *
  9705. * @param {number} layer - The layer to set.
  9706. */
  9707. set( layer ) {
  9708. this.mask = ( 1 << layer | 0 ) >>> 0;
  9709. }
  9710. /**
  9711. * Adds membership of the given layer.
  9712. *
  9713. * @param {number} layer - The layer to enable.
  9714. */
  9715. enable( layer ) {
  9716. this.mask |= 1 << layer | 0;
  9717. }
  9718. /**
  9719. * Adds membership to all layers.
  9720. */
  9721. enableAll() {
  9722. this.mask = 0xffffffff | 0;
  9723. }
  9724. /**
  9725. * Toggles the membership of the given layer.
  9726. *
  9727. * @param {number} layer - The layer to toggle.
  9728. */
  9729. toggle( layer ) {
  9730. this.mask ^= 1 << layer | 0;
  9731. }
  9732. /**
  9733. * Removes membership of the given layer.
  9734. *
  9735. * @param {number} layer - The layer to enable.
  9736. */
  9737. disable( layer ) {
  9738. this.mask &= ~ ( 1 << layer | 0 );
  9739. }
  9740. /**
  9741. * Removes the membership from all layers.
  9742. */
  9743. disableAll() {
  9744. this.mask = 0;
  9745. }
  9746. /**
  9747. * Returns `true` if this and the given layers object have at least one
  9748. * layer in common.
  9749. *
  9750. * @param {Layers} layers - The layers to test.
  9751. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9752. */
  9753. test( layers ) {
  9754. return ( this.mask & layers.mask ) !== 0;
  9755. }
  9756. /**
  9757. * Returns `true` if the given layer is enabled.
  9758. *
  9759. * @param {number} layer - The layer to test.
  9760. * @return {boolean } Whether the given layer is enabled or not.
  9761. */
  9762. isEnabled( layer ) {
  9763. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9764. }
  9765. }
  9766. let _object3DId = 0;
  9767. const _v1$4 = /*@__PURE__*/ new Vector3();
  9768. const _q1 = /*@__PURE__*/ new Quaternion();
  9769. const _m1$3 = /*@__PURE__*/ new Matrix4();
  9770. const _target = /*@__PURE__*/ new Vector3();
  9771. const _position$3 = /*@__PURE__*/ new Vector3();
  9772. const _scale$2 = /*@__PURE__*/ new Vector3();
  9773. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9774. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9775. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9776. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9777. /**
  9778. * Fires when the object has been added to its parent object.
  9779. *
  9780. * @event Object3D#added
  9781. * @type {Object}
  9782. */
  9783. const _addedEvent = { type: 'added' };
  9784. /**
  9785. * Fires when the object has been removed from its parent object.
  9786. *
  9787. * @event Object3D#removed
  9788. * @type {Object}
  9789. */
  9790. const _removedEvent = { type: 'removed' };
  9791. /**
  9792. * Fires when a new child object has been added.
  9793. *
  9794. * @event Object3D#childadded
  9795. * @type {Object}
  9796. */
  9797. const _childaddedEvent = { type: 'childadded', child: null };
  9798. /**
  9799. * Fires when a new child object has been added.
  9800. *
  9801. * @event Object3D#childremoved
  9802. * @type {Object}
  9803. */
  9804. const _childremovedEvent = { type: 'childremoved', child: null };
  9805. /**
  9806. * This is the base class for most objects in three.js and provides a set of
  9807. * properties and methods for manipulating objects in 3D space.
  9808. *
  9809. * @augments EventDispatcher
  9810. */
  9811. class Object3D extends EventDispatcher {
  9812. /**
  9813. * Constructs a new 3D object.
  9814. */
  9815. constructor() {
  9816. super();
  9817. /**
  9818. * This flag can be used for type testing.
  9819. *
  9820. * @type {boolean}
  9821. * @readonly
  9822. * @default true
  9823. */
  9824. this.isObject3D = true;
  9825. /**
  9826. * The ID of the 3D object.
  9827. *
  9828. * @name Object3D#id
  9829. * @type {number}
  9830. * @readonly
  9831. */
  9832. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9833. /**
  9834. * The UUID of the 3D object.
  9835. *
  9836. * @type {string}
  9837. * @readonly
  9838. */
  9839. this.uuid = generateUUID();
  9840. /**
  9841. * The name of the 3D object.
  9842. *
  9843. * @type {string}
  9844. */
  9845. this.name = '';
  9846. /**
  9847. * The type property is used for detecting the object type
  9848. * in context of serialization/deserialization.
  9849. *
  9850. * @type {string}
  9851. * @readonly
  9852. */
  9853. this.type = 'Object3D';
  9854. /**
  9855. * A reference to the parent object.
  9856. *
  9857. * @type {?Object3D}
  9858. * @default null
  9859. */
  9860. this.parent = null;
  9861. /**
  9862. * An array holding the child 3D objects of this instance.
  9863. *
  9864. * @type {Array<Object3D>}
  9865. */
  9866. this.children = [];
  9867. /**
  9868. * Defines the `up` direction of the 3D object which influences
  9869. * the orientation via methods like {@link Object3D#lookAt}.
  9870. *
  9871. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9872. *
  9873. * @type {Vector3}
  9874. */
  9875. this.up = Object3D.DEFAULT_UP.clone();
  9876. const position = new Vector3();
  9877. const rotation = new Euler();
  9878. const quaternion = new Quaternion();
  9879. const scale = new Vector3( 1, 1, 1 );
  9880. function onRotationChange() {
  9881. quaternion.setFromEuler( rotation, false );
  9882. }
  9883. function onQuaternionChange() {
  9884. rotation.setFromQuaternion( quaternion, undefined, false );
  9885. }
  9886. rotation._onChange( onRotationChange );
  9887. quaternion._onChange( onQuaternionChange );
  9888. Object.defineProperties( this, {
  9889. /**
  9890. * Represents the object's local position.
  9891. *
  9892. * @name Object3D#position
  9893. * @type {Vector3}
  9894. * @default (0,0,0)
  9895. */
  9896. position: {
  9897. configurable: true,
  9898. enumerable: true,
  9899. value: position
  9900. },
  9901. /**
  9902. * Represents the object's local rotation as Euler angles, in radians.
  9903. *
  9904. * @name Object3D#rotation
  9905. * @type {Euler}
  9906. * @default (0,0,0)
  9907. */
  9908. rotation: {
  9909. configurable: true,
  9910. enumerable: true,
  9911. value: rotation
  9912. },
  9913. /**
  9914. * Represents the object's local rotation as Quaternions.
  9915. *
  9916. * @name Object3D#quaternion
  9917. * @type {Quaternion}
  9918. */
  9919. quaternion: {
  9920. configurable: true,
  9921. enumerable: true,
  9922. value: quaternion
  9923. },
  9924. /**
  9925. * Represents the object's local scale.
  9926. *
  9927. * @name Object3D#scale
  9928. * @type {Vector3}
  9929. * @default (1,1,1)
  9930. */
  9931. scale: {
  9932. configurable: true,
  9933. enumerable: true,
  9934. value: scale
  9935. },
  9936. /**
  9937. * Represents the object's model-view matrix.
  9938. *
  9939. * @name Object3D#modelViewMatrix
  9940. * @type {Matrix4}
  9941. */
  9942. modelViewMatrix: {
  9943. value: new Matrix4()
  9944. },
  9945. /**
  9946. * Represents the object's normal matrix.
  9947. *
  9948. * @name Object3D#normalMatrix
  9949. * @type {Matrix3}
  9950. */
  9951. normalMatrix: {
  9952. value: new Matrix3()
  9953. }
  9954. } );
  9955. /**
  9956. * Represents the object's transformation matrix in local space.
  9957. *
  9958. * @type {Matrix4}
  9959. */
  9960. this.matrix = new Matrix4();
  9961. /**
  9962. * Represents the object's transformation matrix in world space.
  9963. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9964. *
  9965. * @type {Matrix4}
  9966. */
  9967. this.matrixWorld = new Matrix4();
  9968. /**
  9969. * When set to `true`, the engine automatically computes the local matrix from position,
  9970. * rotation and scale every frame.
  9971. *
  9972. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9973. *
  9974. * @type {boolean}
  9975. * @default true
  9976. */
  9977. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9978. /**
  9979. * When set to `true`, the engine automatically computes the world matrix from the current local
  9980. * matrix and the object's transformation hierarchy.
  9981. *
  9982. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9983. *
  9984. * @type {boolean}
  9985. * @default true
  9986. */
  9987. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9988. /**
  9989. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9990. * to `false`.
  9991. *
  9992. * @type {boolean}
  9993. * @default false
  9994. */
  9995. this.matrixWorldNeedsUpdate = false;
  9996. /**
  9997. * The layer membership of the 3D object. The 3D object is only visible if it has
  9998. * at least one layer in common with the camera in use. This property can also be
  9999. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10000. *
  10001. * @type {Layers}
  10002. */
  10003. this.layers = new Layers();
  10004. /**
  10005. * When set to `true`, the 3D object gets rendered.
  10006. *
  10007. * @type {boolean}
  10008. * @default true
  10009. */
  10010. this.visible = true;
  10011. /**
  10012. * When set to `true`, the 3D object gets rendered into shadow maps.
  10013. *
  10014. * @type {boolean}
  10015. * @default false
  10016. */
  10017. this.castShadow = false;
  10018. /**
  10019. * When set to `true`, the 3D object is affected by shadows in the scene.
  10020. *
  10021. * @type {boolean}
  10022. * @default false
  10023. */
  10024. this.receiveShadow = false;
  10025. /**
  10026. * When set to `true`, the 3D object is honored by view frustum culling.
  10027. *
  10028. * @type {boolean}
  10029. * @default true
  10030. */
  10031. this.frustumCulled = true;
  10032. /**
  10033. * This value allows the default rendering order of scene graph objects to be
  10034. * overridden although opaque and transparent objects remain sorted independently.
  10035. * When this property is set for an instance of {@link Group},all descendants
  10036. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10037. * render order.
  10038. *
  10039. * @type {number}
  10040. * @default 0
  10041. */
  10042. this.renderOrder = 0;
  10043. /**
  10044. * An array holding the animation clips of the 3D object.
  10045. *
  10046. * @type {Array<AnimationClip>}
  10047. */
  10048. this.animations = [];
  10049. /**
  10050. * Custom depth material to be used when rendering to the depth map. Can only be used
  10051. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10052. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10053. * material for proper shadows.
  10054. *
  10055. * Only relevant in context of {@link WebGLRenderer}.
  10056. *
  10057. * @type {(Material|undefined)}
  10058. * @default undefined
  10059. */
  10060. this.customDepthMaterial = undefined;
  10061. /**
  10062. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10063. *
  10064. * Only relevant in context of {@link WebGLRenderer}.
  10065. *
  10066. * @type {(Material|undefined)}
  10067. * @default undefined
  10068. */
  10069. this.customDistanceMaterial = undefined;
  10070. /**
  10071. * An object that can be used to store custom data about the 3D object. It
  10072. * should not hold references to functions as these will not be cloned.
  10073. *
  10074. * @type {Object}
  10075. */
  10076. this.userData = {};
  10077. }
  10078. /**
  10079. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10080. *
  10081. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10082. * @param {Object3D} object - The 3D object.
  10083. * @param {Camera} camera - The camera that is used to render the scene.
  10084. * @param {Camera} shadowCamera - The shadow camera.
  10085. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10086. * @param {Material} depthMaterial - The depth material.
  10087. * @param {Object} group - The geometry group data.
  10088. */
  10089. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10090. /**
  10091. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10092. *
  10093. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10094. * @param {Object3D} object - The 3D object.
  10095. * @param {Camera} camera - The camera that is used to render the scene.
  10096. * @param {Camera} shadowCamera - The shadow camera.
  10097. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10098. * @param {Material} depthMaterial - The depth material.
  10099. * @param {Object} group - The geometry group data.
  10100. */
  10101. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10102. /**
  10103. * A callback that is executed immediately before a 3D object is rendered.
  10104. *
  10105. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10106. * @param {Object3D} object - The 3D object.
  10107. * @param {Camera} camera - The camera that is used to render the scene.
  10108. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10109. * @param {Material} material - The 3D object's material.
  10110. * @param {Object} group - The geometry group data.
  10111. */
  10112. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10113. /**
  10114. * A callback that is executed immediately after a 3D object is rendered.
  10115. *
  10116. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10117. * @param {Object3D} object - The 3D object.
  10118. * @param {Camera} camera - The camera that is used to render the scene.
  10119. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10120. * @param {Material} material - The 3D object's material.
  10121. * @param {Object} group - The geometry group data.
  10122. */
  10123. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10124. /**
  10125. * Applies the given transformation matrix to the object and updates the object's position,
  10126. * rotation and scale.
  10127. *
  10128. * @param {Matrix4} matrix - The transformation matrix.
  10129. */
  10130. applyMatrix4( matrix ) {
  10131. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10132. this.matrix.premultiply( matrix );
  10133. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10134. }
  10135. /**
  10136. * Applies a rotation represented by given the quaternion to the 3D object.
  10137. *
  10138. * @param {Quaternion} q - The quaternion.
  10139. * @return {Object3D} A reference to this instance.
  10140. */
  10141. applyQuaternion( q ) {
  10142. this.quaternion.premultiply( q );
  10143. return this;
  10144. }
  10145. /**
  10146. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10147. *
  10148. * @param {Vector3} axis - The (normalized) axis vector.
  10149. * @param {number} angle - The angle in radians.
  10150. */
  10151. setRotationFromAxisAngle( axis, angle ) {
  10152. // assumes axis is normalized
  10153. this.quaternion.setFromAxisAngle( axis, angle );
  10154. }
  10155. /**
  10156. * Sets the given rotation represented as Euler angles to the 3D object.
  10157. *
  10158. * @param {Euler} euler - The Euler angles.
  10159. */
  10160. setRotationFromEuler( euler ) {
  10161. this.quaternion.setFromEuler( euler, true );
  10162. }
  10163. /**
  10164. * Sets the given rotation represented as rotation matrix to the 3D object.
  10165. *
  10166. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10167. * a pure rotation matrix (i.e, unscaled).
  10168. */
  10169. setRotationFromMatrix( m ) {
  10170. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10171. this.quaternion.setFromRotationMatrix( m );
  10172. }
  10173. /**
  10174. * Sets the given rotation represented as a Quaternion to the 3D object.
  10175. *
  10176. * @param {Quaternion} q - The Quaternion
  10177. */
  10178. setRotationFromQuaternion( q ) {
  10179. // assumes q is normalized
  10180. this.quaternion.copy( q );
  10181. }
  10182. /**
  10183. * Rotates the 3D object along an axis in local space.
  10184. *
  10185. * @param {Vector3} axis - The (normalized) axis vector.
  10186. * @param {number} angle - The angle in radians.
  10187. * @return {Object3D} A reference to this instance.
  10188. */
  10189. rotateOnAxis( axis, angle ) {
  10190. // rotate object on axis in object space
  10191. // axis is assumed to be normalized
  10192. _q1.setFromAxisAngle( axis, angle );
  10193. this.quaternion.multiply( _q1 );
  10194. return this;
  10195. }
  10196. /**
  10197. * Rotates the 3D object along an axis in world space.
  10198. *
  10199. * @param {Vector3} axis - The (normalized) axis vector.
  10200. * @param {number} angle - The angle in radians.
  10201. * @return {Object3D} A reference to this instance.
  10202. */
  10203. rotateOnWorldAxis( axis, angle ) {
  10204. // rotate object on axis in world space
  10205. // axis is assumed to be normalized
  10206. // method assumes no rotated parent
  10207. _q1.setFromAxisAngle( axis, angle );
  10208. this.quaternion.premultiply( _q1 );
  10209. return this;
  10210. }
  10211. /**
  10212. * Rotates the 3D object around its X axis in local space.
  10213. *
  10214. * @param {number} angle - The angle in radians.
  10215. * @return {Object3D} A reference to this instance.
  10216. */
  10217. rotateX( angle ) {
  10218. return this.rotateOnAxis( _xAxis, angle );
  10219. }
  10220. /**
  10221. * Rotates the 3D object around its Y axis in local space.
  10222. *
  10223. * @param {number} angle - The angle in radians.
  10224. * @return {Object3D} A reference to this instance.
  10225. */
  10226. rotateY( angle ) {
  10227. return this.rotateOnAxis( _yAxis, angle );
  10228. }
  10229. /**
  10230. * Rotates the 3D object around its Z axis in local space.
  10231. *
  10232. * @param {number} angle - The angle in radians.
  10233. * @return {Object3D} A reference to this instance.
  10234. */
  10235. rotateZ( angle ) {
  10236. return this.rotateOnAxis( _zAxis, angle );
  10237. }
  10238. /**
  10239. * Translate the 3D object by a distance along the given axis in local space.
  10240. *
  10241. * @param {Vector3} axis - The (normalized) axis vector.
  10242. * @param {number} distance - The distance in world units.
  10243. * @return {Object3D} A reference to this instance.
  10244. */
  10245. translateOnAxis( axis, distance ) {
  10246. // translate object by distance along axis in object space
  10247. // axis is assumed to be normalized
  10248. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10249. this.position.add( _v1$4.multiplyScalar( distance ) );
  10250. return this;
  10251. }
  10252. /**
  10253. * Translate the 3D object by a distance along its X-axis in local space.
  10254. *
  10255. * @param {number} distance - The distance in world units.
  10256. * @return {Object3D} A reference to this instance.
  10257. */
  10258. translateX( distance ) {
  10259. return this.translateOnAxis( _xAxis, distance );
  10260. }
  10261. /**
  10262. * Translate the 3D object by a distance along its Y-axis in local space.
  10263. *
  10264. * @param {number} distance - The distance in world units.
  10265. * @return {Object3D} A reference to this instance.
  10266. */
  10267. translateY( distance ) {
  10268. return this.translateOnAxis( _yAxis, distance );
  10269. }
  10270. /**
  10271. * Translate the 3D object by a distance along its Z-axis in local space.
  10272. *
  10273. * @param {number} distance - The distance in world units.
  10274. * @return {Object3D} A reference to this instance.
  10275. */
  10276. translateZ( distance ) {
  10277. return this.translateOnAxis( _zAxis, distance );
  10278. }
  10279. /**
  10280. * Converts the given vector from this 3D object's local space to world space.
  10281. *
  10282. * @param {Vector3} vector - The vector to convert.
  10283. * @return {Vector3} The converted vector.
  10284. */
  10285. localToWorld( vector ) {
  10286. this.updateWorldMatrix( true, false );
  10287. return vector.applyMatrix4( this.matrixWorld );
  10288. }
  10289. /**
  10290. * Converts the given vector from this 3D object's word space to local space.
  10291. *
  10292. * @param {Vector3} vector - The vector to convert.
  10293. * @return {Vector3} The converted vector.
  10294. */
  10295. worldToLocal( vector ) {
  10296. this.updateWorldMatrix( true, false );
  10297. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10298. }
  10299. /**
  10300. * Rotates the object to face a point in world space.
  10301. *
  10302. * This method does not support objects having non-uniformly-scaled parent(s).
  10303. *
  10304. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10305. * @param {number} [y] - The y coordinate in world space.
  10306. * @param {number} [z] - The z coordinate in world space.
  10307. */
  10308. lookAt( x, y, z ) {
  10309. // This method does not support objects having non-uniformly-scaled parent(s)
  10310. if ( x.isVector3 ) {
  10311. _target.copy( x );
  10312. } else {
  10313. _target.set( x, y, z );
  10314. }
  10315. const parent = this.parent;
  10316. this.updateWorldMatrix( true, false );
  10317. _position$3.setFromMatrixPosition( this.matrixWorld );
  10318. if ( this.isCamera || this.isLight ) {
  10319. _m1$3.lookAt( _position$3, _target, this.up );
  10320. } else {
  10321. _m1$3.lookAt( _target, _position$3, this.up );
  10322. }
  10323. this.quaternion.setFromRotationMatrix( _m1$3 );
  10324. if ( parent ) {
  10325. _m1$3.extractRotation( parent.matrixWorld );
  10326. _q1.setFromRotationMatrix( _m1$3 );
  10327. this.quaternion.premultiply( _q1.invert() );
  10328. }
  10329. }
  10330. /**
  10331. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10332. * objects may be added. Any current parent on an object passed in here will be
  10333. * removed, since an object can have at most one parent.
  10334. *
  10335. * @fires Object3D#added
  10336. * @fires Object3D#childadded
  10337. * @param {Object3D} object - The 3D object to add.
  10338. * @return {Object3D} A reference to this instance.
  10339. */
  10340. add( object ) {
  10341. if ( arguments.length > 1 ) {
  10342. for ( let i = 0; i < arguments.length; i ++ ) {
  10343. this.add( arguments[ i ] );
  10344. }
  10345. return this;
  10346. }
  10347. if ( object === this ) {
  10348. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10349. return this;
  10350. }
  10351. if ( object && object.isObject3D ) {
  10352. object.removeFromParent();
  10353. object.parent = this;
  10354. this.children.push( object );
  10355. object.dispatchEvent( _addedEvent );
  10356. _childaddedEvent.child = object;
  10357. this.dispatchEvent( _childaddedEvent );
  10358. _childaddedEvent.child = null;
  10359. } else {
  10360. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10361. }
  10362. return this;
  10363. }
  10364. /**
  10365. * Removes the given 3D object as child from this 3D object.
  10366. * An arbitrary number of objects may be removed.
  10367. *
  10368. * @fires Object3D#removed
  10369. * @fires Object3D#childremoved
  10370. * @param {Object3D} object - The 3D object to remove.
  10371. * @return {Object3D} A reference to this instance.
  10372. */
  10373. remove( object ) {
  10374. if ( arguments.length > 1 ) {
  10375. for ( let i = 0; i < arguments.length; i ++ ) {
  10376. this.remove( arguments[ i ] );
  10377. }
  10378. return this;
  10379. }
  10380. const index = this.children.indexOf( object );
  10381. if ( index !== - 1 ) {
  10382. object.parent = null;
  10383. this.children.splice( index, 1 );
  10384. object.dispatchEvent( _removedEvent );
  10385. _childremovedEvent.child = object;
  10386. this.dispatchEvent( _childremovedEvent );
  10387. _childremovedEvent.child = null;
  10388. }
  10389. return this;
  10390. }
  10391. /**
  10392. * Removes this 3D object from its current parent.
  10393. *
  10394. * @fires Object3D#removed
  10395. * @fires Object3D#childremoved
  10396. * @return {Object3D} A reference to this instance.
  10397. */
  10398. removeFromParent() {
  10399. const parent = this.parent;
  10400. if ( parent !== null ) {
  10401. parent.remove( this );
  10402. }
  10403. return this;
  10404. }
  10405. /**
  10406. * Removes all child objects.
  10407. *
  10408. * @fires Object3D#removed
  10409. * @fires Object3D#childremoved
  10410. * @return {Object3D} A reference to this instance.
  10411. */
  10412. clear() {
  10413. return this.remove( ... this.children );
  10414. }
  10415. /**
  10416. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10417. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10418. *
  10419. * @fires Object3D#added
  10420. * @fires Object3D#childadded
  10421. * @param {Object3D} object - The 3D object to attach.
  10422. * @return {Object3D} A reference to this instance.
  10423. */
  10424. attach( object ) {
  10425. // adds object as a child of this, while maintaining the object's world transform
  10426. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10427. this.updateWorldMatrix( true, false );
  10428. _m1$3.copy( this.matrixWorld ).invert();
  10429. if ( object.parent !== null ) {
  10430. object.parent.updateWorldMatrix( true, false );
  10431. _m1$3.multiply( object.parent.matrixWorld );
  10432. }
  10433. object.applyMatrix4( _m1$3 );
  10434. object.removeFromParent();
  10435. object.parent = this;
  10436. this.children.push( object );
  10437. object.updateWorldMatrix( false, true );
  10438. object.dispatchEvent( _addedEvent );
  10439. _childaddedEvent.child = object;
  10440. this.dispatchEvent( _childaddedEvent );
  10441. _childaddedEvent.child = null;
  10442. return this;
  10443. }
  10444. /**
  10445. * Searches through the 3D object and its children, starting with the 3D object
  10446. * itself, and returns the first with a matching ID.
  10447. *
  10448. * @param {number} id - The id.
  10449. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10450. */
  10451. getObjectById( id ) {
  10452. return this.getObjectByProperty( 'id', id );
  10453. }
  10454. /**
  10455. * Searches through the 3D object and its children, starting with the 3D object
  10456. * itself, and returns the first with a matching name.
  10457. *
  10458. * @param {string} name - The name.
  10459. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10460. */
  10461. getObjectByName( name ) {
  10462. return this.getObjectByProperty( 'name', name );
  10463. }
  10464. /**
  10465. * Searches through the 3D object and its children, starting with the 3D object
  10466. * itself, and returns the first with a matching property value.
  10467. *
  10468. * @param {string} name - The name of the property.
  10469. * @param {any} value - The value.
  10470. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10471. */
  10472. getObjectByProperty( name, value ) {
  10473. if ( this[ name ] === value ) return this;
  10474. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10475. const child = this.children[ i ];
  10476. const object = child.getObjectByProperty( name, value );
  10477. if ( object !== undefined ) {
  10478. return object;
  10479. }
  10480. }
  10481. return undefined;
  10482. }
  10483. /**
  10484. * Searches through the 3D object and its children, starting with the 3D object
  10485. * itself, and returns all 3D objects with a matching property value.
  10486. *
  10487. * @param {string} name - The name of the property.
  10488. * @param {any} value - The value.
  10489. * @param {Array<Object3D>} result - The method stores the result in this array.
  10490. * @return {Array<Object3D>} The found 3D objects.
  10491. */
  10492. getObjectsByProperty( name, value, result = [] ) {
  10493. if ( this[ name ] === value ) result.push( this );
  10494. const children = this.children;
  10495. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10496. children[ i ].getObjectsByProperty( name, value, result );
  10497. }
  10498. return result;
  10499. }
  10500. /**
  10501. * Returns a vector representing the position of the 3D object in world space.
  10502. *
  10503. * @param {Vector3} target - The target vector the result is stored to.
  10504. * @return {Vector3} The 3D object's position in world space.
  10505. */
  10506. getWorldPosition( target ) {
  10507. this.updateWorldMatrix( true, false );
  10508. return target.setFromMatrixPosition( this.matrixWorld );
  10509. }
  10510. /**
  10511. * Returns a Quaternion representing the position of the 3D object in world space.
  10512. *
  10513. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10514. * @return {Quaternion} The 3D object's rotation in world space.
  10515. */
  10516. getWorldQuaternion( target ) {
  10517. this.updateWorldMatrix( true, false );
  10518. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10519. return target;
  10520. }
  10521. /**
  10522. * Returns a vector representing the scale of the 3D object in world space.
  10523. *
  10524. * @param {Vector3} target - The target vector the result is stored to.
  10525. * @return {Vector3} The 3D object's scale in world space.
  10526. */
  10527. getWorldScale( target ) {
  10528. this.updateWorldMatrix( true, false );
  10529. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10530. return target;
  10531. }
  10532. /**
  10533. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10534. *
  10535. * @param {Vector3} target - The target vector the result is stored to.
  10536. * @return {Vector3} The 3D object's direction in world space.
  10537. */
  10538. getWorldDirection( target ) {
  10539. this.updateWorldMatrix( true, false );
  10540. const e = this.matrixWorld.elements;
  10541. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10542. }
  10543. /**
  10544. * Abstract method to get intersections between a casted ray and this
  10545. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10546. * implement this method in order to use raycasting.
  10547. *
  10548. * @abstract
  10549. * @param {Raycaster} raycaster - The raycaster.
  10550. * @param {Array<Object>} intersects - An array holding the result of the method.
  10551. */
  10552. raycast( /* raycaster, intersects */ ) {}
  10553. /**
  10554. * Executes the callback on this 3D object and all descendants.
  10555. *
  10556. * Note: Modifying the scene graph inside the callback is discouraged.
  10557. *
  10558. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10559. */
  10560. traverse( callback ) {
  10561. callback( this );
  10562. const children = this.children;
  10563. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10564. children[ i ].traverse( callback );
  10565. }
  10566. }
  10567. /**
  10568. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10569. * Descendants of invisible 3D objects are not traversed.
  10570. *
  10571. * Note: Modifying the scene graph inside the callback is discouraged.
  10572. *
  10573. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10574. */
  10575. traverseVisible( callback ) {
  10576. if ( this.visible === false ) return;
  10577. callback( this );
  10578. const children = this.children;
  10579. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10580. children[ i ].traverseVisible( callback );
  10581. }
  10582. }
  10583. /**
  10584. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10585. *
  10586. * Note: Modifying the scene graph inside the callback is discouraged.
  10587. *
  10588. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10589. */
  10590. traverseAncestors( callback ) {
  10591. const parent = this.parent;
  10592. if ( parent !== null ) {
  10593. callback( parent );
  10594. parent.traverseAncestors( callback );
  10595. }
  10596. }
  10597. /**
  10598. * Updates the transformation matrix in local space by computing it from the current
  10599. * position, rotation and scale values.
  10600. */
  10601. updateMatrix() {
  10602. this.matrix.compose( this.position, this.quaternion, this.scale );
  10603. this.matrixWorldNeedsUpdate = true;
  10604. }
  10605. /**
  10606. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10607. *
  10608. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10609. * local space. The computation of the local and world matrix can be controlled with the
  10610. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10611. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10612. *
  10613. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10614. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10615. */
  10616. updateMatrixWorld( force ) {
  10617. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10618. if ( this.matrixWorldNeedsUpdate || force ) {
  10619. if ( this.matrixWorldAutoUpdate === true ) {
  10620. if ( this.parent === null ) {
  10621. this.matrixWorld.copy( this.matrix );
  10622. } else {
  10623. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10624. }
  10625. }
  10626. this.matrixWorldNeedsUpdate = false;
  10627. force = true;
  10628. }
  10629. // make sure descendants are updated if required
  10630. const children = this.children;
  10631. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10632. const child = children[ i ];
  10633. child.updateMatrixWorld( force );
  10634. }
  10635. }
  10636. /**
  10637. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10638. * update of ancestor and descendant nodes.
  10639. *
  10640. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10641. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10642. */
  10643. updateWorldMatrix( updateParents, updateChildren ) {
  10644. const parent = this.parent;
  10645. if ( updateParents === true && parent !== null ) {
  10646. parent.updateWorldMatrix( true, false );
  10647. }
  10648. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10649. if ( this.matrixWorldAutoUpdate === true ) {
  10650. if ( this.parent === null ) {
  10651. this.matrixWorld.copy( this.matrix );
  10652. } else {
  10653. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10654. }
  10655. }
  10656. // make sure descendants are updated
  10657. if ( updateChildren === true ) {
  10658. const children = this.children;
  10659. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10660. const child = children[ i ];
  10661. child.updateWorldMatrix( false, true );
  10662. }
  10663. }
  10664. }
  10665. /**
  10666. * Serializes the 3D object into JSON.
  10667. *
  10668. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10669. * @return {Object} A JSON object representing the serialized 3D object.
  10670. * @see {@link ObjectLoader#parse}
  10671. */
  10672. toJSON( meta ) {
  10673. // meta is a string when called from JSON.stringify
  10674. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10675. const output = {};
  10676. // meta is a hash used to collect geometries, materials.
  10677. // not providing it implies that this is the root object
  10678. // being serialized.
  10679. if ( isRootObject ) {
  10680. // initialize meta obj
  10681. meta = {
  10682. geometries: {},
  10683. materials: {},
  10684. textures: {},
  10685. images: {},
  10686. shapes: {},
  10687. skeletons: {},
  10688. animations: {},
  10689. nodes: {}
  10690. };
  10691. output.metadata = {
  10692. version: 4.6,
  10693. type: 'Object',
  10694. generator: 'Object3D.toJSON'
  10695. };
  10696. }
  10697. // standard Object3D serialization
  10698. const object = {};
  10699. object.uuid = this.uuid;
  10700. object.type = this.type;
  10701. if ( this.name !== '' ) object.name = this.name;
  10702. if ( this.castShadow === true ) object.castShadow = true;
  10703. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10704. if ( this.visible === false ) object.visible = false;
  10705. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10706. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10707. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10708. object.layers = this.layers.mask;
  10709. object.matrix = this.matrix.toArray();
  10710. object.up = this.up.toArray();
  10711. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10712. // object specific properties
  10713. if ( this.isInstancedMesh ) {
  10714. object.type = 'InstancedMesh';
  10715. object.count = this.count;
  10716. object.instanceMatrix = this.instanceMatrix.toJSON();
  10717. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10718. }
  10719. if ( this.isBatchedMesh ) {
  10720. object.type = 'BatchedMesh';
  10721. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10722. object.sortObjects = this.sortObjects;
  10723. object.drawRanges = this._drawRanges;
  10724. object.reservedRanges = this._reservedRanges;
  10725. object.visibility = this._visibility;
  10726. object.active = this._active;
  10727. object.bounds = this._bounds.map( bound => ( {
  10728. boxInitialized: bound.boxInitialized,
  10729. boxMin: bound.box.min.toArray(),
  10730. boxMax: bound.box.max.toArray(),
  10731. sphereInitialized: bound.sphereInitialized,
  10732. sphereRadius: bound.sphere.radius,
  10733. sphereCenter: bound.sphere.center.toArray()
  10734. } ) );
  10735. object.maxInstanceCount = this._maxInstanceCount;
  10736. object.maxVertexCount = this._maxVertexCount;
  10737. object.maxIndexCount = this._maxIndexCount;
  10738. object.geometryInitialized = this._geometryInitialized;
  10739. object.geometryCount = this._geometryCount;
  10740. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10741. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  10742. if ( this.boundingSphere !== null ) {
  10743. object.boundingSphere = {
  10744. center: object.boundingSphere.center.toArray(),
  10745. radius: object.boundingSphere.radius
  10746. };
  10747. }
  10748. if ( this.boundingBox !== null ) {
  10749. object.boundingBox = {
  10750. min: object.boundingBox.min.toArray(),
  10751. max: object.boundingBox.max.toArray()
  10752. };
  10753. }
  10754. }
  10755. //
  10756. function serialize( library, element ) {
  10757. if ( library[ element.uuid ] === undefined ) {
  10758. library[ element.uuid ] = element.toJSON( meta );
  10759. }
  10760. return element.uuid;
  10761. }
  10762. if ( this.isScene ) {
  10763. if ( this.background ) {
  10764. if ( this.background.isColor ) {
  10765. object.background = this.background.toJSON();
  10766. } else if ( this.background.isTexture ) {
  10767. object.background = this.background.toJSON( meta ).uuid;
  10768. }
  10769. }
  10770. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10771. object.environment = this.environment.toJSON( meta ).uuid;
  10772. }
  10773. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10774. object.geometry = serialize( meta.geometries, this.geometry );
  10775. const parameters = this.geometry.parameters;
  10776. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10777. const shapes = parameters.shapes;
  10778. if ( Array.isArray( shapes ) ) {
  10779. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10780. const shape = shapes[ i ];
  10781. serialize( meta.shapes, shape );
  10782. }
  10783. } else {
  10784. serialize( meta.shapes, shapes );
  10785. }
  10786. }
  10787. }
  10788. if ( this.isSkinnedMesh ) {
  10789. object.bindMode = this.bindMode;
  10790. object.bindMatrix = this.bindMatrix.toArray();
  10791. if ( this.skeleton !== undefined ) {
  10792. serialize( meta.skeletons, this.skeleton );
  10793. object.skeleton = this.skeleton.uuid;
  10794. }
  10795. }
  10796. if ( this.material !== undefined ) {
  10797. if ( Array.isArray( this.material ) ) {
  10798. const uuids = [];
  10799. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10800. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10801. }
  10802. object.material = uuids;
  10803. } else {
  10804. object.material = serialize( meta.materials, this.material );
  10805. }
  10806. }
  10807. //
  10808. if ( this.children.length > 0 ) {
  10809. object.children = [];
  10810. for ( let i = 0; i < this.children.length; i ++ ) {
  10811. object.children.push( this.children[ i ].toJSON( meta ).object );
  10812. }
  10813. }
  10814. //
  10815. if ( this.animations.length > 0 ) {
  10816. object.animations = [];
  10817. for ( let i = 0; i < this.animations.length; i ++ ) {
  10818. const animation = this.animations[ i ];
  10819. object.animations.push( serialize( meta.animations, animation ) );
  10820. }
  10821. }
  10822. if ( isRootObject ) {
  10823. const geometries = extractFromCache( meta.geometries );
  10824. const materials = extractFromCache( meta.materials );
  10825. const textures = extractFromCache( meta.textures );
  10826. const images = extractFromCache( meta.images );
  10827. const shapes = extractFromCache( meta.shapes );
  10828. const skeletons = extractFromCache( meta.skeletons );
  10829. const animations = extractFromCache( meta.animations );
  10830. const nodes = extractFromCache( meta.nodes );
  10831. if ( geometries.length > 0 ) output.geometries = geometries;
  10832. if ( materials.length > 0 ) output.materials = materials;
  10833. if ( textures.length > 0 ) output.textures = textures;
  10834. if ( images.length > 0 ) output.images = images;
  10835. if ( shapes.length > 0 ) output.shapes = shapes;
  10836. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10837. if ( animations.length > 0 ) output.animations = animations;
  10838. if ( nodes.length > 0 ) output.nodes = nodes;
  10839. }
  10840. output.object = object;
  10841. return output;
  10842. // extract data from the cache hash
  10843. // remove metadata on each item
  10844. // and return as array
  10845. function extractFromCache( cache ) {
  10846. const values = [];
  10847. for ( const key in cache ) {
  10848. const data = cache[ key ];
  10849. delete data.metadata;
  10850. values.push( data );
  10851. }
  10852. return values;
  10853. }
  10854. }
  10855. /**
  10856. * Returns a new 3D object with copied values from this instance.
  10857. *
  10858. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10859. * @return {Object3D} A clone of this instance.
  10860. */
  10861. clone( recursive ) {
  10862. return new this.constructor().copy( this, recursive );
  10863. }
  10864. /**
  10865. * Copies the values of the given 3D object to this instance.
  10866. *
  10867. * @param {Object3D} source - The 3D object to copy.
  10868. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10869. * @return {Object3D} A reference to this instance.
  10870. */
  10871. copy( source, recursive = true ) {
  10872. this.name = source.name;
  10873. this.up.copy( source.up );
  10874. this.position.copy( source.position );
  10875. this.rotation.order = source.rotation.order;
  10876. this.quaternion.copy( source.quaternion );
  10877. this.scale.copy( source.scale );
  10878. this.matrix.copy( source.matrix );
  10879. this.matrixWorld.copy( source.matrixWorld );
  10880. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10881. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10882. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10883. this.layers.mask = source.layers.mask;
  10884. this.visible = source.visible;
  10885. this.castShadow = source.castShadow;
  10886. this.receiveShadow = source.receiveShadow;
  10887. this.frustumCulled = source.frustumCulled;
  10888. this.renderOrder = source.renderOrder;
  10889. this.animations = source.animations.slice();
  10890. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10891. if ( recursive === true ) {
  10892. for ( let i = 0; i < source.children.length; i ++ ) {
  10893. const child = source.children[ i ];
  10894. this.add( child.clone() );
  10895. }
  10896. }
  10897. return this;
  10898. }
  10899. }
  10900. /**
  10901. * The default up direction for objects, also used as the default
  10902. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10903. *
  10904. * @static
  10905. * @type {Vector3}
  10906. * @default (0,1,0)
  10907. */
  10908. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10909. /**
  10910. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10911. * newly created 3D objects.
  10912. *
  10913. * @static
  10914. * @type {boolean}
  10915. * @default true
  10916. */
  10917. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10918. /**
  10919. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10920. * newly created 3D objects.
  10921. *
  10922. * @static
  10923. * @type {boolean}
  10924. * @default true
  10925. */
  10926. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10927. const _v0$2 = /*@__PURE__*/ new Vector3();
  10928. const _v1$3 = /*@__PURE__*/ new Vector3();
  10929. const _v2$2 = /*@__PURE__*/ new Vector3();
  10930. const _v3$2 = /*@__PURE__*/ new Vector3();
  10931. const _vab = /*@__PURE__*/ new Vector3();
  10932. const _vac = /*@__PURE__*/ new Vector3();
  10933. const _vbc = /*@__PURE__*/ new Vector3();
  10934. const _vap = /*@__PURE__*/ new Vector3();
  10935. const _vbp = /*@__PURE__*/ new Vector3();
  10936. const _vcp = /*@__PURE__*/ new Vector3();
  10937. const _v40 = /*@__PURE__*/ new Vector4();
  10938. const _v41 = /*@__PURE__*/ new Vector4();
  10939. const _v42 = /*@__PURE__*/ new Vector4();
  10940. /**
  10941. * A geometric triangle as defined by three vectors representing its three corners.
  10942. */
  10943. class Triangle {
  10944. /**
  10945. * Constructs a new triangle.
  10946. *
  10947. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  10948. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  10949. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  10950. */
  10951. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  10952. /**
  10953. * The first corner of the triangle.
  10954. *
  10955. * @type {Vector3}
  10956. */
  10957. this.a = a;
  10958. /**
  10959. * The second corner of the triangle.
  10960. *
  10961. * @type {Vector3}
  10962. */
  10963. this.b = b;
  10964. /**
  10965. * The third corner of the triangle.
  10966. *
  10967. * @type {Vector3}
  10968. */
  10969. this.c = c;
  10970. }
  10971. /**
  10972. * Computes the normal vector of a triangle.
  10973. *
  10974. * @param {Vector3} a - The first corner of the triangle.
  10975. * @param {Vector3} b - The second corner of the triangle.
  10976. * @param {Vector3} c - The third corner of the triangle.
  10977. * @param {Vector3} target - The target vector that is used to store the method's result.
  10978. * @return {Vector3} The triangle's normal.
  10979. */
  10980. static getNormal( a, b, c, target ) {
  10981. target.subVectors( c, b );
  10982. _v0$2.subVectors( a, b );
  10983. target.cross( _v0$2 );
  10984. const targetLengthSq = target.lengthSq();
  10985. if ( targetLengthSq > 0 ) {
  10986. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  10987. }
  10988. return target.set( 0, 0, 0 );
  10989. }
  10990. /**
  10991. * Computes a barycentric coordinates from the given vector.
  10992. * Returns `null` if the triangle is degenerate.
  10993. *
  10994. * @param {Vector3} point - A point in 3D space.
  10995. * @param {Vector3} a - The first corner of the triangle.
  10996. * @param {Vector3} b - The second corner of the triangle.
  10997. * @param {Vector3} c - The third corner of the triangle.
  10998. * @param {Vector3} target - The target vector that is used to store the method's result.
  10999. * @return {?Vector3} The barycentric coordinates for the given point
  11000. */
  11001. static getBarycoord( point, a, b, c, target ) {
  11002. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11003. _v0$2.subVectors( c, a );
  11004. _v1$3.subVectors( b, a );
  11005. _v2$2.subVectors( point, a );
  11006. const dot00 = _v0$2.dot( _v0$2 );
  11007. const dot01 = _v0$2.dot( _v1$3 );
  11008. const dot02 = _v0$2.dot( _v2$2 );
  11009. const dot11 = _v1$3.dot( _v1$3 );
  11010. const dot12 = _v1$3.dot( _v2$2 );
  11011. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11012. // collinear or singular triangle
  11013. if ( denom === 0 ) {
  11014. target.set( 0, 0, 0 );
  11015. return null;
  11016. }
  11017. const invDenom = 1 / denom;
  11018. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11019. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11020. // barycentric coordinates must always sum to 1
  11021. return target.set( 1 - u - v, v, u );
  11022. }
  11023. /**
  11024. * Returns `true` if the given point, when projected onto the plane of the
  11025. * triangle, lies within the triangle.
  11026. *
  11027. * @param {Vector3} point - The point in 3D space to test.
  11028. * @param {Vector3} a - The first corner of the triangle.
  11029. * @param {Vector3} b - The second corner of the triangle.
  11030. * @param {Vector3} c - The third corner of the triangle.
  11031. * @return {boolean} Whether the given point, when projected onto the plane of the
  11032. * triangle, lies within the triangle or not.
  11033. */
  11034. static containsPoint( point, a, b, c ) {
  11035. // if the triangle is degenerate then we can't contain a point
  11036. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11037. return false;
  11038. }
  11039. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11040. }
  11041. /**
  11042. * Computes the value barycentrically interpolated for the given point on the
  11043. * triangle. Returns `null` if the triangle is degenerate.
  11044. *
  11045. * @param {Vector3} point - Position of interpolated point.
  11046. * @param {Vector3} p1 - The first corner of the triangle.
  11047. * @param {Vector3} p2 - The second corner of the triangle.
  11048. * @param {Vector3} p3 - The third corner of the triangle.
  11049. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11050. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11051. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11052. * @param {Vector3} target - The target vector that is used to store the method's result.
  11053. * @return {?Vector3} The interpolated value.
  11054. */
  11055. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11056. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11057. target.x = 0;
  11058. target.y = 0;
  11059. if ( 'z' in target ) target.z = 0;
  11060. if ( 'w' in target ) target.w = 0;
  11061. return null;
  11062. }
  11063. target.setScalar( 0 );
  11064. target.addScaledVector( v1, _v3$2.x );
  11065. target.addScaledVector( v2, _v3$2.y );
  11066. target.addScaledVector( v3, _v3$2.z );
  11067. return target;
  11068. }
  11069. /**
  11070. * Computes the value barycentrically interpolated for the given attribute and indices.
  11071. *
  11072. * @param {BufferAttribute} attr - The attribute to interpolate.
  11073. * @param {number} i1 - Index of first vertex.
  11074. * @param {number} i2 - Index of second vertex.
  11075. * @param {number} i3 - Index of third vertex.
  11076. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11077. * @param {Vector3} target - The target vector that is used to store the method's result.
  11078. * @return {Vector3} The interpolated attribute value.
  11079. */
  11080. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11081. _v40.setScalar( 0 );
  11082. _v41.setScalar( 0 );
  11083. _v42.setScalar( 0 );
  11084. _v40.fromBufferAttribute( attr, i1 );
  11085. _v41.fromBufferAttribute( attr, i2 );
  11086. _v42.fromBufferAttribute( attr, i3 );
  11087. target.setScalar( 0 );
  11088. target.addScaledVector( _v40, barycoord.x );
  11089. target.addScaledVector( _v41, barycoord.y );
  11090. target.addScaledVector( _v42, barycoord.z );
  11091. return target;
  11092. }
  11093. /**
  11094. * Returns `true` if the triangle is oriented towards the given direction.
  11095. *
  11096. * @param {Vector3} a - The first corner of the triangle.
  11097. * @param {Vector3} b - The second corner of the triangle.
  11098. * @param {Vector3} c - The third corner of the triangle.
  11099. * @param {Vector3} direction - The (normalized) direction vector.
  11100. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11101. */
  11102. static isFrontFacing( a, b, c, direction ) {
  11103. _v0$2.subVectors( c, b );
  11104. _v1$3.subVectors( a, b );
  11105. // strictly front facing
  11106. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11107. }
  11108. /**
  11109. * Sets the triangle's vertices by copying the given values.
  11110. *
  11111. * @param {Vector3} a - The first corner of the triangle.
  11112. * @param {Vector3} b - The second corner of the triangle.
  11113. * @param {Vector3} c - The third corner of the triangle.
  11114. * @return {Triangle} A reference to this triangle.
  11115. */
  11116. set( a, b, c ) {
  11117. this.a.copy( a );
  11118. this.b.copy( b );
  11119. this.c.copy( c );
  11120. return this;
  11121. }
  11122. /**
  11123. * Sets the triangle's vertices by copying the given array values.
  11124. *
  11125. * @param {Array<Vector3>} points - An array with 3D points.
  11126. * @param {number} i0 - The array index representing the first corner of the triangle.
  11127. * @param {number} i1 - The array index representing the second corner of the triangle.
  11128. * @param {number} i2 - The array index representing the third corner of the triangle.
  11129. * @return {Triangle} A reference to this triangle.
  11130. */
  11131. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11132. this.a.copy( points[ i0 ] );
  11133. this.b.copy( points[ i1 ] );
  11134. this.c.copy( points[ i2 ] );
  11135. return this;
  11136. }
  11137. /**
  11138. * Sets the triangle's vertices by copying the given attribute values.
  11139. *
  11140. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11141. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11142. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11143. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11144. * @return {Triangle} A reference to this triangle.
  11145. */
  11146. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11147. this.a.fromBufferAttribute( attribute, i0 );
  11148. this.b.fromBufferAttribute( attribute, i1 );
  11149. this.c.fromBufferAttribute( attribute, i2 );
  11150. return this;
  11151. }
  11152. /**
  11153. * Returns a new triangle with copied values from this instance.
  11154. *
  11155. * @return {Triangle} A clone of this instance.
  11156. */
  11157. clone() {
  11158. return new this.constructor().copy( this );
  11159. }
  11160. /**
  11161. * Copies the values of the given triangle to this instance.
  11162. *
  11163. * @param {Triangle} triangle - The triangle to copy.
  11164. * @return {Triangle} A reference to this triangle.
  11165. */
  11166. copy( triangle ) {
  11167. this.a.copy( triangle.a );
  11168. this.b.copy( triangle.b );
  11169. this.c.copy( triangle.c );
  11170. return this;
  11171. }
  11172. /**
  11173. * Computes the area of the triangle.
  11174. *
  11175. * @return {number} The triangle's area.
  11176. */
  11177. getArea() {
  11178. _v0$2.subVectors( this.c, this.b );
  11179. _v1$3.subVectors( this.a, this.b );
  11180. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11181. }
  11182. /**
  11183. * Computes the midpoint of the triangle.
  11184. *
  11185. * @param {Vector3} target - The target vector that is used to store the method's result.
  11186. * @return {Vector3} The triangle's midpoint.
  11187. */
  11188. getMidpoint( target ) {
  11189. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11190. }
  11191. /**
  11192. * Computes the normal of the triangle.
  11193. *
  11194. * @param {Vector3} target - The target vector that is used to store the method's result.
  11195. * @return {Vector3} The triangle's normal.
  11196. */
  11197. getNormal( target ) {
  11198. return Triangle.getNormal( this.a, this.b, this.c, target );
  11199. }
  11200. /**
  11201. * Computes a plane the triangle lies within.
  11202. *
  11203. * @param {Plane} target - The target vector that is used to store the method's result.
  11204. * @return {Plane} The plane the triangle lies within.
  11205. */
  11206. getPlane( target ) {
  11207. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11208. }
  11209. /**
  11210. * Computes a barycentric coordinates from the given vector.
  11211. * Returns `null` if the triangle is degenerate.
  11212. *
  11213. * @param {Vector3} point - A point in 3D space.
  11214. * @param {Vector3} target - The target vector that is used to store the method's result.
  11215. * @return {?Vector3} The barycentric coordinates for the given point
  11216. */
  11217. getBarycoord( point, target ) {
  11218. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11219. }
  11220. /**
  11221. * Computes the value barycentrically interpolated for the given point on the
  11222. * triangle. Returns `null` if the triangle is degenerate.
  11223. *
  11224. * @param {Vector3} point - Position of interpolated point.
  11225. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11226. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11227. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11228. * @param {Vector3} target - The target vector that is used to store the method's result.
  11229. * @return {?Vector3} The interpolated value.
  11230. */
  11231. getInterpolation( point, v1, v2, v3, target ) {
  11232. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11233. }
  11234. /**
  11235. * Returns `true` if the given point, when projected onto the plane of the
  11236. * triangle, lies within the triangle.
  11237. *
  11238. * @param {Vector3} point - The point in 3D space to test.
  11239. * @return {boolean} Whether the given point, when projected onto the plane of the
  11240. * triangle, lies within the triangle or not.
  11241. */
  11242. containsPoint( point ) {
  11243. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11244. }
  11245. /**
  11246. * Returns `true` if the triangle is oriented towards the given direction.
  11247. *
  11248. * @param {Vector3} direction - The (normalized) direction vector.
  11249. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11250. */
  11251. isFrontFacing( direction ) {
  11252. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11253. }
  11254. /**
  11255. * Returns `true` if this triangle intersects with the given box.
  11256. *
  11257. * @param {Box3} box - The box to intersect.
  11258. * @return {boolean} Whether this triangle intersects with the given box or not.
  11259. */
  11260. intersectsBox( box ) {
  11261. return box.intersectsTriangle( this );
  11262. }
  11263. /**
  11264. * Returns the closest point on the triangle to the given point.
  11265. *
  11266. * @param {Vector3} p - The point to compute the closest point for.
  11267. * @param {Vector3} target - The target vector that is used to store the method's result.
  11268. * @return {Vector3} The closest point on the triangle.
  11269. */
  11270. closestPointToPoint( p, target ) {
  11271. const a = this.a, b = this.b, c = this.c;
  11272. let v, w;
  11273. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11274. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11275. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11276. // basically, we're distinguishing which of the voronoi regions of the triangle
  11277. // the point lies in with the minimum amount of redundant computation.
  11278. _vab.subVectors( b, a );
  11279. _vac.subVectors( c, a );
  11280. _vap.subVectors( p, a );
  11281. const d1 = _vab.dot( _vap );
  11282. const d2 = _vac.dot( _vap );
  11283. if ( d1 <= 0 && d2 <= 0 ) {
  11284. // vertex region of A; barycentric coords (1, 0, 0)
  11285. return target.copy( a );
  11286. }
  11287. _vbp.subVectors( p, b );
  11288. const d3 = _vab.dot( _vbp );
  11289. const d4 = _vac.dot( _vbp );
  11290. if ( d3 >= 0 && d4 <= d3 ) {
  11291. // vertex region of B; barycentric coords (0, 1, 0)
  11292. return target.copy( b );
  11293. }
  11294. const vc = d1 * d4 - d3 * d2;
  11295. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11296. v = d1 / ( d1 - d3 );
  11297. // edge region of AB; barycentric coords (1-v, v, 0)
  11298. return target.copy( a ).addScaledVector( _vab, v );
  11299. }
  11300. _vcp.subVectors( p, c );
  11301. const d5 = _vab.dot( _vcp );
  11302. const d6 = _vac.dot( _vcp );
  11303. if ( d6 >= 0 && d5 <= d6 ) {
  11304. // vertex region of C; barycentric coords (0, 0, 1)
  11305. return target.copy( c );
  11306. }
  11307. const vb = d5 * d2 - d1 * d6;
  11308. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11309. w = d2 / ( d2 - d6 );
  11310. // edge region of AC; barycentric coords (1-w, 0, w)
  11311. return target.copy( a ).addScaledVector( _vac, w );
  11312. }
  11313. const va = d3 * d6 - d5 * d4;
  11314. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11315. _vbc.subVectors( c, b );
  11316. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11317. // edge region of BC; barycentric coords (0, 1-w, w)
  11318. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11319. }
  11320. // face region
  11321. const denom = 1 / ( va + vb + vc );
  11322. // u = va * denom
  11323. v = vb * denom;
  11324. w = vc * denom;
  11325. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11326. }
  11327. /**
  11328. * Returns `true` if this triangle is equal with the given one.
  11329. *
  11330. * @param {Triangle} triangle - The triangle to test for equality.
  11331. * @return {boolean} Whether this triangle is equal with the given one.
  11332. */
  11333. equals( triangle ) {
  11334. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11335. }
  11336. }
  11337. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11338. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11339. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11340. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11341. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11342. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11343. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11344. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11345. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11346. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11347. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11348. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11349. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11350. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11351. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11352. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11353. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11354. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11355. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11356. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11357. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11358. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11359. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11360. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11361. const _hslA = { h: 0, s: 0, l: 0 };
  11362. const _hslB = { h: 0, s: 0, l: 0 };
  11363. function hue2rgb( p, q, t ) {
  11364. if ( t < 0 ) t += 1;
  11365. if ( t > 1 ) t -= 1;
  11366. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11367. if ( t < 1 / 2 ) return q;
  11368. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11369. return p;
  11370. }
  11371. /**
  11372. * A Color instance is represented by RGB components in the linear <i>working
  11373. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11374. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11375. * strings) are converted to the working color space automatically.
  11376. *
  11377. * ```js
  11378. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11379. * const color = new THREE.Color().setHex( 0x112233 );
  11380. * ```
  11381. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11382. * ```js
  11383. * // assumed already LinearSRGBColorSpace; no conversion
  11384. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11385. *
  11386. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11387. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11388. * ```
  11389. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11390. * see <i>Color management</i>. Iterating through a Color instance will yield
  11391. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11392. * in any of the following ways:
  11393. * ```js
  11394. * //empty constructor - will default white
  11395. * const color1 = new THREE.Color();
  11396. *
  11397. * //Hexadecimal color (recommended)
  11398. * const color2 = new THREE.Color( 0xff0000 );
  11399. *
  11400. * //RGB string
  11401. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11402. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11403. *
  11404. * //X11 color name - all 140 color names are supported.
  11405. * //Note the lack of CamelCase in the name
  11406. * const color5 = new THREE.Color( 'skyblue' );
  11407. * //HSL string
  11408. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11409. *
  11410. * //Separate RGB values between 0 and 1
  11411. * const color7 = new THREE.Color( 1, 0, 0 );
  11412. * ```
  11413. */
  11414. class Color {
  11415. /**
  11416. * Constructs a new color.
  11417. *
  11418. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11419. * and that method is used throughout the rest of the documentation.
  11420. *
  11421. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11422. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11423. * @param {number} [g] - The green component.
  11424. * @param {number} [b] - The blue component.
  11425. */
  11426. constructor( r, g, b ) {
  11427. /**
  11428. * This flag can be used for type testing.
  11429. *
  11430. * @type {boolean}
  11431. * @readonly
  11432. * @default true
  11433. */
  11434. this.isColor = true;
  11435. /**
  11436. * The red component.
  11437. *
  11438. * @type {number}
  11439. * @default 1
  11440. */
  11441. this.r = 1;
  11442. /**
  11443. * The green component.
  11444. *
  11445. * @type {number}
  11446. * @default 1
  11447. */
  11448. this.g = 1;
  11449. /**
  11450. * The blue component.
  11451. *
  11452. * @type {number}
  11453. * @default 1
  11454. */
  11455. this.b = 1;
  11456. return this.set( r, g, b );
  11457. }
  11458. /**
  11459. * Sets the colors's components from the given values.
  11460. *
  11461. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11462. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11463. * @param {number} [g] - The green component.
  11464. * @param {number} [b] - The blue component.
  11465. * @return {Color} A reference to this color.
  11466. */
  11467. set( r, g, b ) {
  11468. if ( g === undefined && b === undefined ) {
  11469. // r is THREE.Color, hex or string
  11470. const value = r;
  11471. if ( value && value.isColor ) {
  11472. this.copy( value );
  11473. } else if ( typeof value === 'number' ) {
  11474. this.setHex( value );
  11475. } else if ( typeof value === 'string' ) {
  11476. this.setStyle( value );
  11477. }
  11478. } else {
  11479. this.setRGB( r, g, b );
  11480. }
  11481. return this;
  11482. }
  11483. /**
  11484. * Sets the colors's components to the given scalar value.
  11485. *
  11486. * @param {number} scalar - The scalar value.
  11487. * @return {Color} A reference to this color.
  11488. */
  11489. setScalar( scalar ) {
  11490. this.r = scalar;
  11491. this.g = scalar;
  11492. this.b = scalar;
  11493. return this;
  11494. }
  11495. /**
  11496. * Sets this color from a hexadecimal value.
  11497. *
  11498. * @param {number} hex - The hexadecimal value.
  11499. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11500. * @return {Color} A reference to this color.
  11501. */
  11502. setHex( hex, colorSpace = SRGBColorSpace ) {
  11503. hex = Math.floor( hex );
  11504. this.r = ( hex >> 16 & 255 ) / 255;
  11505. this.g = ( hex >> 8 & 255 ) / 255;
  11506. this.b = ( hex & 255 ) / 255;
  11507. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11508. return this;
  11509. }
  11510. /**
  11511. * Sets this color from RGB values.
  11512. *
  11513. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11514. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11515. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11516. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11517. * @return {Color} A reference to this color.
  11518. */
  11519. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11520. this.r = r;
  11521. this.g = g;
  11522. this.b = b;
  11523. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11524. return this;
  11525. }
  11526. /**
  11527. * Sets this color from RGB values.
  11528. *
  11529. * @param {number} h - Hue value between `0.0` and `1.0`.
  11530. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11531. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11532. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11533. * @return {Color} A reference to this color.
  11534. */
  11535. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11536. // h,s,l ranges are in 0.0 - 1.0
  11537. h = euclideanModulo( h, 1 );
  11538. s = clamp( s, 0, 1 );
  11539. l = clamp( l, 0, 1 );
  11540. if ( s === 0 ) {
  11541. this.r = this.g = this.b = l;
  11542. } else {
  11543. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11544. const q = ( 2 * l ) - p;
  11545. this.r = hue2rgb( q, p, h + 1 / 3 );
  11546. this.g = hue2rgb( q, p, h );
  11547. this.b = hue2rgb( q, p, h - 1 / 3 );
  11548. }
  11549. ColorManagement.toWorkingColorSpace( this, colorSpace );
  11550. return this;
  11551. }
  11552. /**
  11553. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11554. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11555. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11556. * all 140 color names are supported).
  11557. *
  11558. * @param {string} style - Color as a CSS-style string.
  11559. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11560. * @return {Color} A reference to this color.
  11561. */
  11562. setStyle( style, colorSpace = SRGBColorSpace ) {
  11563. function handleAlpha( string ) {
  11564. if ( string === undefined ) return;
  11565. if ( parseFloat( string ) < 1 ) {
  11566. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11567. }
  11568. }
  11569. let m;
  11570. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11571. // rgb / hsl
  11572. let color;
  11573. const name = m[ 1 ];
  11574. const components = m[ 2 ];
  11575. switch ( name ) {
  11576. case 'rgb':
  11577. case 'rgba':
  11578. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11579. // rgb(255,0,0) rgba(255,0,0,0.5)
  11580. handleAlpha( color[ 4 ] );
  11581. return this.setRGB(
  11582. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11583. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11584. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11585. colorSpace
  11586. );
  11587. }
  11588. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11589. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11590. handleAlpha( color[ 4 ] );
  11591. return this.setRGB(
  11592. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11593. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11594. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11595. colorSpace
  11596. );
  11597. }
  11598. break;
  11599. case 'hsl':
  11600. case 'hsla':
  11601. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11602. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11603. handleAlpha( color[ 4 ] );
  11604. return this.setHSL(
  11605. parseFloat( color[ 1 ] ) / 360,
  11606. parseFloat( color[ 2 ] ) / 100,
  11607. parseFloat( color[ 3 ] ) / 100,
  11608. colorSpace
  11609. );
  11610. }
  11611. break;
  11612. default:
  11613. console.warn( 'THREE.Color: Unknown color model ' + style );
  11614. }
  11615. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11616. // hex color
  11617. const hex = m[ 1 ];
  11618. const size = hex.length;
  11619. if ( size === 3 ) {
  11620. // #ff0
  11621. return this.setRGB(
  11622. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11623. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11624. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11625. colorSpace
  11626. );
  11627. } else if ( size === 6 ) {
  11628. // #ff0000
  11629. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11630. } else {
  11631. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11632. }
  11633. } else if ( style && style.length > 0 ) {
  11634. return this.setColorName( style, colorSpace );
  11635. }
  11636. return this;
  11637. }
  11638. /**
  11639. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11640. * you don't need the other CSS-style formats.
  11641. *
  11642. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11643. * ```js
  11644. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11645. * ```
  11646. *
  11647. * @param {string} style - The color name.
  11648. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11649. * @return {Color} A reference to this color.
  11650. */
  11651. setColorName( style, colorSpace = SRGBColorSpace ) {
  11652. // color keywords
  11653. const hex = _colorKeywords[ style.toLowerCase() ];
  11654. if ( hex !== undefined ) {
  11655. // red
  11656. this.setHex( hex, colorSpace );
  11657. } else {
  11658. // unknown color
  11659. console.warn( 'THREE.Color: Unknown color ' + style );
  11660. }
  11661. return this;
  11662. }
  11663. /**
  11664. * Returns a new color with copied values from this instance.
  11665. *
  11666. * @return {Color} A clone of this instance.
  11667. */
  11668. clone() {
  11669. return new this.constructor( this.r, this.g, this.b );
  11670. }
  11671. /**
  11672. * Copies the values of the given color to this instance.
  11673. *
  11674. * @param {Color} color - The color to copy.
  11675. * @return {Color} A reference to this color.
  11676. */
  11677. copy( color ) {
  11678. this.r = color.r;
  11679. this.g = color.g;
  11680. this.b = color.b;
  11681. return this;
  11682. }
  11683. /**
  11684. * Copies the given color into this color, and then converts this color from
  11685. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11686. *
  11687. * @param {Color} color - The color to copy/convert.
  11688. * @return {Color} A reference to this color.
  11689. */
  11690. copySRGBToLinear( color ) {
  11691. this.r = SRGBToLinear( color.r );
  11692. this.g = SRGBToLinear( color.g );
  11693. this.b = SRGBToLinear( color.b );
  11694. return this;
  11695. }
  11696. /**
  11697. * Copies the given color into this color, and then converts this color from
  11698. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11699. *
  11700. * @param {Color} color - The color to copy/convert.
  11701. * @return {Color} A reference to this color.
  11702. */
  11703. copyLinearToSRGB( color ) {
  11704. this.r = LinearToSRGB( color.r );
  11705. this.g = LinearToSRGB( color.g );
  11706. this.b = LinearToSRGB( color.b );
  11707. return this;
  11708. }
  11709. /**
  11710. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11711. *
  11712. * @return {Color} A reference to this color.
  11713. */
  11714. convertSRGBToLinear() {
  11715. this.copySRGBToLinear( this );
  11716. return this;
  11717. }
  11718. /**
  11719. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11720. *
  11721. * @return {Color} A reference to this color.
  11722. */
  11723. convertLinearToSRGB() {
  11724. this.copyLinearToSRGB( this );
  11725. return this;
  11726. }
  11727. /**
  11728. * Returns the hexadecimal value of this color.
  11729. *
  11730. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11731. * @return {number} The hexadecimal value.
  11732. */
  11733. getHex( colorSpace = SRGBColorSpace ) {
  11734. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11735. 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 ) );
  11736. }
  11737. /**
  11738. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11739. *
  11740. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11741. * @return {string} The hexadecimal value as a string.
  11742. */
  11743. getHexString( colorSpace = SRGBColorSpace ) {
  11744. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  11745. }
  11746. /**
  11747. * Converts the colors RGB values into the HSL format and stores them into the
  11748. * given target object.
  11749. *
  11750. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11751. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11752. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11753. */
  11754. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11755. // h,s,l ranges are in 0.0 - 1.0
  11756. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11757. const r = _color.r, g = _color.g, b = _color.b;
  11758. const max = Math.max( r, g, b );
  11759. const min = Math.min( r, g, b );
  11760. let hue, saturation;
  11761. const lightness = ( min + max ) / 2.0;
  11762. if ( min === max ) {
  11763. hue = 0;
  11764. saturation = 0;
  11765. } else {
  11766. const delta = max - min;
  11767. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11768. switch ( max ) {
  11769. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11770. case g: hue = ( b - r ) / delta + 2; break;
  11771. case b: hue = ( r - g ) / delta + 4; break;
  11772. }
  11773. hue /= 6;
  11774. }
  11775. target.h = hue;
  11776. target.s = saturation;
  11777. target.l = lightness;
  11778. return target;
  11779. }
  11780. /**
  11781. * Returns the RGB values of this color and stores them into the given target object.
  11782. *
  11783. * @param {Color} target - The target color that is used to store the method's result.
  11784. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11785. * @return {Color} The RGB representation of this color.
  11786. */
  11787. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11788. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11789. target.r = _color.r;
  11790. target.g = _color.g;
  11791. target.b = _color.b;
  11792. return target;
  11793. }
  11794. /**
  11795. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11796. *
  11797. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11798. * @return {string} The CSS representation of this color.
  11799. */
  11800. getStyle( colorSpace = SRGBColorSpace ) {
  11801. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  11802. const r = _color.r, g = _color.g, b = _color.b;
  11803. if ( colorSpace !== SRGBColorSpace ) {
  11804. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  11805. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  11806. }
  11807. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  11808. }
  11809. /**
  11810. * Adds the given HSL values to this color's values.
  11811. * Internally, this converts the color's RGB values to HSL, adds HSL
  11812. * and then converts the color back to RGB.
  11813. *
  11814. * @param {number} h - Hue value between `0.0` and `1.0`.
  11815. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11816. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11817. * @return {Color} A reference to this color.
  11818. */
  11819. offsetHSL( h, s, l ) {
  11820. this.getHSL( _hslA );
  11821. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  11822. }
  11823. /**
  11824. * Adds the RGB values of the given color to the RGB values of this color.
  11825. *
  11826. * @param {Color} color - The color to add.
  11827. * @return {Color} A reference to this color.
  11828. */
  11829. add( color ) {
  11830. this.r += color.r;
  11831. this.g += color.g;
  11832. this.b += color.b;
  11833. return this;
  11834. }
  11835. /**
  11836. * Adds the RGB values of the given colors and stores the result in this instance.
  11837. *
  11838. * @param {Color} color1 - The first color.
  11839. * @param {Color} color2 - The second color.
  11840. * @return {Color} A reference to this color.
  11841. */
  11842. addColors( color1, color2 ) {
  11843. this.r = color1.r + color2.r;
  11844. this.g = color1.g + color2.g;
  11845. this.b = color1.b + color2.b;
  11846. return this;
  11847. }
  11848. /**
  11849. * Adds the given scalar value to the RGB values of this color.
  11850. *
  11851. * @param {number} s - The scalar to add.
  11852. * @return {Color} A reference to this color.
  11853. */
  11854. addScalar( s ) {
  11855. this.r += s;
  11856. this.g += s;
  11857. this.b += s;
  11858. return this;
  11859. }
  11860. /**
  11861. * Subtracts the RGB values of the given color from the RGB values of this color.
  11862. *
  11863. * @param {Color} color - The color to subtract.
  11864. * @return {Color} A reference to this color.
  11865. */
  11866. sub( color ) {
  11867. this.r = Math.max( 0, this.r - color.r );
  11868. this.g = Math.max( 0, this.g - color.g );
  11869. this.b = Math.max( 0, this.b - color.b );
  11870. return this;
  11871. }
  11872. /**
  11873. * Multiplies the RGB values of the given color with the RGB values of this color.
  11874. *
  11875. * @param {Color} color - The color to multiply.
  11876. * @return {Color} A reference to this color.
  11877. */
  11878. multiply( color ) {
  11879. this.r *= color.r;
  11880. this.g *= color.g;
  11881. this.b *= color.b;
  11882. return this;
  11883. }
  11884. /**
  11885. * Multiplies the given scalar value with the RGB values of this color.
  11886. *
  11887. * @param {number} s - The scalar to multiply.
  11888. * @return {Color} A reference to this color.
  11889. */
  11890. multiplyScalar( s ) {
  11891. this.r *= s;
  11892. this.g *= s;
  11893. this.b *= s;
  11894. return this;
  11895. }
  11896. /**
  11897. * Linearly interpolates this color's RGB values toward the RGB values of the
  11898. * given color. The alpha argument can be thought of as the ratio between
  11899. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11900. *
  11901. * @param {Color} color - The color to converge on.
  11902. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11903. * @return {Color} A reference to this color.
  11904. */
  11905. lerp( color, alpha ) {
  11906. this.r += ( color.r - this.r ) * alpha;
  11907. this.g += ( color.g - this.g ) * alpha;
  11908. this.b += ( color.b - this.b ) * alpha;
  11909. return this;
  11910. }
  11911. /**
  11912. * Linearly interpolates between the given colors and stores the result in this instance.
  11913. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11914. * is the first and `1.0` is the second color.
  11915. *
  11916. * @param {Color} color1 - The first color.
  11917. * @param {Color} color2 - The second color.
  11918. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11919. * @return {Color} A reference to this color.
  11920. */
  11921. lerpColors( color1, color2, alpha ) {
  11922. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11923. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11924. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11925. return this;
  11926. }
  11927. /**
  11928. * Linearly interpolates this color's HSL values toward the HSL values of the
  11929. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11930. * from one color to the other, but instead going through all the hues in between
  11931. * those two colors. The alpha argument can be thought of as the ratio between
  11932. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11933. *
  11934. * @param {Color} color - The color to converge on.
  11935. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11936. * @return {Color} A reference to this color.
  11937. */
  11938. lerpHSL( color, alpha ) {
  11939. this.getHSL( _hslA );
  11940. color.getHSL( _hslB );
  11941. const h = lerp( _hslA.h, _hslB.h, alpha );
  11942. const s = lerp( _hslA.s, _hslB.s, alpha );
  11943. const l = lerp( _hslA.l, _hslB.l, alpha );
  11944. this.setHSL( h, s, l );
  11945. return this;
  11946. }
  11947. /**
  11948. * Sets the color's RGB components from the given 3D vector.
  11949. *
  11950. * @param {Vector3} v - The vector to set.
  11951. * @return {Color} A reference to this color.
  11952. */
  11953. setFromVector3( v ) {
  11954. this.r = v.x;
  11955. this.g = v.y;
  11956. this.b = v.z;
  11957. return this;
  11958. }
  11959. /**
  11960. * Transforms this color with the given 3x3 matrix.
  11961. *
  11962. * @param {Matrix3} m - The matrix.
  11963. * @return {Color} A reference to this color.
  11964. */
  11965. applyMatrix3( m ) {
  11966. const r = this.r, g = this.g, b = this.b;
  11967. const e = m.elements;
  11968. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11969. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11970. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11971. return this;
  11972. }
  11973. /**
  11974. * Returns `true` if this color is equal with the given one.
  11975. *
  11976. * @param {Color} c - The color to test for equality.
  11977. * @return {boolean} Whether this bounding color is equal with the given one.
  11978. */
  11979. equals( c ) {
  11980. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11981. }
  11982. /**
  11983. * Sets this color's RGB components from the given array.
  11984. *
  11985. * @param {Array<number>} array - An array holding the RGB values.
  11986. * @param {number} [offset=0] - The offset into the array.
  11987. * @return {Color} A reference to this color.
  11988. */
  11989. fromArray( array, offset = 0 ) {
  11990. this.r = array[ offset ];
  11991. this.g = array[ offset + 1 ];
  11992. this.b = array[ offset + 2 ];
  11993. return this;
  11994. }
  11995. /**
  11996. * Writes the RGB components of this color to the given array. If no array is provided,
  11997. * the method returns a new instance.
  11998. *
  11999. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12000. * @param {number} [offset=0] - Index of the first element in the array.
  12001. * @return {Array<number>} The color components.
  12002. */
  12003. toArray( array = [], offset = 0 ) {
  12004. array[ offset ] = this.r;
  12005. array[ offset + 1 ] = this.g;
  12006. array[ offset + 2 ] = this.b;
  12007. return array;
  12008. }
  12009. /**
  12010. * Sets the components of this color from the given buffer attribute.
  12011. *
  12012. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12013. * @param {number} index - The index into the attribute.
  12014. * @return {Color} A reference to this color.
  12015. */
  12016. fromBufferAttribute( attribute, index ) {
  12017. this.r = attribute.getX( index );
  12018. this.g = attribute.getY( index );
  12019. this.b = attribute.getZ( index );
  12020. return this;
  12021. }
  12022. /**
  12023. * This methods defines the serialization result of this class. Returns the color
  12024. * as a hexadecimal value.
  12025. *
  12026. * @return {number} The hexadecimal value.
  12027. */
  12028. toJSON() {
  12029. return this.getHex();
  12030. }
  12031. *[ Symbol.iterator ]() {
  12032. yield this.r;
  12033. yield this.g;
  12034. yield this.b;
  12035. }
  12036. }
  12037. const _color = /*@__PURE__*/ new Color();
  12038. /**
  12039. * A dictionary with X11 color names.
  12040. *
  12041. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12042. *
  12043. * @static
  12044. * @type {Object}
  12045. */
  12046. Color.NAMES = _colorKeywords;
  12047. let _materialId = 0;
  12048. /**
  12049. * Abstract base class for materials.
  12050. *
  12051. * Materials define the appearance of renderable 3D objects.
  12052. *
  12053. * @abstract
  12054. * @augments EventDispatcher
  12055. */
  12056. class Material extends EventDispatcher {
  12057. /**
  12058. * Constructs a new material.
  12059. */
  12060. constructor() {
  12061. super();
  12062. /**
  12063. * This flag can be used for type testing.
  12064. *
  12065. * @type {boolean}
  12066. * @readonly
  12067. * @default true
  12068. */
  12069. this.isMaterial = true;
  12070. /**
  12071. * The ID of the material.
  12072. *
  12073. * @name Material#id
  12074. * @type {number}
  12075. * @readonly
  12076. */
  12077. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12078. /**
  12079. * The UUID of the material.
  12080. *
  12081. * @type {string}
  12082. * @readonly
  12083. */
  12084. this.uuid = generateUUID();
  12085. /**
  12086. * The name of the material.
  12087. *
  12088. * @type {string}
  12089. */
  12090. this.name = '';
  12091. /**
  12092. * The type property is used for detecting the object type
  12093. * in context of serialization/deserialization.
  12094. *
  12095. * @type {string}
  12096. * @readonly
  12097. */
  12098. this.type = 'Material';
  12099. /**
  12100. * Defines the blending type of the material.
  12101. *
  12102. * It must be set to `CustomBlending` if custom blending properties like
  12103. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12104. * should have any effect.
  12105. *
  12106. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12107. * @default NormalBlending
  12108. */
  12109. this.blending = NormalBlending;
  12110. /**
  12111. * Defines which side of faces will be rendered - front, back or both.
  12112. *
  12113. * @type {(FrontSide|BackSide|DoubleSide)}
  12114. * @default FrontSide
  12115. */
  12116. this.side = FrontSide;
  12117. /**
  12118. * If set to `true`, vertex colors should be used.
  12119. *
  12120. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12121. * four (RGBA) component color buffer attribute is used.
  12122. *
  12123. * @type {boolean}
  12124. * @default false
  12125. */
  12126. this.vertexColors = false;
  12127. /**
  12128. * Defines how transparent the material is.
  12129. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12130. *
  12131. * If the {@link Material#transparent} is not set to `true`,
  12132. * the material will remain fully opaque and this value will only affect its color.
  12133. *
  12134. * @type {number}
  12135. * @default 1
  12136. */
  12137. this.opacity = 1;
  12138. /**
  12139. * Defines whether this material is transparent. This has an effect on
  12140. * rendering as transparent objects need special treatment and are rendered
  12141. * after non-transparent objects.
  12142. *
  12143. * When set to true, the extent to which the material is transparent is
  12144. * controlled by {@link Material#opacity}.
  12145. *
  12146. * @type {boolean}
  12147. * @default false
  12148. */
  12149. this.transparent = false;
  12150. /**
  12151. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12152. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12153. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12154. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12155. *
  12156. * @type {boolean}
  12157. * @default false
  12158. */
  12159. this.alphaHash = false;
  12160. /**
  12161. * Defines the blending source factor.
  12162. *
  12163. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12164. * @default SrcAlphaFactor
  12165. */
  12166. this.blendSrc = SrcAlphaFactor;
  12167. /**
  12168. * Defines the blending destination factor.
  12169. *
  12170. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12171. * @default OneMinusSrcAlphaFactor
  12172. */
  12173. this.blendDst = OneMinusSrcAlphaFactor;
  12174. /**
  12175. * Defines the blending equation.
  12176. *
  12177. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12178. * @default OneMinusSrcAlphaFactor
  12179. */
  12180. this.blendEquation = AddEquation;
  12181. /**
  12182. * Defines the blending source alpha factor.
  12183. *
  12184. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12185. * @default null
  12186. */
  12187. this.blendSrcAlpha = null;
  12188. /**
  12189. * Defines the blending destination alpha factor.
  12190. *
  12191. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12192. * @default null
  12193. */
  12194. this.blendDstAlpha = null;
  12195. /**
  12196. * Defines the blending equation of the alpha channel.
  12197. *
  12198. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12199. * @default OneMinusSrcAlphaFactor
  12200. */
  12201. this.blendEquationAlpha = null;
  12202. /**
  12203. * Represents the RGB values of the constant blend color.
  12204. *
  12205. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12206. *
  12207. * @type {Color}
  12208. * @default (0,0,0)
  12209. */
  12210. this.blendColor = new Color( 0, 0, 0 );
  12211. /**
  12212. * Represents the alpha value of the constant blend color.
  12213. *
  12214. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12215. *
  12216. * @type {number}
  12217. * @default 0
  12218. */
  12219. this.blendAlpha = 0;
  12220. /**
  12221. * Defines the depth function.
  12222. *
  12223. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12224. * @default LessEqualDepth
  12225. */
  12226. this.depthFunc = LessEqualDepth;
  12227. /**
  12228. * Whether to have depth test enabled when rendering this material.
  12229. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12230. *
  12231. * @type {boolean}
  12232. * @default true
  12233. */
  12234. this.depthTest = true;
  12235. /**
  12236. * Whether rendering this material has any effect on the depth buffer.
  12237. *
  12238. * When drawing 2D overlays it can be useful to disable the depth writing in
  12239. * order to layer several things together without creating z-index artifacts.
  12240. *
  12241. * @type {boolean}
  12242. * @default true
  12243. */
  12244. this.depthWrite = true;
  12245. /**
  12246. * The bit mask to use when writing to the stencil buffer.
  12247. *
  12248. * @type {number}
  12249. * @default 0xff
  12250. */
  12251. this.stencilWriteMask = 0xff;
  12252. /**
  12253. * The stencil comparison function to use.
  12254. *
  12255. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12256. * @default AlwaysStencilFunc
  12257. */
  12258. this.stencilFunc = AlwaysStencilFunc;
  12259. /**
  12260. * The value to use when performing stencil comparisons or stencil operations.
  12261. *
  12262. * @type {number}
  12263. * @default 0
  12264. */
  12265. this.stencilRef = 0;
  12266. /**
  12267. * The bit mask to use when comparing against the stencil buffer.
  12268. *
  12269. * @type {number}
  12270. * @default 0xff
  12271. */
  12272. this.stencilFuncMask = 0xff;
  12273. /**
  12274. * Which stencil operation to perform when the comparison function returns `false`.
  12275. *
  12276. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12277. * @default KeepStencilOp
  12278. */
  12279. this.stencilFail = KeepStencilOp;
  12280. /**
  12281. * Which stencil operation to perform when the comparison function returns
  12282. * `true` but the depth test fails.
  12283. *
  12284. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12285. * @default KeepStencilOp
  12286. */
  12287. this.stencilZFail = KeepStencilOp;
  12288. /**
  12289. * Which stencil operation to perform when the comparison function returns
  12290. * `true` and the depth test passes.
  12291. *
  12292. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12293. * @default KeepStencilOp
  12294. */
  12295. this.stencilZPass = KeepStencilOp;
  12296. /**
  12297. * Whether stencil operations are performed against the stencil buffer. In
  12298. * order to perform writes or comparisons against the stencil buffer this
  12299. * value must be `true`.
  12300. *
  12301. * @type {boolean}
  12302. * @default false
  12303. */
  12304. this.stencilWrite = false;
  12305. /**
  12306. * User-defined clipping planes specified as THREE.Plane objects in world
  12307. * space. These planes apply to the objects this material is attached to.
  12308. * Points in space whose signed distance to the plane is negative are clipped
  12309. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12310. * be `true`.
  12311. *
  12312. * @type {?Array<Plane>}
  12313. * @default null
  12314. */
  12315. this.clippingPlanes = null;
  12316. /**
  12317. * Changes the behavior of clipping planes so that only their intersection is
  12318. * clipped, rather than their union.
  12319. *
  12320. * @type {boolean}
  12321. * @default false
  12322. */
  12323. this.clipIntersection = false;
  12324. /**
  12325. * Defines whether to clip shadows according to the clipping planes specified
  12326. * on this material.
  12327. *
  12328. * @type {boolean}
  12329. * @default false
  12330. */
  12331. this.clipShadows = false;
  12332. /**
  12333. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12334. * is determined as follows:
  12335. *
  12336. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12337. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12338. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12339. *
  12340. * @type {?(FrontSide|BackSide|DoubleSide)}
  12341. * @default null
  12342. */
  12343. this.shadowSide = null;
  12344. /**
  12345. * Whether to render the material's color.
  12346. *
  12347. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12348. * objects that occlude other objects.
  12349. *
  12350. * @type {boolean}
  12351. * @default true
  12352. */
  12353. this.colorWrite = true;
  12354. /**
  12355. * Override the renderer's default precision for this material.
  12356. *
  12357. * @type {?('highp'|'mediump'|'lowp')}
  12358. * @default null
  12359. */
  12360. this.precision = null;
  12361. /**
  12362. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12363. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12364. * The offset is added before the depth test is performed and before the value is written
  12365. * into the depth buffer.
  12366. *
  12367. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12368. * rendering solids with highlighted edges.
  12369. *
  12370. * @type {boolean}
  12371. * @default false
  12372. */
  12373. this.polygonOffset = false;
  12374. /**
  12375. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12376. *
  12377. * @type {number}
  12378. * @default 0
  12379. */
  12380. this.polygonOffsetFactor = 0;
  12381. /**
  12382. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12383. *
  12384. * @type {number}
  12385. * @default 0
  12386. */
  12387. this.polygonOffsetUnits = 0;
  12388. /**
  12389. * Whether to apply dithering to the color to remove the appearance of banding.
  12390. *
  12391. * @type {boolean}
  12392. * @default false
  12393. */
  12394. this.dithering = false;
  12395. /**
  12396. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12397. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12398. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12399. *
  12400. * @type {boolean}
  12401. * @default false
  12402. */
  12403. this.alphaToCoverage = false;
  12404. /**
  12405. * Whether to premultiply the alpha (transparency) value.
  12406. *
  12407. * @type {boolean}
  12408. * @default false
  12409. */
  12410. this.premultipliedAlpha = false;
  12411. /**
  12412. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12413. *
  12414. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12415. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12416. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12417. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12418. * disable the two pass rendering to avoid performance issues.
  12419. *
  12420. * @type {boolean}
  12421. * @default false
  12422. */
  12423. this.forceSinglePass = false;
  12424. /**
  12425. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12426. *
  12427. * @type {boolean}
  12428. * @default true
  12429. */
  12430. this.allowOverride = true;
  12431. /**
  12432. * Defines whether 3D objects using this material are visible.
  12433. *
  12434. * @type {boolean}
  12435. * @default true
  12436. */
  12437. this.visible = true;
  12438. /**
  12439. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12440. *
  12441. * It is ignored when rendering to a render target or using post processing or when using
  12442. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12443. *
  12444. * @type {boolean}
  12445. * @default true
  12446. */
  12447. this.toneMapped = true;
  12448. /**
  12449. * An object that can be used to store custom data about the Material. It
  12450. * should not hold references to functions as these will not be cloned.
  12451. *
  12452. * @type {Object}
  12453. */
  12454. this.userData = {};
  12455. /**
  12456. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12457. *
  12458. * @type {number}
  12459. * @readonly
  12460. * @default 0
  12461. */
  12462. this.version = 0;
  12463. this._alphaTest = 0;
  12464. }
  12465. /**
  12466. * Sets the alpha value to be used when running an alpha test. The material
  12467. * will not be rendered if the opacity is lower than this value.
  12468. *
  12469. * @type {number}
  12470. * @readonly
  12471. * @default 0
  12472. */
  12473. get alphaTest() {
  12474. return this._alphaTest;
  12475. }
  12476. set alphaTest( value ) {
  12477. if ( this._alphaTest > 0 !== value > 0 ) {
  12478. this.version ++;
  12479. }
  12480. this._alphaTest = value;
  12481. }
  12482. /**
  12483. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12484. *
  12485. * This method can only be used when rendering with {@link WebGLRenderer}.
  12486. *
  12487. * @param {WebGLRenderer} renderer - The renderer.
  12488. * @param {Scene} scene - The scene.
  12489. * @param {Camera} camera - The camera that is used to render the scene.
  12490. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12491. * @param {Object3D} object - The 3D object.
  12492. * @param {Object} group - The geometry group data.
  12493. */
  12494. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12495. /**
  12496. * An optional callback that is executed immediately before the shader
  12497. * program is compiled. This function is called with the shader source code
  12498. * as a parameter. Useful for the modification of built-in materials.
  12499. *
  12500. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12501. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12502. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12503. *
  12504. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12505. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12506. */
  12507. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12508. /**
  12509. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12510. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12511. * shader or recompile the shader for this material as needed.
  12512. *
  12513. * This method can only be used when rendering with {@link WebGLRenderer}.
  12514. *
  12515. * @return {string} The custom program cache key.
  12516. */
  12517. customProgramCacheKey() {
  12518. return this.onBeforeCompile.toString();
  12519. }
  12520. /**
  12521. * This method can be used to set default values from parameter objects.
  12522. * It is a generic implementation so it can be used with different types
  12523. * of materials.
  12524. *
  12525. * @param {Object} [values] - The material values to set.
  12526. */
  12527. setValues( values ) {
  12528. if ( values === undefined ) return;
  12529. for ( const key in values ) {
  12530. const newValue = values[ key ];
  12531. if ( newValue === undefined ) {
  12532. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12533. continue;
  12534. }
  12535. const currentValue = this[ key ];
  12536. if ( currentValue === undefined ) {
  12537. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12538. continue;
  12539. }
  12540. if ( currentValue && currentValue.isColor ) {
  12541. currentValue.set( newValue );
  12542. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12543. currentValue.copy( newValue );
  12544. } else {
  12545. this[ key ] = newValue;
  12546. }
  12547. }
  12548. }
  12549. /**
  12550. * Serializes the material into JSON.
  12551. *
  12552. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12553. * @return {Object} A JSON object representing the serialized material.
  12554. * @see {@link ObjectLoader#parse}
  12555. */
  12556. toJSON( meta ) {
  12557. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12558. if ( isRootObject ) {
  12559. meta = {
  12560. textures: {},
  12561. images: {}
  12562. };
  12563. }
  12564. const data = {
  12565. metadata: {
  12566. version: 4.6,
  12567. type: 'Material',
  12568. generator: 'Material.toJSON'
  12569. }
  12570. };
  12571. // standard Material serialization
  12572. data.uuid = this.uuid;
  12573. data.type = this.type;
  12574. if ( this.name !== '' ) data.name = this.name;
  12575. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12576. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12577. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12578. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12579. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12580. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12581. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12582. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12583. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12584. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12585. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12586. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12587. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12588. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12589. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12590. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12591. }
  12592. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12593. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12594. }
  12595. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12596. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12597. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12598. }
  12599. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12600. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12601. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12602. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12603. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12604. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12605. }
  12606. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12607. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12608. }
  12609. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12610. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12611. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12612. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12613. }
  12614. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12615. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12616. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12617. if ( this.lightMap && this.lightMap.isTexture ) {
  12618. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12619. data.lightMapIntensity = this.lightMapIntensity;
  12620. }
  12621. if ( this.aoMap && this.aoMap.isTexture ) {
  12622. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12623. data.aoMapIntensity = this.aoMapIntensity;
  12624. }
  12625. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12626. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12627. data.bumpScale = this.bumpScale;
  12628. }
  12629. if ( this.normalMap && this.normalMap.isTexture ) {
  12630. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12631. data.normalMapType = this.normalMapType;
  12632. data.normalScale = this.normalScale.toArray();
  12633. }
  12634. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12635. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12636. data.displacementScale = this.displacementScale;
  12637. data.displacementBias = this.displacementBias;
  12638. }
  12639. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12640. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12641. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12642. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12643. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12644. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12645. if ( this.envMap && this.envMap.isTexture ) {
  12646. data.envMap = this.envMap.toJSON( meta ).uuid;
  12647. if ( this.combine !== undefined ) data.combine = this.combine;
  12648. }
  12649. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12650. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12651. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12652. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12653. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12654. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12655. }
  12656. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12657. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12658. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12659. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12660. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12661. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12662. if ( this.size !== undefined ) data.size = this.size;
  12663. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12664. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12665. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12666. if ( this.side !== FrontSide ) data.side = this.side;
  12667. if ( this.vertexColors === true ) data.vertexColors = true;
  12668. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12669. if ( this.transparent === true ) data.transparent = true;
  12670. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12671. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12672. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12673. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12674. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12675. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12676. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12677. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12678. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12679. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12680. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12681. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12682. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12683. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12684. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12685. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12686. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12687. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12688. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12689. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12690. // rotation (SpriteMaterial)
  12691. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12692. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12693. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12694. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12695. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12696. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12697. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12698. if ( this.scale !== undefined ) data.scale = this.scale;
  12699. if ( this.dithering === true ) data.dithering = true;
  12700. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12701. if ( this.alphaHash === true ) data.alphaHash = true;
  12702. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12703. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12704. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12705. if ( this.wireframe === true ) data.wireframe = true;
  12706. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12707. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12708. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12709. if ( this.flatShading === true ) data.flatShading = true;
  12710. if ( this.visible === false ) data.visible = false;
  12711. if ( this.toneMapped === false ) data.toneMapped = false;
  12712. if ( this.fog === false ) data.fog = false;
  12713. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12714. // TODO: Copied from Object3D.toJSON
  12715. function extractFromCache( cache ) {
  12716. const values = [];
  12717. for ( const key in cache ) {
  12718. const data = cache[ key ];
  12719. delete data.metadata;
  12720. values.push( data );
  12721. }
  12722. return values;
  12723. }
  12724. if ( isRootObject ) {
  12725. const textures = extractFromCache( meta.textures );
  12726. const images = extractFromCache( meta.images );
  12727. if ( textures.length > 0 ) data.textures = textures;
  12728. if ( images.length > 0 ) data.images = images;
  12729. }
  12730. return data;
  12731. }
  12732. /**
  12733. * Returns a new material with copied values from this instance.
  12734. *
  12735. * @return {Material} A clone of this instance.
  12736. */
  12737. clone() {
  12738. return new this.constructor().copy( this );
  12739. }
  12740. /**
  12741. * Copies the values of the given material to this instance.
  12742. *
  12743. * @param {Material} source - The material to copy.
  12744. * @return {Material} A reference to this instance.
  12745. */
  12746. copy( source ) {
  12747. this.name = source.name;
  12748. this.blending = source.blending;
  12749. this.side = source.side;
  12750. this.vertexColors = source.vertexColors;
  12751. this.opacity = source.opacity;
  12752. this.transparent = source.transparent;
  12753. this.blendSrc = source.blendSrc;
  12754. this.blendDst = source.blendDst;
  12755. this.blendEquation = source.blendEquation;
  12756. this.blendSrcAlpha = source.blendSrcAlpha;
  12757. this.blendDstAlpha = source.blendDstAlpha;
  12758. this.blendEquationAlpha = source.blendEquationAlpha;
  12759. this.blendColor.copy( source.blendColor );
  12760. this.blendAlpha = source.blendAlpha;
  12761. this.depthFunc = source.depthFunc;
  12762. this.depthTest = source.depthTest;
  12763. this.depthWrite = source.depthWrite;
  12764. this.stencilWriteMask = source.stencilWriteMask;
  12765. this.stencilFunc = source.stencilFunc;
  12766. this.stencilRef = source.stencilRef;
  12767. this.stencilFuncMask = source.stencilFuncMask;
  12768. this.stencilFail = source.stencilFail;
  12769. this.stencilZFail = source.stencilZFail;
  12770. this.stencilZPass = source.stencilZPass;
  12771. this.stencilWrite = source.stencilWrite;
  12772. const srcPlanes = source.clippingPlanes;
  12773. let dstPlanes = null;
  12774. if ( srcPlanes !== null ) {
  12775. const n = srcPlanes.length;
  12776. dstPlanes = new Array( n );
  12777. for ( let i = 0; i !== n; ++ i ) {
  12778. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12779. }
  12780. }
  12781. this.clippingPlanes = dstPlanes;
  12782. this.clipIntersection = source.clipIntersection;
  12783. this.clipShadows = source.clipShadows;
  12784. this.shadowSide = source.shadowSide;
  12785. this.colorWrite = source.colorWrite;
  12786. this.precision = source.precision;
  12787. this.polygonOffset = source.polygonOffset;
  12788. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12789. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12790. this.dithering = source.dithering;
  12791. this.alphaTest = source.alphaTest;
  12792. this.alphaHash = source.alphaHash;
  12793. this.alphaToCoverage = source.alphaToCoverage;
  12794. this.premultipliedAlpha = source.premultipliedAlpha;
  12795. this.forceSinglePass = source.forceSinglePass;
  12796. this.visible = source.visible;
  12797. this.toneMapped = source.toneMapped;
  12798. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12799. return this;
  12800. }
  12801. /**
  12802. * Frees the GPU-related resources allocated by this instance. Call this
  12803. * method whenever this instance is no longer used in your app.
  12804. *
  12805. * @fires Material#dispose
  12806. */
  12807. dispose() {
  12808. /**
  12809. * Fires when the material has been disposed of.
  12810. *
  12811. * @event Material#dispose
  12812. * @type {Object}
  12813. */
  12814. this.dispatchEvent( { type: 'dispose' } );
  12815. }
  12816. /**
  12817. * Setting this property to `true` indicates the engine the material
  12818. * needs to be recompiled.
  12819. *
  12820. * @type {boolean}
  12821. * @default false
  12822. * @param {boolean} value
  12823. */
  12824. set needsUpdate( value ) {
  12825. if ( value === true ) this.version ++;
  12826. }
  12827. onBuild( /* shaderobject, renderer */ ) {
  12828. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  12829. }
  12830. }
  12831. /**
  12832. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  12833. *
  12834. * This material is not affected by lights.
  12835. *
  12836. * @augments Material
  12837. */
  12838. class MeshBasicMaterial extends Material {
  12839. /**
  12840. * Constructs a new mesh basic material.
  12841. *
  12842. * @param {Object} [parameters] - An object with one or more properties
  12843. * defining the material's appearance. Any property of the material
  12844. * (including any property from inherited materials) can be passed
  12845. * in here. Color values can be passed any type of value accepted
  12846. * by {@link Color#set}.
  12847. */
  12848. constructor( parameters ) {
  12849. super();
  12850. /**
  12851. * This flag can be used for type testing.
  12852. *
  12853. * @type {boolean}
  12854. * @readonly
  12855. * @default true
  12856. */
  12857. this.isMeshBasicMaterial = true;
  12858. this.type = 'MeshBasicMaterial';
  12859. /**
  12860. * Color of the material.
  12861. *
  12862. * @type {Color}
  12863. * @default (1,1,1)
  12864. */
  12865. this.color = new Color( 0xffffff ); // emissive
  12866. /**
  12867. * The color map. May optionally include an alpha channel, typically combined
  12868. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  12869. * color is modulated by the diffuse `color`.
  12870. *
  12871. * @type {?Texture}
  12872. * @default null
  12873. */
  12874. this.map = null;
  12875. /**
  12876. * The light map. Requires a second set of UVs.
  12877. *
  12878. * @type {?Texture}
  12879. * @default null
  12880. */
  12881. this.lightMap = null;
  12882. /**
  12883. * Intensity of the baked light.
  12884. *
  12885. * @type {number}
  12886. * @default 1
  12887. */
  12888. this.lightMapIntensity = 1.0;
  12889. /**
  12890. * The red channel of this texture is used as the ambient occlusion map.
  12891. * Requires a second set of UVs.
  12892. *
  12893. * @type {?Texture}
  12894. * @default null
  12895. */
  12896. this.aoMap = null;
  12897. /**
  12898. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  12899. * disables ambient occlusion. Where intensity is `1` and the AO map's
  12900. * red channel is also `1`, ambient light is fully occluded on a surface.
  12901. *
  12902. * @type {number}
  12903. * @default 1
  12904. */
  12905. this.aoMapIntensity = 1.0;
  12906. /**
  12907. * Specular map used by the material.
  12908. *
  12909. * @type {?Texture}
  12910. * @default null
  12911. */
  12912. this.specularMap = null;
  12913. /**
  12914. * The alpha map is a grayscale texture that controls the opacity across the
  12915. * surface (black: fully transparent; white: fully opaque).
  12916. *
  12917. * Only the color of the texture is used, ignoring the alpha channel if one
  12918. * exists. For RGB and RGBA textures, the renderer will use the green channel
  12919. * when sampling this texture due to the extra bit of precision provided for
  12920. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  12921. * luminance/alpha textures will also still work as expected.
  12922. *
  12923. * @type {?Texture}
  12924. * @default null
  12925. */
  12926. this.alphaMap = null;
  12927. /**
  12928. * The environment map.
  12929. *
  12930. * @type {?Texture}
  12931. * @default null
  12932. */
  12933. this.envMap = null;
  12934. /**
  12935. * The rotation of the environment map in radians.
  12936. *
  12937. * @type {Euler}
  12938. * @default (0,0,0)
  12939. */
  12940. this.envMapRotation = new Euler();
  12941. /**
  12942. * How to combine the result of the surface's color with the environment map, if any.
  12943. *
  12944. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  12945. * blend between the two colors.
  12946. *
  12947. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  12948. * @default MultiplyOperation
  12949. */
  12950. this.combine = MultiplyOperation;
  12951. /**
  12952. * How much the environment map affects the surface.
  12953. * The valid range is between `0` (no reflections) and `1` (full reflections).
  12954. *
  12955. * @type {number}
  12956. * @default 1
  12957. */
  12958. this.reflectivity = 1;
  12959. /**
  12960. * The index of refraction (IOR) of air (approximately 1) divided by the
  12961. * index of refraction of the material. It is used with environment mapping
  12962. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  12963. * The refraction ratio should not exceed `1`.
  12964. *
  12965. * @type {number}
  12966. * @default 0.98
  12967. */
  12968. this.refractionRatio = 0.98;
  12969. /**
  12970. * Renders the geometry as a wireframe.
  12971. *
  12972. * @type {boolean}
  12973. * @default false
  12974. */
  12975. this.wireframe = false;
  12976. /**
  12977. * Controls the thickness of the wireframe.
  12978. *
  12979. * Can only be used with {@link SVGRenderer}.
  12980. *
  12981. * @type {number}
  12982. * @default 1
  12983. */
  12984. this.wireframeLinewidth = 1;
  12985. /**
  12986. * Defines appearance of wireframe ends.
  12987. *
  12988. * Can only be used with {@link SVGRenderer}.
  12989. *
  12990. * @type {('round'|'bevel'|'miter')}
  12991. * @default 'round'
  12992. */
  12993. this.wireframeLinecap = 'round';
  12994. /**
  12995. * Defines appearance of wireframe joints.
  12996. *
  12997. * Can only be used with {@link SVGRenderer}.
  12998. *
  12999. * @type {('round'|'bevel'|'miter')}
  13000. * @default 'round'
  13001. */
  13002. this.wireframeLinejoin = 'round';
  13003. /**
  13004. * Whether the material is affected by fog or not.
  13005. *
  13006. * @type {boolean}
  13007. * @default true
  13008. */
  13009. this.fog = true;
  13010. this.setValues( parameters );
  13011. }
  13012. copy( source ) {
  13013. super.copy( source );
  13014. this.color.copy( source.color );
  13015. this.map = source.map;
  13016. this.lightMap = source.lightMap;
  13017. this.lightMapIntensity = source.lightMapIntensity;
  13018. this.aoMap = source.aoMap;
  13019. this.aoMapIntensity = source.aoMapIntensity;
  13020. this.specularMap = source.specularMap;
  13021. this.alphaMap = source.alphaMap;
  13022. this.envMap = source.envMap;
  13023. this.envMapRotation.copy( source.envMapRotation );
  13024. this.combine = source.combine;
  13025. this.reflectivity = source.reflectivity;
  13026. this.refractionRatio = source.refractionRatio;
  13027. this.wireframe = source.wireframe;
  13028. this.wireframeLinewidth = source.wireframeLinewidth;
  13029. this.wireframeLinecap = source.wireframeLinecap;
  13030. this.wireframeLinejoin = source.wireframeLinejoin;
  13031. this.fog = source.fog;
  13032. return this;
  13033. }
  13034. }
  13035. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13036. const _tables = /*@__PURE__*/ _generateTables();
  13037. function _generateTables() {
  13038. // float32 to float16 helpers
  13039. const buffer = new ArrayBuffer( 4 );
  13040. const floatView = new Float32Array( buffer );
  13041. const uint32View = new Uint32Array( buffer );
  13042. const baseTable = new Uint32Array( 512 );
  13043. const shiftTable = new Uint32Array( 512 );
  13044. for ( let i = 0; i < 256; ++ i ) {
  13045. const e = i - 127;
  13046. // very small number (0, -0)
  13047. if ( e < - 27 ) {
  13048. baseTable[ i ] = 0x0000;
  13049. baseTable[ i | 0x100 ] = 0x8000;
  13050. shiftTable[ i ] = 24;
  13051. shiftTable[ i | 0x100 ] = 24;
  13052. // small number (denorm)
  13053. } else if ( e < - 14 ) {
  13054. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13055. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13056. shiftTable[ i ] = - e - 1;
  13057. shiftTable[ i | 0x100 ] = - e - 1;
  13058. // normal number
  13059. } else if ( e <= 15 ) {
  13060. baseTable[ i ] = ( e + 15 ) << 10;
  13061. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13062. shiftTable[ i ] = 13;
  13063. shiftTable[ i | 0x100 ] = 13;
  13064. // large number (Infinity, -Infinity)
  13065. } else if ( e < 128 ) {
  13066. baseTable[ i ] = 0x7c00;
  13067. baseTable[ i | 0x100 ] = 0xfc00;
  13068. shiftTable[ i ] = 24;
  13069. shiftTable[ i | 0x100 ] = 24;
  13070. // stay (NaN, Infinity, -Infinity)
  13071. } else {
  13072. baseTable[ i ] = 0x7c00;
  13073. baseTable[ i | 0x100 ] = 0xfc00;
  13074. shiftTable[ i ] = 13;
  13075. shiftTable[ i | 0x100 ] = 13;
  13076. }
  13077. }
  13078. // float16 to float32 helpers
  13079. const mantissaTable = new Uint32Array( 2048 );
  13080. const exponentTable = new Uint32Array( 64 );
  13081. const offsetTable = new Uint32Array( 64 );
  13082. for ( let i = 1; i < 1024; ++ i ) {
  13083. let m = i << 13; // zero pad mantissa bits
  13084. let e = 0; // zero exponent
  13085. // normalized
  13086. while ( ( m & 0x00800000 ) === 0 ) {
  13087. m <<= 1;
  13088. e -= 0x00800000; // decrement exponent
  13089. }
  13090. m &= ~ 0x00800000; // clear leading 1 bit
  13091. e += 0x38800000; // adjust bias
  13092. mantissaTable[ i ] = m | e;
  13093. }
  13094. for ( let i = 1024; i < 2048; ++ i ) {
  13095. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13096. }
  13097. for ( let i = 1; i < 31; ++ i ) {
  13098. exponentTable[ i ] = i << 23;
  13099. }
  13100. exponentTable[ 31 ] = 0x47800000;
  13101. exponentTable[ 32 ] = 0x80000000;
  13102. for ( let i = 33; i < 63; ++ i ) {
  13103. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13104. }
  13105. exponentTable[ 63 ] = 0xc7800000;
  13106. for ( let i = 1; i < 64; ++ i ) {
  13107. if ( i !== 32 ) {
  13108. offsetTable[ i ] = 1024;
  13109. }
  13110. }
  13111. return {
  13112. floatView: floatView,
  13113. uint32View: uint32View,
  13114. baseTable: baseTable,
  13115. shiftTable: shiftTable,
  13116. mantissaTable: mantissaTable,
  13117. exponentTable: exponentTable,
  13118. offsetTable: offsetTable
  13119. };
  13120. }
  13121. /**
  13122. * Returns a half precision floating point value (FP16) from the given single
  13123. * precision floating point value (FP32).
  13124. *
  13125. * @param {number} val - A single precision floating point value.
  13126. * @return {number} The FP16 value.
  13127. */
  13128. function toHalfFloat( val ) {
  13129. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13130. val = clamp( val, - 65504, 65504 );
  13131. _tables.floatView[ 0 ] = val;
  13132. const f = _tables.uint32View[ 0 ];
  13133. const e = ( f >> 23 ) & 0x1ff;
  13134. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13135. }
  13136. /**
  13137. * Returns a single precision floating point value (FP32) from the given half
  13138. * precision floating point value (FP16).
  13139. *
  13140. * @param {number} val - A half precision floating point value.
  13141. * @return {number} The FP32 value.
  13142. */
  13143. function fromHalfFloat( val ) {
  13144. const m = val >> 10;
  13145. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13146. return _tables.floatView[ 0 ];
  13147. }
  13148. /**
  13149. * A class containing utility functions for data.
  13150. *
  13151. * @hideconstructor
  13152. */
  13153. class DataUtils {
  13154. /**
  13155. * Returns a half precision floating point value (FP16) from the given single
  13156. * precision floating point value (FP32).
  13157. *
  13158. * @param {number} val - A single precision floating point value.
  13159. * @return {number} The FP16 value.
  13160. */
  13161. static toHalfFloat( val ) {
  13162. return toHalfFloat( val );
  13163. }
  13164. /**
  13165. * Returns a single precision floating point value (FP32) from the given half
  13166. * precision floating point value (FP16).
  13167. *
  13168. * @param {number} val - A half precision floating point value.
  13169. * @return {number} The FP32 value.
  13170. */
  13171. static fromHalfFloat( val ) {
  13172. return fromHalfFloat( val );
  13173. }
  13174. }
  13175. const _vector$9 = /*@__PURE__*/ new Vector3();
  13176. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13177. let _id$3 = 0;
  13178. /**
  13179. * This class stores data for an attribute (such as vertex positions, face
  13180. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13181. * a geometry, which allows for more efficient passing of data to the GPU.
  13182. *
  13183. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13184. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13185. */
  13186. class BufferAttribute {
  13187. /**
  13188. * Constructs a new buffer attribute.
  13189. *
  13190. * @param {TypedArray} array - The array holding the attribute data.
  13191. * @param {number} itemSize - The item size.
  13192. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13193. */
  13194. constructor( array, itemSize, normalized = false ) {
  13195. if ( Array.isArray( array ) ) {
  13196. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13197. }
  13198. /**
  13199. * This flag can be used for type testing.
  13200. *
  13201. * @type {boolean}
  13202. * @readonly
  13203. * @default true
  13204. */
  13205. this.isBufferAttribute = true;
  13206. /**
  13207. * The ID of the buffer attribute.
  13208. *
  13209. * @name BufferAttribute#id
  13210. * @type {number}
  13211. * @readonly
  13212. */
  13213. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13214. /**
  13215. * The name of the buffer attribute.
  13216. *
  13217. * @type {string}
  13218. */
  13219. this.name = '';
  13220. /**
  13221. * The array holding the attribute data. It should have `itemSize * numVertices`
  13222. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13223. *
  13224. * @type {TypedArray}
  13225. */
  13226. this.array = array;
  13227. /**
  13228. * The number of values of the array that should be associated with a particular vertex.
  13229. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13230. * normal, or color), then the value should be `3`.
  13231. *
  13232. * @type {number}
  13233. */
  13234. this.itemSize = itemSize;
  13235. /**
  13236. * Represents the number of items this buffer attribute stores. It is internally computed
  13237. * by dividing the `array` length by the `itemSize`.
  13238. *
  13239. * @type {number}
  13240. * @readonly
  13241. */
  13242. this.count = array !== undefined ? array.length / itemSize : 0;
  13243. /**
  13244. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13245. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13246. * and `normalized` is `true`, the values `0 -+65535` in the array data will be mapped to
  13247. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13248. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13249. *
  13250. * @type {boolean}
  13251. */
  13252. this.normalized = normalized;
  13253. /**
  13254. * Defines the intended usage pattern of the data store for optimization purposes.
  13255. *
  13256. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13257. * instantiate a new one and set the desired usage before the next render.
  13258. *
  13259. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13260. * @default StaticDrawUsage
  13261. */
  13262. this.usage = StaticDrawUsage;
  13263. /**
  13264. * This can be used to only update some components of stored vectors (for example, just the
  13265. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13266. *
  13267. * @type {Array<Object>}
  13268. */
  13269. this.updateRanges = [];
  13270. /**
  13271. * Configures the bound GPU type for use in shaders.
  13272. *
  13273. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13274. * For lower precision float types, use `Float16BufferAttribute`.
  13275. *
  13276. * @type {(FloatType|IntType)}
  13277. * @default FloatType
  13278. */
  13279. this.gpuType = FloatType;
  13280. /**
  13281. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13282. *
  13283. * @type {number}
  13284. */
  13285. this.version = 0;
  13286. }
  13287. /**
  13288. * A callback function that is executed after the renderer has transferred the attribute
  13289. * array data to the GPU.
  13290. */
  13291. onUploadCallback() {}
  13292. /**
  13293. * Flag to indicate that this attribute has changed and should be re-sent to
  13294. * the GPU. Set this to `true` when you modify the value of the array.
  13295. *
  13296. * @type {number}
  13297. * @default false
  13298. * @param {boolean} value
  13299. */
  13300. set needsUpdate( value ) {
  13301. if ( value === true ) this.version ++;
  13302. }
  13303. /**
  13304. * Sets the usage of this buffer attribute.
  13305. *
  13306. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13307. * @return {BufferAttribute} A reference to this buffer attribute.
  13308. */
  13309. setUsage( value ) {
  13310. this.usage = value;
  13311. return this;
  13312. }
  13313. /**
  13314. * Adds a range of data in the data array to be updated on the GPU.
  13315. *
  13316. * @param {number} start - Position at which to start update.
  13317. * @param {number} count - The number of components to update.
  13318. */
  13319. addUpdateRange( start, count ) {
  13320. this.updateRanges.push( { start, count } );
  13321. }
  13322. /**
  13323. * Clears the update ranges.
  13324. */
  13325. clearUpdateRanges() {
  13326. this.updateRanges.length = 0;
  13327. }
  13328. /**
  13329. * Copies the values of the given buffer attribute to this instance.
  13330. *
  13331. * @param {BufferAttribute} source - The buffer attribute to copy.
  13332. * @return {BufferAttribute} A reference to this instance.
  13333. */
  13334. copy( source ) {
  13335. this.name = source.name;
  13336. this.array = new source.array.constructor( source.array );
  13337. this.itemSize = source.itemSize;
  13338. this.count = source.count;
  13339. this.normalized = source.normalized;
  13340. this.usage = source.usage;
  13341. this.gpuType = source.gpuType;
  13342. return this;
  13343. }
  13344. /**
  13345. * Copies a vector from the given buffer attribute to this one. The start
  13346. * and destination position in the attribute buffers are represented by the
  13347. * given indices.
  13348. *
  13349. * @param {number} index1 - The destination index into this buffer attribute.
  13350. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13351. * @param {number} index2 - The source index into the given buffer attribute.
  13352. * @return {BufferAttribute} A reference to this instance.
  13353. */
  13354. copyAt( index1, attribute, index2 ) {
  13355. index1 *= this.itemSize;
  13356. index2 *= attribute.itemSize;
  13357. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13358. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13359. }
  13360. return this;
  13361. }
  13362. /**
  13363. * Copies the given array data into this buffer attribute.
  13364. *
  13365. * @param {(TypedArray|Array)} array - The array to copy.
  13366. * @return {BufferAttribute} A reference to this instance.
  13367. */
  13368. copyArray( array ) {
  13369. this.array.set( array );
  13370. return this;
  13371. }
  13372. /**
  13373. * Applies the given 3x3 matrix to the given attribute. Works with
  13374. * item size `2` and `3`.
  13375. *
  13376. * @param {Matrix3} m - The matrix to apply.
  13377. * @return {BufferAttribute} A reference to this instance.
  13378. */
  13379. applyMatrix3( m ) {
  13380. if ( this.itemSize === 2 ) {
  13381. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13382. _vector2$1.fromBufferAttribute( this, i );
  13383. _vector2$1.applyMatrix3( m );
  13384. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13385. }
  13386. } else if ( this.itemSize === 3 ) {
  13387. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13388. _vector$9.fromBufferAttribute( this, i );
  13389. _vector$9.applyMatrix3( m );
  13390. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13391. }
  13392. }
  13393. return this;
  13394. }
  13395. /**
  13396. * Applies the given 4x4 matrix to the given attribute. Only works with
  13397. * item size `3`.
  13398. *
  13399. * @param {Matrix4} m - The matrix to apply.
  13400. * @return {BufferAttribute} A reference to this instance.
  13401. */
  13402. applyMatrix4( m ) {
  13403. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13404. _vector$9.fromBufferAttribute( this, i );
  13405. _vector$9.applyMatrix4( m );
  13406. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13407. }
  13408. return this;
  13409. }
  13410. /**
  13411. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13412. * item size `3`.
  13413. *
  13414. * @param {Matrix3} m - The normal matrix to apply.
  13415. * @return {BufferAttribute} A reference to this instance.
  13416. */
  13417. applyNormalMatrix( m ) {
  13418. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13419. _vector$9.fromBufferAttribute( this, i );
  13420. _vector$9.applyNormalMatrix( m );
  13421. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13422. }
  13423. return this;
  13424. }
  13425. /**
  13426. * Applies the given 4x4 matrix to the given attribute. Only works with
  13427. * item size `3` and with direction vectors.
  13428. *
  13429. * @param {Matrix4} m - The matrix to apply.
  13430. * @return {BufferAttribute} A reference to this instance.
  13431. */
  13432. transformDirection( m ) {
  13433. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13434. _vector$9.fromBufferAttribute( this, i );
  13435. _vector$9.transformDirection( m );
  13436. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13437. }
  13438. return this;
  13439. }
  13440. /**
  13441. * Sets the given array data in the buffer attribute.
  13442. *
  13443. * @param {(TypedArray|Array)} value - The array data to set.
  13444. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13445. * @return {BufferAttribute} A reference to this instance.
  13446. */
  13447. set( value, offset = 0 ) {
  13448. // Matching BufferAttribute constructor, do not normalize the array.
  13449. this.array.set( value, offset );
  13450. return this;
  13451. }
  13452. /**
  13453. * Returns the given component of the vector at the given index.
  13454. *
  13455. * @param {number} index - The index into the buffer attribute.
  13456. * @param {number} component - The component index.
  13457. * @return {number} The returned value.
  13458. */
  13459. getComponent( index, component ) {
  13460. let value = this.array[ index * this.itemSize + component ];
  13461. if ( this.normalized ) value = denormalize( value, this.array );
  13462. return value;
  13463. }
  13464. /**
  13465. * Sets the given value to the given component of the vector at the given index.
  13466. *
  13467. * @param {number} index - The index into the buffer attribute.
  13468. * @param {number} component - The component index.
  13469. * @param {number} value - The value to set.
  13470. * @return {BufferAttribute} A reference to this instance.
  13471. */
  13472. setComponent( index, component, value ) {
  13473. if ( this.normalized ) value = normalize( value, this.array );
  13474. this.array[ index * this.itemSize + component ] = value;
  13475. return this;
  13476. }
  13477. /**
  13478. * Returns the x component of the vector at the given index.
  13479. *
  13480. * @param {number} index - The index into the buffer attribute.
  13481. * @return {number} The x component.
  13482. */
  13483. getX( index ) {
  13484. let x = this.array[ index * this.itemSize ];
  13485. if ( this.normalized ) x = denormalize( x, this.array );
  13486. return x;
  13487. }
  13488. /**
  13489. * Sets the x component of the vector at the given index.
  13490. *
  13491. * @param {number} index - The index into the buffer attribute.
  13492. * @param {number} x - The value to set.
  13493. * @return {BufferAttribute} A reference to this instance.
  13494. */
  13495. setX( index, x ) {
  13496. if ( this.normalized ) x = normalize( x, this.array );
  13497. this.array[ index * this.itemSize ] = x;
  13498. return this;
  13499. }
  13500. /**
  13501. * Returns the y component of the vector at the given index.
  13502. *
  13503. * @param {number} index - The index into the buffer attribute.
  13504. * @return {number} The y component.
  13505. */
  13506. getY( index ) {
  13507. let y = this.array[ index * this.itemSize + 1 ];
  13508. if ( this.normalized ) y = denormalize( y, this.array );
  13509. return y;
  13510. }
  13511. /**
  13512. * Sets the y component of the vector at the given index.
  13513. *
  13514. * @param {number} index - The index into the buffer attribute.
  13515. * @param {number} y - The value to set.
  13516. * @return {BufferAttribute} A reference to this instance.
  13517. */
  13518. setY( index, y ) {
  13519. if ( this.normalized ) y = normalize( y, this.array );
  13520. this.array[ index * this.itemSize + 1 ] = y;
  13521. return this;
  13522. }
  13523. /**
  13524. * Returns the z component of the vector at the given index.
  13525. *
  13526. * @param {number} index - The index into the buffer attribute.
  13527. * @return {number} The z component.
  13528. */
  13529. getZ( index ) {
  13530. let z = this.array[ index * this.itemSize + 2 ];
  13531. if ( this.normalized ) z = denormalize( z, this.array );
  13532. return z;
  13533. }
  13534. /**
  13535. * Sets the z component of the vector at the given index.
  13536. *
  13537. * @param {number} index - The index into the buffer attribute.
  13538. * @param {number} z - The value to set.
  13539. * @return {BufferAttribute} A reference to this instance.
  13540. */
  13541. setZ( index, z ) {
  13542. if ( this.normalized ) z = normalize( z, this.array );
  13543. this.array[ index * this.itemSize + 2 ] = z;
  13544. return this;
  13545. }
  13546. /**
  13547. * Returns the w component of the vector at the given index.
  13548. *
  13549. * @param {number} index - The index into the buffer attribute.
  13550. * @return {number} The w component.
  13551. */
  13552. getW( index ) {
  13553. let w = this.array[ index * this.itemSize + 3 ];
  13554. if ( this.normalized ) w = denormalize( w, this.array );
  13555. return w;
  13556. }
  13557. /**
  13558. * Sets the w component of the vector at the given index.
  13559. *
  13560. * @param {number} index - The index into the buffer attribute.
  13561. * @param {number} w - The value to set.
  13562. * @return {BufferAttribute} A reference to this instance.
  13563. */
  13564. setW( index, w ) {
  13565. if ( this.normalized ) w = normalize( w, this.array );
  13566. this.array[ index * this.itemSize + 3 ] = w;
  13567. return this;
  13568. }
  13569. /**
  13570. * Sets the x and y component of the vector at the given index.
  13571. *
  13572. * @param {number} index - The index into the buffer attribute.
  13573. * @param {number} x - The value for the x component to set.
  13574. * @param {number} y - The value for the y component to set.
  13575. * @return {BufferAttribute} A reference to this instance.
  13576. */
  13577. setXY( index, x, y ) {
  13578. index *= this.itemSize;
  13579. if ( this.normalized ) {
  13580. x = normalize( x, this.array );
  13581. y = normalize( y, this.array );
  13582. }
  13583. this.array[ index + 0 ] = x;
  13584. this.array[ index + 1 ] = y;
  13585. return this;
  13586. }
  13587. /**
  13588. * Sets the x, y and z component of the vector at the given index.
  13589. *
  13590. * @param {number} index - The index into the buffer attribute.
  13591. * @param {number} x - The value for the x component to set.
  13592. * @param {number} y - The value for the y component to set.
  13593. * @param {number} z - The value for the z component to set.
  13594. * @return {BufferAttribute} A reference to this instance.
  13595. */
  13596. setXYZ( index, x, y, z ) {
  13597. index *= this.itemSize;
  13598. if ( this.normalized ) {
  13599. x = normalize( x, this.array );
  13600. y = normalize( y, this.array );
  13601. z = normalize( z, this.array );
  13602. }
  13603. this.array[ index + 0 ] = x;
  13604. this.array[ index + 1 ] = y;
  13605. this.array[ index + 2 ] = z;
  13606. return this;
  13607. }
  13608. /**
  13609. * Sets the x, y, z and w component of the vector at the given index.
  13610. *
  13611. * @param {number} index - The index into the buffer attribute.
  13612. * @param {number} x - The value for the x component to set.
  13613. * @param {number} y - The value for the y component to set.
  13614. * @param {number} z - The value for the z component to set.
  13615. * @param {number} w - The value for the w component to set.
  13616. * @return {BufferAttribute} A reference to this instance.
  13617. */
  13618. setXYZW( index, x, y, z, w ) {
  13619. index *= this.itemSize;
  13620. if ( this.normalized ) {
  13621. x = normalize( x, this.array );
  13622. y = normalize( y, this.array );
  13623. z = normalize( z, this.array );
  13624. w = normalize( w, this.array );
  13625. }
  13626. this.array[ index + 0 ] = x;
  13627. this.array[ index + 1 ] = y;
  13628. this.array[ index + 2 ] = z;
  13629. this.array[ index + 3 ] = w;
  13630. return this;
  13631. }
  13632. /**
  13633. * Sets the given callback function that is executed after the Renderer has transferred
  13634. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13635. * the upload when attribute data are not needed anymore on the CPU side.
  13636. *
  13637. * @param {Function} callback - The `onUpload()` callback.
  13638. * @return {BufferAttribute} A reference to this instance.
  13639. */
  13640. onUpload( callback ) {
  13641. this.onUploadCallback = callback;
  13642. return this;
  13643. }
  13644. /**
  13645. * Returns a new buffer attribute with copied values from this instance.
  13646. *
  13647. * @return {BufferAttribute} A clone of this instance.
  13648. */
  13649. clone() {
  13650. return new this.constructor( this.array, this.itemSize ).copy( this );
  13651. }
  13652. /**
  13653. * Serializes the buffer attribute into JSON.
  13654. *
  13655. * @return {Object} A JSON object representing the serialized buffer attribute.
  13656. */
  13657. toJSON() {
  13658. const data = {
  13659. itemSize: this.itemSize,
  13660. type: this.array.constructor.name,
  13661. array: Array.from( this.array ),
  13662. normalized: this.normalized
  13663. };
  13664. if ( this.name !== '' ) data.name = this.name;
  13665. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13666. return data;
  13667. }
  13668. }
  13669. /**
  13670. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13671. * a plain `Array` instance.
  13672. *
  13673. * @augments BufferAttribute
  13674. */
  13675. class Int8BufferAttribute extends BufferAttribute {
  13676. /**
  13677. * Constructs a new buffer attribute.
  13678. *
  13679. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13680. * @param {number} itemSize - The item size.
  13681. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13682. */
  13683. constructor( array, itemSize, normalized ) {
  13684. super( new Int8Array( array ), itemSize, normalized );
  13685. }
  13686. }
  13687. /**
  13688. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13689. * a plain `Array` instance.
  13690. *
  13691. * @augments BufferAttribute
  13692. */
  13693. class Uint8BufferAttribute extends BufferAttribute {
  13694. /**
  13695. * Constructs a new buffer attribute.
  13696. *
  13697. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13698. * @param {number} itemSize - The item size.
  13699. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13700. */
  13701. constructor( array, itemSize, normalized ) {
  13702. super( new Uint8Array( array ), itemSize, normalized );
  13703. }
  13704. }
  13705. /**
  13706. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13707. * a plain `Array` instance.
  13708. *
  13709. * @augments BufferAttribute
  13710. */
  13711. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13712. /**
  13713. * Constructs a new buffer attribute.
  13714. *
  13715. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13716. * @param {number} itemSize - The item size.
  13717. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13718. */
  13719. constructor( array, itemSize, normalized ) {
  13720. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13721. }
  13722. }
  13723. /**
  13724. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13725. * a plain `Array` instance.
  13726. *
  13727. * @augments BufferAttribute
  13728. */
  13729. class Int16BufferAttribute extends BufferAttribute {
  13730. /**
  13731. * Constructs a new buffer attribute.
  13732. *
  13733. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13734. * @param {number} itemSize - The item size.
  13735. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13736. */
  13737. constructor( array, itemSize, normalized ) {
  13738. super( new Int16Array( array ), itemSize, normalized );
  13739. }
  13740. }
  13741. /**
  13742. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13743. * a plain `Array` instance.
  13744. *
  13745. * @augments BufferAttribute
  13746. */
  13747. class Uint16BufferAttribute extends BufferAttribute {
  13748. /**
  13749. * Constructs a new buffer attribute.
  13750. *
  13751. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13752. * @param {number} itemSize - The item size.
  13753. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13754. */
  13755. constructor( array, itemSize, normalized ) {
  13756. super( new Uint16Array( array ), itemSize, normalized );
  13757. }
  13758. }
  13759. /**
  13760. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13761. * a plain `Array` instance.
  13762. *
  13763. * @augments BufferAttribute
  13764. */
  13765. class Int32BufferAttribute extends BufferAttribute {
  13766. /**
  13767. * Constructs a new buffer attribute.
  13768. *
  13769. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13770. * @param {number} itemSize - The item size.
  13771. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13772. */
  13773. constructor( array, itemSize, normalized ) {
  13774. super( new Int32Array( array ), itemSize, normalized );
  13775. }
  13776. }
  13777. /**
  13778. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13779. * a plain `Array` instance.
  13780. *
  13781. * @augments BufferAttribute
  13782. */
  13783. class Uint32BufferAttribute extends BufferAttribute {
  13784. /**
  13785. * Constructs a new buffer attribute.
  13786. *
  13787. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13788. * @param {number} itemSize - The item size.
  13789. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13790. */
  13791. constructor( array, itemSize, normalized ) {
  13792. super( new Uint32Array( array ), itemSize, normalized );
  13793. }
  13794. }
  13795. /**
  13796. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13797. * a plain `Array` instance.
  13798. *
  13799. * This class automatically converts to to and from FP16 since `Float16Array` is not
  13800. * natively supported in JavaScript.
  13801. *
  13802. * @augments BufferAttribute
  13803. */
  13804. class Float16BufferAttribute extends BufferAttribute {
  13805. /**
  13806. * Constructs a new buffer attribute.
  13807. *
  13808. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13809. * @param {number} itemSize - The item size.
  13810. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13811. */
  13812. constructor( array, itemSize, normalized ) {
  13813. super( new Uint16Array( array ), itemSize, normalized );
  13814. this.isFloat16BufferAttribute = true;
  13815. }
  13816. getX( index ) {
  13817. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13818. if ( this.normalized ) x = denormalize( x, this.array );
  13819. return x;
  13820. }
  13821. setX( index, x ) {
  13822. if ( this.normalized ) x = normalize( x, this.array );
  13823. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13824. return this;
  13825. }
  13826. getY( index ) {
  13827. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13828. if ( this.normalized ) y = denormalize( y, this.array );
  13829. return y;
  13830. }
  13831. setY( index, y ) {
  13832. if ( this.normalized ) y = normalize( y, this.array );
  13833. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13834. return this;
  13835. }
  13836. getZ( index ) {
  13837. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13838. if ( this.normalized ) z = denormalize( z, this.array );
  13839. return z;
  13840. }
  13841. setZ( index, z ) {
  13842. if ( this.normalized ) z = normalize( z, this.array );
  13843. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13844. return this;
  13845. }
  13846. getW( index ) {
  13847. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13848. if ( this.normalized ) w = denormalize( w, this.array );
  13849. return w;
  13850. }
  13851. setW( index, w ) {
  13852. if ( this.normalized ) w = normalize( w, this.array );
  13853. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13854. return this;
  13855. }
  13856. setXY( index, x, y ) {
  13857. index *= this.itemSize;
  13858. if ( this.normalized ) {
  13859. x = normalize( x, this.array );
  13860. y = normalize( y, this.array );
  13861. }
  13862. this.array[ index + 0 ] = toHalfFloat( x );
  13863. this.array[ index + 1 ] = toHalfFloat( y );
  13864. return this;
  13865. }
  13866. setXYZ( index, x, y, z ) {
  13867. index *= this.itemSize;
  13868. if ( this.normalized ) {
  13869. x = normalize( x, this.array );
  13870. y = normalize( y, this.array );
  13871. z = normalize( z, this.array );
  13872. }
  13873. this.array[ index + 0 ] = toHalfFloat( x );
  13874. this.array[ index + 1 ] = toHalfFloat( y );
  13875. this.array[ index + 2 ] = toHalfFloat( z );
  13876. return this;
  13877. }
  13878. setXYZW( index, x, y, z, w ) {
  13879. index *= this.itemSize;
  13880. if ( this.normalized ) {
  13881. x = normalize( x, this.array );
  13882. y = normalize( y, this.array );
  13883. z = normalize( z, this.array );
  13884. w = normalize( w, this.array );
  13885. }
  13886. this.array[ index + 0 ] = toHalfFloat( x );
  13887. this.array[ index + 1 ] = toHalfFloat( y );
  13888. this.array[ index + 2 ] = toHalfFloat( z );
  13889. this.array[ index + 3 ] = toHalfFloat( w );
  13890. return this;
  13891. }
  13892. }
  13893. /**
  13894. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13895. * a plain `Array` instance.
  13896. *
  13897. * @augments BufferAttribute
  13898. */
  13899. class Float32BufferAttribute extends BufferAttribute {
  13900. /**
  13901. * Constructs a new buffer attribute.
  13902. *
  13903. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13904. * @param {number} itemSize - The item size.
  13905. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13906. */
  13907. constructor( array, itemSize, normalized ) {
  13908. super( new Float32Array( array ), itemSize, normalized );
  13909. }
  13910. }
  13911. let _id$2 = 0;
  13912. const _m1$2 = /*@__PURE__*/ new Matrix4();
  13913. const _obj = /*@__PURE__*/ new Object3D();
  13914. const _offset = /*@__PURE__*/ new Vector3();
  13915. const _box$2 = /*@__PURE__*/ new Box3();
  13916. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13917. const _vector$8 = /*@__PURE__*/ new Vector3();
  13918. /**
  13919. * A representation of mesh, line, or point geometry. Includes vertex
  13920. * positions, face indices, normals, colors, UVs, and custom attributes
  13921. * within buffers, reducing the cost of passing all this data to the GPU.
  13922. *
  13923. * ```js
  13924. * const geometry = new THREE.BufferGeometry();
  13925. * // create a simple square shape. We duplicate the top left and bottom right
  13926. * // vertices because each vertex needs to appear once per triangle.
  13927. * const vertices = new Float32Array( [
  13928. * -1.0, -1.0, 1.0, // v0
  13929. * 1.0, -1.0, 1.0, // v1
  13930. * 1.0, 1.0, 1.0, // v2
  13931. *
  13932. * 1.0, 1.0, 1.0, // v3
  13933. * -1.0, 1.0, 1.0, // v4
  13934. * -1.0, -1.0, 1.0 // v5
  13935. * ] );
  13936. * // itemSize = 3 because there are 3 values (components) per vertex
  13937. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13938. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13939. * const mesh = new THREE.Mesh( geometry, material );
  13940. * ```
  13941. *
  13942. * @augments EventDispatcher
  13943. */
  13944. class BufferGeometry extends EventDispatcher {
  13945. /**
  13946. * Constructs a new geometry.
  13947. */
  13948. constructor() {
  13949. super();
  13950. /**
  13951. * This flag can be used for type testing.
  13952. *
  13953. * @type {boolean}
  13954. * @readonly
  13955. * @default true
  13956. */
  13957. this.isBufferGeometry = true;
  13958. /**
  13959. * The ID of the geometry.
  13960. *
  13961. * @name BufferGeometry#id
  13962. * @type {number}
  13963. * @readonly
  13964. */
  13965. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13966. /**
  13967. * The UUID of the geometry.
  13968. *
  13969. * @type {string}
  13970. * @readonly
  13971. */
  13972. this.uuid = generateUUID();
  13973. /**
  13974. * The name of the geometry.
  13975. *
  13976. * @type {string}
  13977. */
  13978. this.name = '';
  13979. this.type = 'BufferGeometry';
  13980. /**
  13981. * Allows for vertices to be re-used across multiple triangles; this is
  13982. * called using "indexed triangles". Each triangle is associated with the
  13983. * indices of three vertices. This attribute therefore stores the index of
  13984. * each vertex for each triangular face. If this attribute is not set, the
  13985. * renderer assumes that each three contiguous positions represent a single triangle.
  13986. *
  13987. * @type {?BufferAttribute}
  13988. * @default null
  13989. */
  13990. this.index = null;
  13991. /**
  13992. * A (storage) buffer attribute which was generated with a compute shader and
  13993. * now defines indirect draw calls.
  13994. *
  13995. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13996. *
  13997. * @type {?BufferAttribute}
  13998. * @default null
  13999. */
  14000. this.indirect = null;
  14001. /**
  14002. * This dictionary has as id the name of the attribute to be set and as value
  14003. * the buffer attribute to set it to. Rather than accessing this property directly,
  14004. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14005. *
  14006. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14007. */
  14008. this.attributes = {};
  14009. /**
  14010. * This dictionary holds the morph targets of the geometry.
  14011. *
  14012. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14013. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14014. *
  14015. * @type {Object}
  14016. */
  14017. this.morphAttributes = {};
  14018. /**
  14019. * Used to control the morph target behavior; when set to `true`, the morph
  14020. * target data is treated as relative offsets, rather than as absolute
  14021. * positions/normals.
  14022. *
  14023. * @type {boolean}
  14024. * @default false
  14025. */
  14026. this.morphTargetsRelative = false;
  14027. /**
  14028. * Split the geometry into groups, each of which will be rendered in a
  14029. * separate draw call. This allows an array of materials to be used with the geometry.
  14030. *
  14031. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14032. *
  14033. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14034. * indices, and must not leave vertices or indices unused.
  14035. *
  14036. * @type {Array<Object>}
  14037. */
  14038. this.groups = [];
  14039. /**
  14040. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14041. *
  14042. * @type {Box3}
  14043. * @default null
  14044. */
  14045. this.boundingBox = null;
  14046. /**
  14047. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14048. *
  14049. * @type {Sphere}
  14050. * @default null
  14051. */
  14052. this.boundingSphere = null;
  14053. /**
  14054. * Determines the part of the geometry to render. This should not be set directly,
  14055. * instead use `setDrawRange()`.
  14056. *
  14057. * @type {{start:number,count:number}}
  14058. */
  14059. this.drawRange = { start: 0, count: Infinity };
  14060. /**
  14061. * An object that can be used to store custom data about the geometry.
  14062. * It should not hold references to functions as these will not be cloned.
  14063. *
  14064. * @type {Object}
  14065. */
  14066. this.userData = {};
  14067. }
  14068. /**
  14069. * Returns the index of this geometry.
  14070. *
  14071. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14072. */
  14073. getIndex() {
  14074. return this.index;
  14075. }
  14076. /**
  14077. * Sets the given index to this geometry.
  14078. *
  14079. * @param {Array<number>|BufferAttribute} index - The index to set.
  14080. * @return {BufferGeometry} A reference to this instance.
  14081. */
  14082. setIndex( index ) {
  14083. if ( Array.isArray( index ) ) {
  14084. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14085. } else {
  14086. this.index = index;
  14087. }
  14088. return this;
  14089. }
  14090. /**
  14091. * Sets the given indirect attribute to this geometry.
  14092. *
  14093. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14094. * @return {BufferGeometry} A reference to this instance.
  14095. */
  14096. setIndirect( indirect ) {
  14097. this.indirect = indirect;
  14098. return this;
  14099. }
  14100. /**
  14101. * Returns the indirect attribute of this geometry.
  14102. *
  14103. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14104. */
  14105. getIndirect() {
  14106. return this.indirect;
  14107. }
  14108. /**
  14109. * Returns the buffer attribute for the given name.
  14110. *
  14111. * @param {string} name - The attribute name.
  14112. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14113. * Returns `undefined` if not attribute has been found.
  14114. */
  14115. getAttribute( name ) {
  14116. return this.attributes[ name ];
  14117. }
  14118. /**
  14119. * Sets the given attribute for the given name.
  14120. *
  14121. * @param {string} name - The attribute name.
  14122. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14123. * @return {BufferGeometry} A reference to this instance.
  14124. */
  14125. setAttribute( name, attribute ) {
  14126. this.attributes[ name ] = attribute;
  14127. return this;
  14128. }
  14129. /**
  14130. * Deletes the attribute for the given name.
  14131. *
  14132. * @param {string} name - The attribute name to delete.
  14133. * @return {BufferGeometry} A reference to this instance.
  14134. */
  14135. deleteAttribute( name ) {
  14136. delete this.attributes[ name ];
  14137. return this;
  14138. }
  14139. /**
  14140. * Returns `true` if this geometry has an attribute for the given name.
  14141. *
  14142. * @param {string} name - The attribute name.
  14143. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14144. */
  14145. hasAttribute( name ) {
  14146. return this.attributes[ name ] !== undefined;
  14147. }
  14148. /**
  14149. * Adds a group to this geometry.
  14150. *
  14151. * @param {number} start - The first element in this draw call. That is the first
  14152. * vertex for non-indexed geometry, otherwise the first triangle index.
  14153. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14154. * @param {number} [materialIndex=0] - The material array index to use.
  14155. */
  14156. addGroup( start, count, materialIndex = 0 ) {
  14157. this.groups.push( {
  14158. start: start,
  14159. count: count,
  14160. materialIndex: materialIndex
  14161. } );
  14162. }
  14163. /**
  14164. * Clears all groups.
  14165. */
  14166. clearGroups() {
  14167. this.groups = [];
  14168. }
  14169. /**
  14170. * Sets the draw range for this geometry.
  14171. *
  14172. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14173. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14174. * For indexed BufferGeometry, `count` is the number of indices to render.
  14175. */
  14176. setDrawRange( start, count ) {
  14177. this.drawRange.start = start;
  14178. this.drawRange.count = count;
  14179. }
  14180. /**
  14181. * Applies the given 4x4 transformation matrix to the geometry.
  14182. *
  14183. * @param {Matrix4} matrix - The matrix to apply.
  14184. * @return {BufferGeometry} A reference to this instance.
  14185. */
  14186. applyMatrix4( matrix ) {
  14187. const position = this.attributes.position;
  14188. if ( position !== undefined ) {
  14189. position.applyMatrix4( matrix );
  14190. position.needsUpdate = true;
  14191. }
  14192. const normal = this.attributes.normal;
  14193. if ( normal !== undefined ) {
  14194. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14195. normal.applyNormalMatrix( normalMatrix );
  14196. normal.needsUpdate = true;
  14197. }
  14198. const tangent = this.attributes.tangent;
  14199. if ( tangent !== undefined ) {
  14200. tangent.transformDirection( matrix );
  14201. tangent.needsUpdate = true;
  14202. }
  14203. if ( this.boundingBox !== null ) {
  14204. this.computeBoundingBox();
  14205. }
  14206. if ( this.boundingSphere !== null ) {
  14207. this.computeBoundingSphere();
  14208. }
  14209. return this;
  14210. }
  14211. /**
  14212. * Applies the rotation represented by the Quaternion to the geometry.
  14213. *
  14214. * @param {Quaternion} q - The Quaternion to apply.
  14215. * @return {BufferGeometry} A reference to this instance.
  14216. */
  14217. applyQuaternion( q ) {
  14218. _m1$2.makeRotationFromQuaternion( q );
  14219. this.applyMatrix4( _m1$2 );
  14220. return this;
  14221. }
  14222. /**
  14223. * Rotates the geometry about the X axis. This is typically done as a one time
  14224. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14225. * real-time mesh rotation.
  14226. *
  14227. * @param {number} angle - The angle in radians.
  14228. * @return {BufferGeometry} A reference to this instance.
  14229. */
  14230. rotateX( angle ) {
  14231. // rotate geometry around world x-axis
  14232. _m1$2.makeRotationX( angle );
  14233. this.applyMatrix4( _m1$2 );
  14234. return this;
  14235. }
  14236. /**
  14237. * Rotates the geometry about the Y axis. This is typically done as a one time
  14238. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14239. * real-time mesh rotation.
  14240. *
  14241. * @param {number} angle - The angle in radians.
  14242. * @return {BufferGeometry} A reference to this instance.
  14243. */
  14244. rotateY( angle ) {
  14245. // rotate geometry around world y-axis
  14246. _m1$2.makeRotationY( angle );
  14247. this.applyMatrix4( _m1$2 );
  14248. return this;
  14249. }
  14250. /**
  14251. * Rotates the geometry about the Z axis. This is typically done as a one time
  14252. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14253. * real-time mesh rotation.
  14254. *
  14255. * @param {number} angle - The angle in radians.
  14256. * @return {BufferGeometry} A reference to this instance.
  14257. */
  14258. rotateZ( angle ) {
  14259. // rotate geometry around world z-axis
  14260. _m1$2.makeRotationZ( angle );
  14261. this.applyMatrix4( _m1$2 );
  14262. return this;
  14263. }
  14264. /**
  14265. * Translates the geometry. This is typically done as a one time
  14266. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14267. * real-time mesh rotation.
  14268. *
  14269. * @param {number} x - The x offset.
  14270. * @param {number} y - The y offset.
  14271. * @param {number} z - The z offset.
  14272. * @return {BufferGeometry} A reference to this instance.
  14273. */
  14274. translate( x, y, z ) {
  14275. // translate geometry
  14276. _m1$2.makeTranslation( x, y, z );
  14277. this.applyMatrix4( _m1$2 );
  14278. return this;
  14279. }
  14280. /**
  14281. * Scales the geometry. This is typically done as a one time
  14282. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14283. * real-time mesh rotation.
  14284. *
  14285. * @param {number} x - The x scale.
  14286. * @param {number} y - The y scale.
  14287. * @param {number} z - The z scale.
  14288. * @return {BufferGeometry} A reference to this instance.
  14289. */
  14290. scale( x, y, z ) {
  14291. // scale geometry
  14292. _m1$2.makeScale( x, y, z );
  14293. this.applyMatrix4( _m1$2 );
  14294. return this;
  14295. }
  14296. /**
  14297. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14298. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14299. * real-time mesh rotation.
  14300. *
  14301. * @param {Vector3} vector - The target point.
  14302. * @return {BufferGeometry} A reference to this instance.
  14303. */
  14304. lookAt( vector ) {
  14305. _obj.lookAt( vector );
  14306. _obj.updateMatrix();
  14307. this.applyMatrix4( _obj.matrix );
  14308. return this;
  14309. }
  14310. /**
  14311. * Center the geometry based on its bounding box.
  14312. *
  14313. * @return {BufferGeometry} A reference to this instance.
  14314. */
  14315. center() {
  14316. this.computeBoundingBox();
  14317. this.boundingBox.getCenter( _offset ).negate();
  14318. this.translate( _offset.x, _offset.y, _offset.z );
  14319. return this;
  14320. }
  14321. /**
  14322. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14323. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14324. * set to `0`.
  14325. *
  14326. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14327. * data from the array. The length of the array must match the vertex count.
  14328. *
  14329. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14330. * @return {BufferGeometry} A reference to this instance.
  14331. */
  14332. setFromPoints( points ) {
  14333. const positionAttribute = this.getAttribute( 'position' );
  14334. if ( positionAttribute === undefined ) {
  14335. const position = [];
  14336. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14337. const point = points[ i ];
  14338. position.push( point.x, point.y, point.z || 0 );
  14339. }
  14340. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14341. } else {
  14342. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14343. for ( let i = 0; i < l; i ++ ) {
  14344. const point = points[ i ];
  14345. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14346. }
  14347. if ( points.length > positionAttribute.count ) {
  14348. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14349. }
  14350. positionAttribute.needsUpdate = true;
  14351. }
  14352. return this;
  14353. }
  14354. /**
  14355. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14356. * The bounding box is not computed by the engine; it must be computed by your app.
  14357. * You may need to recompute the bounding box if the geometry vertices are modified.
  14358. */
  14359. computeBoundingBox() {
  14360. if ( this.boundingBox === null ) {
  14361. this.boundingBox = new Box3();
  14362. }
  14363. const position = this.attributes.position;
  14364. const morphAttributesPosition = this.morphAttributes.position;
  14365. if ( position && position.isGLBufferAttribute ) {
  14366. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14367. this.boundingBox.set(
  14368. new Vector3( - Infinity, - Infinity, - Infinity ),
  14369. new Vector3( + Infinity, + Infinity, + Infinity )
  14370. );
  14371. return;
  14372. }
  14373. if ( position !== undefined ) {
  14374. this.boundingBox.setFromBufferAttribute( position );
  14375. // process morph attributes if present
  14376. if ( morphAttributesPosition ) {
  14377. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14378. const morphAttribute = morphAttributesPosition[ i ];
  14379. _box$2.setFromBufferAttribute( morphAttribute );
  14380. if ( this.morphTargetsRelative ) {
  14381. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14382. this.boundingBox.expandByPoint( _vector$8 );
  14383. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14384. this.boundingBox.expandByPoint( _vector$8 );
  14385. } else {
  14386. this.boundingBox.expandByPoint( _box$2.min );
  14387. this.boundingBox.expandByPoint( _box$2.max );
  14388. }
  14389. }
  14390. }
  14391. } else {
  14392. this.boundingBox.makeEmpty();
  14393. }
  14394. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14395. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14396. }
  14397. }
  14398. /**
  14399. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14400. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14401. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14402. */
  14403. computeBoundingSphere() {
  14404. if ( this.boundingSphere === null ) {
  14405. this.boundingSphere = new Sphere();
  14406. }
  14407. const position = this.attributes.position;
  14408. const morphAttributesPosition = this.morphAttributes.position;
  14409. if ( position && position.isGLBufferAttribute ) {
  14410. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14411. this.boundingSphere.set( new Vector3(), Infinity );
  14412. return;
  14413. }
  14414. if ( position ) {
  14415. // first, find the center of the bounding sphere
  14416. const center = this.boundingSphere.center;
  14417. _box$2.setFromBufferAttribute( position );
  14418. // process morph attributes if present
  14419. if ( morphAttributesPosition ) {
  14420. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14421. const morphAttribute = morphAttributesPosition[ i ];
  14422. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14423. if ( this.morphTargetsRelative ) {
  14424. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14425. _box$2.expandByPoint( _vector$8 );
  14426. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14427. _box$2.expandByPoint( _vector$8 );
  14428. } else {
  14429. _box$2.expandByPoint( _boxMorphTargets.min );
  14430. _box$2.expandByPoint( _boxMorphTargets.max );
  14431. }
  14432. }
  14433. }
  14434. _box$2.getCenter( center );
  14435. // second, try to find a boundingSphere with a radius smaller than the
  14436. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14437. let maxRadiusSq = 0;
  14438. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14439. _vector$8.fromBufferAttribute( position, i );
  14440. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14441. }
  14442. // process morph attributes if present
  14443. if ( morphAttributesPosition ) {
  14444. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14445. const morphAttribute = morphAttributesPosition[ i ];
  14446. const morphTargetsRelative = this.morphTargetsRelative;
  14447. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14448. _vector$8.fromBufferAttribute( morphAttribute, j );
  14449. if ( morphTargetsRelative ) {
  14450. _offset.fromBufferAttribute( position, j );
  14451. _vector$8.add( _offset );
  14452. }
  14453. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14454. }
  14455. }
  14456. }
  14457. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14458. if ( isNaN( this.boundingSphere.radius ) ) {
  14459. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14460. }
  14461. }
  14462. }
  14463. /**
  14464. * Calculates and adds a tangent attribute to this geometry.
  14465. *
  14466. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14467. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14468. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14469. */
  14470. computeTangents() {
  14471. const index = this.index;
  14472. const attributes = this.attributes;
  14473. // based on http://www.terathon.com/code/tangent.html
  14474. // (per vertex tangents)
  14475. if ( index === null ||
  14476. attributes.position === undefined ||
  14477. attributes.normal === undefined ||
  14478. attributes.uv === undefined ) {
  14479. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14480. return;
  14481. }
  14482. const positionAttribute = attributes.position;
  14483. const normalAttribute = attributes.normal;
  14484. const uvAttribute = attributes.uv;
  14485. if ( this.hasAttribute( 'tangent' ) === false ) {
  14486. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14487. }
  14488. const tangentAttribute = this.getAttribute( 'tangent' );
  14489. const tan1 = [], tan2 = [];
  14490. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14491. tan1[ i ] = new Vector3();
  14492. tan2[ i ] = new Vector3();
  14493. }
  14494. const vA = new Vector3(),
  14495. vB = new Vector3(),
  14496. vC = new Vector3(),
  14497. uvA = new Vector2(),
  14498. uvB = new Vector2(),
  14499. uvC = new Vector2(),
  14500. sdir = new Vector3(),
  14501. tdir = new Vector3();
  14502. function handleTriangle( a, b, c ) {
  14503. vA.fromBufferAttribute( positionAttribute, a );
  14504. vB.fromBufferAttribute( positionAttribute, b );
  14505. vC.fromBufferAttribute( positionAttribute, c );
  14506. uvA.fromBufferAttribute( uvAttribute, a );
  14507. uvB.fromBufferAttribute( uvAttribute, b );
  14508. uvC.fromBufferAttribute( uvAttribute, c );
  14509. vB.sub( vA );
  14510. vC.sub( vA );
  14511. uvB.sub( uvA );
  14512. uvC.sub( uvA );
  14513. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14514. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14515. if ( ! isFinite( r ) ) return;
  14516. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14517. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14518. tan1[ a ].add( sdir );
  14519. tan1[ b ].add( sdir );
  14520. tan1[ c ].add( sdir );
  14521. tan2[ a ].add( tdir );
  14522. tan2[ b ].add( tdir );
  14523. tan2[ c ].add( tdir );
  14524. }
  14525. let groups = this.groups;
  14526. if ( groups.length === 0 ) {
  14527. groups = [ {
  14528. start: 0,
  14529. count: index.count
  14530. } ];
  14531. }
  14532. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14533. const group = groups[ i ];
  14534. const start = group.start;
  14535. const count = group.count;
  14536. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14537. handleTriangle(
  14538. index.getX( j + 0 ),
  14539. index.getX( j + 1 ),
  14540. index.getX( j + 2 )
  14541. );
  14542. }
  14543. }
  14544. const tmp = new Vector3(), tmp2 = new Vector3();
  14545. const n = new Vector3(), n2 = new Vector3();
  14546. function handleVertex( v ) {
  14547. n.fromBufferAttribute( normalAttribute, v );
  14548. n2.copy( n );
  14549. const t = tan1[ v ];
  14550. // Gram-Schmidt orthogonalize
  14551. tmp.copy( t );
  14552. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14553. // Calculate handedness
  14554. tmp2.crossVectors( n2, t );
  14555. const test = tmp2.dot( tan2[ v ] );
  14556. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  14557. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14558. }
  14559. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14560. const group = groups[ i ];
  14561. const start = group.start;
  14562. const count = group.count;
  14563. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14564. handleVertex( index.getX( j + 0 ) );
  14565. handleVertex( index.getX( j + 1 ) );
  14566. handleVertex( index.getX( j + 2 ) );
  14567. }
  14568. }
  14569. }
  14570. /**
  14571. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14572. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14573. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14574. * to be the same as the face normal.
  14575. */
  14576. computeVertexNormals() {
  14577. const index = this.index;
  14578. const positionAttribute = this.getAttribute( 'position' );
  14579. if ( positionAttribute !== undefined ) {
  14580. let normalAttribute = this.getAttribute( 'normal' );
  14581. if ( normalAttribute === undefined ) {
  14582. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14583. this.setAttribute( 'normal', normalAttribute );
  14584. } else {
  14585. // reset existing normals to zero
  14586. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14587. normalAttribute.setXYZ( i, 0, 0, 0 );
  14588. }
  14589. }
  14590. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14591. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14592. const cb = new Vector3(), ab = new Vector3();
  14593. // indexed elements
  14594. if ( index ) {
  14595. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14596. const vA = index.getX( i + 0 );
  14597. const vB = index.getX( i + 1 );
  14598. const vC = index.getX( i + 2 );
  14599. pA.fromBufferAttribute( positionAttribute, vA );
  14600. pB.fromBufferAttribute( positionAttribute, vB );
  14601. pC.fromBufferAttribute( positionAttribute, vC );
  14602. cb.subVectors( pC, pB );
  14603. ab.subVectors( pA, pB );
  14604. cb.cross( ab );
  14605. nA.fromBufferAttribute( normalAttribute, vA );
  14606. nB.fromBufferAttribute( normalAttribute, vB );
  14607. nC.fromBufferAttribute( normalAttribute, vC );
  14608. nA.add( cb );
  14609. nB.add( cb );
  14610. nC.add( cb );
  14611. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14612. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14613. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14614. }
  14615. } else {
  14616. // non-indexed elements (unconnected triangle soup)
  14617. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14618. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14619. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14620. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14621. cb.subVectors( pC, pB );
  14622. ab.subVectors( pA, pB );
  14623. cb.cross( ab );
  14624. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14625. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14626. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14627. }
  14628. }
  14629. this.normalizeNormals();
  14630. normalAttribute.needsUpdate = true;
  14631. }
  14632. }
  14633. /**
  14634. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14635. * correct lighting on the geometry surfaces.
  14636. */
  14637. normalizeNormals() {
  14638. const normals = this.attributes.normal;
  14639. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14640. _vector$8.fromBufferAttribute( normals, i );
  14641. _vector$8.normalize();
  14642. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14643. }
  14644. }
  14645. /**
  14646. * Return a new non-index version of this indexed geometry. If the geometry
  14647. * is already non-indexed, the method is a NOOP.
  14648. *
  14649. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14650. */
  14651. toNonIndexed() {
  14652. function convertBufferAttribute( attribute, indices ) {
  14653. const array = attribute.array;
  14654. const itemSize = attribute.itemSize;
  14655. const normalized = attribute.normalized;
  14656. const array2 = new array.constructor( indices.length * itemSize );
  14657. let index = 0, index2 = 0;
  14658. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14659. if ( attribute.isInterleavedBufferAttribute ) {
  14660. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14661. } else {
  14662. index = indices[ i ] * itemSize;
  14663. }
  14664. for ( let j = 0; j < itemSize; j ++ ) {
  14665. array2[ index2 ++ ] = array[ index ++ ];
  14666. }
  14667. }
  14668. return new BufferAttribute( array2, itemSize, normalized );
  14669. }
  14670. //
  14671. if ( this.index === null ) {
  14672. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14673. return this;
  14674. }
  14675. const geometry2 = new BufferGeometry();
  14676. const indices = this.index.array;
  14677. const attributes = this.attributes;
  14678. // attributes
  14679. for ( const name in attributes ) {
  14680. const attribute = attributes[ name ];
  14681. const newAttribute = convertBufferAttribute( attribute, indices );
  14682. geometry2.setAttribute( name, newAttribute );
  14683. }
  14684. // morph attributes
  14685. const morphAttributes = this.morphAttributes;
  14686. for ( const name in morphAttributes ) {
  14687. const morphArray = [];
  14688. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14689. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14690. const attribute = morphAttribute[ i ];
  14691. const newAttribute = convertBufferAttribute( attribute, indices );
  14692. morphArray.push( newAttribute );
  14693. }
  14694. geometry2.morphAttributes[ name ] = morphArray;
  14695. }
  14696. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14697. // groups
  14698. const groups = this.groups;
  14699. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14700. const group = groups[ i ];
  14701. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14702. }
  14703. return geometry2;
  14704. }
  14705. /**
  14706. * Serializes the geometry into JSON.
  14707. *
  14708. * @return {Object} A JSON object representing the serialized geometry.
  14709. */
  14710. toJSON() {
  14711. const data = {
  14712. metadata: {
  14713. version: 4.6,
  14714. type: 'BufferGeometry',
  14715. generator: 'BufferGeometry.toJSON'
  14716. }
  14717. };
  14718. // standard BufferGeometry serialization
  14719. data.uuid = this.uuid;
  14720. data.type = this.type;
  14721. if ( this.name !== '' ) data.name = this.name;
  14722. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14723. if ( this.parameters !== undefined ) {
  14724. const parameters = this.parameters;
  14725. for ( const key in parameters ) {
  14726. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14727. }
  14728. return data;
  14729. }
  14730. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14731. data.data = { attributes: {} };
  14732. const index = this.index;
  14733. if ( index !== null ) {
  14734. data.data.index = {
  14735. type: index.array.constructor.name,
  14736. array: Array.prototype.slice.call( index.array )
  14737. };
  14738. }
  14739. const attributes = this.attributes;
  14740. for ( const key in attributes ) {
  14741. const attribute = attributes[ key ];
  14742. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14743. }
  14744. const morphAttributes = {};
  14745. let hasMorphAttributes = false;
  14746. for ( const key in this.morphAttributes ) {
  14747. const attributeArray = this.morphAttributes[ key ];
  14748. const array = [];
  14749. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14750. const attribute = attributeArray[ i ];
  14751. array.push( attribute.toJSON( data.data ) );
  14752. }
  14753. if ( array.length > 0 ) {
  14754. morphAttributes[ key ] = array;
  14755. hasMorphAttributes = true;
  14756. }
  14757. }
  14758. if ( hasMorphAttributes ) {
  14759. data.data.morphAttributes = morphAttributes;
  14760. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14761. }
  14762. const groups = this.groups;
  14763. if ( groups.length > 0 ) {
  14764. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14765. }
  14766. const boundingSphere = this.boundingSphere;
  14767. if ( boundingSphere !== null ) {
  14768. data.data.boundingSphere = {
  14769. center: boundingSphere.center.toArray(),
  14770. radius: boundingSphere.radius
  14771. };
  14772. }
  14773. return data;
  14774. }
  14775. /**
  14776. * Returns a new geometry with copied values from this instance.
  14777. *
  14778. * @return {BufferGeometry} A clone of this instance.
  14779. */
  14780. clone() {
  14781. return new this.constructor().copy( this );
  14782. }
  14783. /**
  14784. * Copies the values of the given geometry to this instance.
  14785. *
  14786. * @param {BufferGeometry} source - The geometry to copy.
  14787. * @return {BufferGeometry} A reference to this instance.
  14788. */
  14789. copy( source ) {
  14790. // reset
  14791. this.index = null;
  14792. this.attributes = {};
  14793. this.morphAttributes = {};
  14794. this.groups = [];
  14795. this.boundingBox = null;
  14796. this.boundingSphere = null;
  14797. // used for storing cloned, shared data
  14798. const data = {};
  14799. // name
  14800. this.name = source.name;
  14801. // index
  14802. const index = source.index;
  14803. if ( index !== null ) {
  14804. this.setIndex( index.clone() );
  14805. }
  14806. // attributes
  14807. const attributes = source.attributes;
  14808. for ( const name in attributes ) {
  14809. const attribute = attributes[ name ];
  14810. this.setAttribute( name, attribute.clone( data ) );
  14811. }
  14812. // morph attributes
  14813. const morphAttributes = source.morphAttributes;
  14814. for ( const name in morphAttributes ) {
  14815. const array = [];
  14816. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14817. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14818. array.push( morphAttribute[ i ].clone( data ) );
  14819. }
  14820. this.morphAttributes[ name ] = array;
  14821. }
  14822. this.morphTargetsRelative = source.morphTargetsRelative;
  14823. // groups
  14824. const groups = source.groups;
  14825. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14826. const group = groups[ i ];
  14827. this.addGroup( group.start, group.count, group.materialIndex );
  14828. }
  14829. // bounding box
  14830. const boundingBox = source.boundingBox;
  14831. if ( boundingBox !== null ) {
  14832. this.boundingBox = boundingBox.clone();
  14833. }
  14834. // bounding sphere
  14835. const boundingSphere = source.boundingSphere;
  14836. if ( boundingSphere !== null ) {
  14837. this.boundingSphere = boundingSphere.clone();
  14838. }
  14839. // draw range
  14840. this.drawRange.start = source.drawRange.start;
  14841. this.drawRange.count = source.drawRange.count;
  14842. // user data
  14843. this.userData = source.userData;
  14844. return this;
  14845. }
  14846. /**
  14847. * Frees the GPU-related resources allocated by this instance. Call this
  14848. * method whenever this instance is no longer used in your app.
  14849. *
  14850. * @fires BufferGeometry#dispose
  14851. */
  14852. dispose() {
  14853. this.dispatchEvent( { type: 'dispose' } );
  14854. }
  14855. }
  14856. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  14857. const _ray$3 = /*@__PURE__*/ new Ray();
  14858. const _sphere$6 = /*@__PURE__*/ new Sphere();
  14859. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  14860. const _vA$1 = /*@__PURE__*/ new Vector3();
  14861. const _vB$1 = /*@__PURE__*/ new Vector3();
  14862. const _vC$1 = /*@__PURE__*/ new Vector3();
  14863. const _tempA = /*@__PURE__*/ new Vector3();
  14864. const _morphA = /*@__PURE__*/ new Vector3();
  14865. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  14866. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  14867. /**
  14868. * Class representing triangular polygon mesh based objects.
  14869. *
  14870. * ```js
  14871. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  14872. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  14873. * const mesh = new THREE.Mesh( geometry, material );
  14874. * scene.add( mesh );
  14875. * ```
  14876. *
  14877. * @augments Object3D
  14878. */
  14879. class Mesh extends Object3D {
  14880. /**
  14881. * Constructs a new mesh.
  14882. *
  14883. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14884. * @param {Material|Array<Material>} [material] - The mesh material.
  14885. */
  14886. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  14887. super();
  14888. /**
  14889. * This flag can be used for type testing.
  14890. *
  14891. * @type {boolean}
  14892. * @readonly
  14893. * @default true
  14894. */
  14895. this.isMesh = true;
  14896. this.type = 'Mesh';
  14897. /**
  14898. * The mesh geometry.
  14899. *
  14900. * @type {BufferGeometry}
  14901. */
  14902. this.geometry = geometry;
  14903. /**
  14904. * The mesh material.
  14905. *
  14906. * @type {Material|Array<Material>}
  14907. * @default MeshBasicMaterial
  14908. */
  14909. this.material = material;
  14910. /**
  14911. * A dictionary representing the morph targets in the geometry. The key is the
  14912. * morph targets name, the value its attribute index. This member is `undefined`
  14913. * by default and only set when morph targets are detected in the geometry.
  14914. *
  14915. * @type {Object<String,number>|undefined}
  14916. * @default undefined
  14917. */
  14918. this.morphTargetDictionary = undefined;
  14919. /**
  14920. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  14921. * is applied. This member is `undefined` by default and only set when morph targets are
  14922. * detected in the geometry.
  14923. *
  14924. * @type {Array<number>|undefined}
  14925. * @default undefined
  14926. */
  14927. this.morphTargetInfluences = undefined;
  14928. this.updateMorphTargets();
  14929. }
  14930. copy( source, recursive ) {
  14931. super.copy( source, recursive );
  14932. if ( source.morphTargetInfluences !== undefined ) {
  14933. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  14934. }
  14935. if ( source.morphTargetDictionary !== undefined ) {
  14936. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  14937. }
  14938. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  14939. this.geometry = source.geometry;
  14940. return this;
  14941. }
  14942. /**
  14943. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  14944. * to make sure existing morph targets can influence this 3D object.
  14945. */
  14946. updateMorphTargets() {
  14947. const geometry = this.geometry;
  14948. const morphAttributes = geometry.morphAttributes;
  14949. const keys = Object.keys( morphAttributes );
  14950. if ( keys.length > 0 ) {
  14951. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  14952. if ( morphAttribute !== undefined ) {
  14953. this.morphTargetInfluences = [];
  14954. this.morphTargetDictionary = {};
  14955. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  14956. const name = morphAttribute[ m ].name || String( m );
  14957. this.morphTargetInfluences.push( 0 );
  14958. this.morphTargetDictionary[ name ] = m;
  14959. }
  14960. }
  14961. }
  14962. }
  14963. /**
  14964. * Returns the local-space position of the vertex at the given index, taking into
  14965. * account the current animation state of both morph targets and skinning.
  14966. *
  14967. * @param {number} index - The vertex index.
  14968. * @param {Vector3} target - The target object that is used to store the method's result.
  14969. * @return {Vector3} The vertex position in local space.
  14970. */
  14971. getVertexPosition( index, target ) {
  14972. const geometry = this.geometry;
  14973. const position = geometry.attributes.position;
  14974. const morphPosition = geometry.morphAttributes.position;
  14975. const morphTargetsRelative = geometry.morphTargetsRelative;
  14976. target.fromBufferAttribute( position, index );
  14977. const morphInfluences = this.morphTargetInfluences;
  14978. if ( morphPosition && morphInfluences ) {
  14979. _morphA.set( 0, 0, 0 );
  14980. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  14981. const influence = morphInfluences[ i ];
  14982. const morphAttribute = morphPosition[ i ];
  14983. if ( influence === 0 ) continue;
  14984. _tempA.fromBufferAttribute( morphAttribute, index );
  14985. if ( morphTargetsRelative ) {
  14986. _morphA.addScaledVector( _tempA, influence );
  14987. } else {
  14988. _morphA.addScaledVector( _tempA.sub( target ), influence );
  14989. }
  14990. }
  14991. target.add( _morphA );
  14992. }
  14993. return target;
  14994. }
  14995. /**
  14996. * Computes intersection points between a casted ray and this line.
  14997. *
  14998. * @param {Raycaster} raycaster - The raycaster.
  14999. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15000. */
  15001. raycast( raycaster, intersects ) {
  15002. const geometry = this.geometry;
  15003. const material = this.material;
  15004. const matrixWorld = this.matrixWorld;
  15005. if ( material === undefined ) return;
  15006. // test with bounding sphere in world space
  15007. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15008. _sphere$6.copy( geometry.boundingSphere );
  15009. _sphere$6.applyMatrix4( matrixWorld );
  15010. // check distance from ray origin to bounding sphere
  15011. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15012. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15013. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15014. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15015. }
  15016. // convert ray to local space of mesh
  15017. _inverseMatrix$3.copy( matrixWorld ).invert();
  15018. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15019. // test with bounding box in local space
  15020. if ( geometry.boundingBox !== null ) {
  15021. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15022. }
  15023. // test for intersections with geometry
  15024. this._computeIntersections( raycaster, intersects, _ray$3 );
  15025. }
  15026. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15027. let intersection;
  15028. const geometry = this.geometry;
  15029. const material = this.material;
  15030. const index = geometry.index;
  15031. const position = geometry.attributes.position;
  15032. const uv = geometry.attributes.uv;
  15033. const uv1 = geometry.attributes.uv1;
  15034. const normal = geometry.attributes.normal;
  15035. const groups = geometry.groups;
  15036. const drawRange = geometry.drawRange;
  15037. if ( index !== null ) {
  15038. // indexed buffer geometry
  15039. if ( Array.isArray( material ) ) {
  15040. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15041. const group = groups[ i ];
  15042. const groupMaterial = material[ group.materialIndex ];
  15043. const start = Math.max( group.start, drawRange.start );
  15044. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15045. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15046. const a = index.getX( j );
  15047. const b = index.getX( j + 1 );
  15048. const c = index.getX( j + 2 );
  15049. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15050. if ( intersection ) {
  15051. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15052. intersection.face.materialIndex = group.materialIndex;
  15053. intersects.push( intersection );
  15054. }
  15055. }
  15056. }
  15057. } else {
  15058. const start = Math.max( 0, drawRange.start );
  15059. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15060. for ( let i = start, il = end; i < il; i += 3 ) {
  15061. const a = index.getX( i );
  15062. const b = index.getX( i + 1 );
  15063. const c = index.getX( i + 2 );
  15064. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15065. if ( intersection ) {
  15066. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15067. intersects.push( intersection );
  15068. }
  15069. }
  15070. }
  15071. } else if ( position !== undefined ) {
  15072. // non-indexed buffer geometry
  15073. if ( Array.isArray( material ) ) {
  15074. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15075. const group = groups[ i ];
  15076. const groupMaterial = material[ group.materialIndex ];
  15077. const start = Math.max( group.start, drawRange.start );
  15078. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15079. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15080. const a = j;
  15081. const b = j + 1;
  15082. const c = j + 2;
  15083. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15084. if ( intersection ) {
  15085. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15086. intersection.face.materialIndex = group.materialIndex;
  15087. intersects.push( intersection );
  15088. }
  15089. }
  15090. }
  15091. } else {
  15092. const start = Math.max( 0, drawRange.start );
  15093. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15094. for ( let i = start, il = end; i < il; i += 3 ) {
  15095. const a = i;
  15096. const b = i + 1;
  15097. const c = i + 2;
  15098. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15099. if ( intersection ) {
  15100. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15101. intersects.push( intersection );
  15102. }
  15103. }
  15104. }
  15105. }
  15106. }
  15107. }
  15108. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15109. let intersect;
  15110. if ( material.side === BackSide ) {
  15111. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15112. } else {
  15113. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15114. }
  15115. if ( intersect === null ) return null;
  15116. _intersectionPointWorld.copy( point );
  15117. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15118. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15119. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15120. return {
  15121. distance: distance,
  15122. point: _intersectionPointWorld.clone(),
  15123. object: object
  15124. };
  15125. }
  15126. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15127. object.getVertexPosition( a, _vA$1 );
  15128. object.getVertexPosition( b, _vB$1 );
  15129. object.getVertexPosition( c, _vC$1 );
  15130. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15131. if ( intersection ) {
  15132. const barycoord = new Vector3();
  15133. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15134. if ( uv ) {
  15135. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15136. }
  15137. if ( uv1 ) {
  15138. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15139. }
  15140. if ( normal ) {
  15141. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15142. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15143. intersection.normal.multiplyScalar( - 1 );
  15144. }
  15145. }
  15146. const face = {
  15147. a: a,
  15148. b: b,
  15149. c: c,
  15150. normal: new Vector3(),
  15151. materialIndex: 0
  15152. };
  15153. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15154. intersection.face = face;
  15155. intersection.barycoord = barycoord;
  15156. }
  15157. return intersection;
  15158. }
  15159. /**
  15160. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15161. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15162. * of the axes.
  15163. *
  15164. * ```js
  15165. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15166. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15167. * const cube = new THREE.Mesh( geometry, material );
  15168. * scene.add( cube );
  15169. * ```
  15170. *
  15171. * @augments BufferGeometry
  15172. */
  15173. class BoxGeometry extends BufferGeometry {
  15174. /**
  15175. * Constructs a new box geometry.
  15176. *
  15177. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15178. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15179. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15180. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15181. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15182. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15183. */
  15184. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15185. super();
  15186. this.type = 'BoxGeometry';
  15187. /**
  15188. * Holds the constructor parameters that have been
  15189. * used to generate the geometry. Any modification
  15190. * after instantiation does not change the geometry.
  15191. *
  15192. * @type {Object}
  15193. */
  15194. this.parameters = {
  15195. width: width,
  15196. height: height,
  15197. depth: depth,
  15198. widthSegments: widthSegments,
  15199. heightSegments: heightSegments,
  15200. depthSegments: depthSegments
  15201. };
  15202. const scope = this;
  15203. // segments
  15204. widthSegments = Math.floor( widthSegments );
  15205. heightSegments = Math.floor( heightSegments );
  15206. depthSegments = Math.floor( depthSegments );
  15207. // buffers
  15208. const indices = [];
  15209. const vertices = [];
  15210. const normals = [];
  15211. const uvs = [];
  15212. // helper variables
  15213. let numberOfVertices = 0;
  15214. let groupStart = 0;
  15215. // build each side of the box geometry
  15216. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15217. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15218. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15219. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15220. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15221. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15222. // build geometry
  15223. this.setIndex( indices );
  15224. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15225. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15226. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15227. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15228. const segmentWidth = width / gridX;
  15229. const segmentHeight = height / gridY;
  15230. const widthHalf = width / 2;
  15231. const heightHalf = height / 2;
  15232. const depthHalf = depth / 2;
  15233. const gridX1 = gridX + 1;
  15234. const gridY1 = gridY + 1;
  15235. let vertexCounter = 0;
  15236. let groupCount = 0;
  15237. const vector = new Vector3();
  15238. // generate vertices, normals and uvs
  15239. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15240. const y = iy * segmentHeight - heightHalf;
  15241. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15242. const x = ix * segmentWidth - widthHalf;
  15243. // set values to correct vector component
  15244. vector[ u ] = x * udir;
  15245. vector[ v ] = y * vdir;
  15246. vector[ w ] = depthHalf;
  15247. // now apply vector to vertex buffer
  15248. vertices.push( vector.x, vector.y, vector.z );
  15249. // set values to correct vector component
  15250. vector[ u ] = 0;
  15251. vector[ v ] = 0;
  15252. vector[ w ] = depth > 0 ? 1 : - 1;
  15253. // now apply vector to normal buffer
  15254. normals.push( vector.x, vector.y, vector.z );
  15255. // uvs
  15256. uvs.push( ix / gridX );
  15257. uvs.push( 1 - ( iy / gridY ) );
  15258. // counters
  15259. vertexCounter += 1;
  15260. }
  15261. }
  15262. // indices
  15263. // 1. you need three indices to draw a single face
  15264. // 2. a single segment consists of two faces
  15265. // 3. so we need to generate six (2*3) indices per segment
  15266. for ( let iy = 0; iy < gridY; iy ++ ) {
  15267. for ( let ix = 0; ix < gridX; ix ++ ) {
  15268. const a = numberOfVertices + ix + gridX1 * iy;
  15269. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15270. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15271. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15272. // faces
  15273. indices.push( a, b, d );
  15274. indices.push( b, c, d );
  15275. // increase counter
  15276. groupCount += 6;
  15277. }
  15278. }
  15279. // add a group to the geometry. this will ensure multi material support
  15280. scope.addGroup( groupStart, groupCount, materialIndex );
  15281. // calculate new start value for groups
  15282. groupStart += groupCount;
  15283. // update total number of vertices
  15284. numberOfVertices += vertexCounter;
  15285. }
  15286. }
  15287. copy( source ) {
  15288. super.copy( source );
  15289. this.parameters = Object.assign( {}, source.parameters );
  15290. return this;
  15291. }
  15292. /**
  15293. * Factory method for creating an instance of this class from the given
  15294. * JSON object.
  15295. *
  15296. * @param {Object} data - A JSON object representing the serialized geometry.
  15297. * @return {BoxGeometry} A new instance.
  15298. */
  15299. static fromJSON( data ) {
  15300. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15301. }
  15302. }
  15303. // Uniform Utilities
  15304. function cloneUniforms( src ) {
  15305. const dst = {};
  15306. for ( const u in src ) {
  15307. dst[ u ] = {};
  15308. for ( const p in src[ u ] ) {
  15309. const property = src[ u ][ p ];
  15310. if ( property && ( property.isColor ||
  15311. property.isMatrix3 || property.isMatrix4 ||
  15312. property.isVector2 || property.isVector3 || property.isVector4 ||
  15313. property.isTexture || property.isQuaternion ) ) {
  15314. if ( property.isRenderTargetTexture ) {
  15315. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15316. dst[ u ][ p ] = null;
  15317. } else {
  15318. dst[ u ][ p ] = property.clone();
  15319. }
  15320. } else if ( Array.isArray( property ) ) {
  15321. dst[ u ][ p ] = property.slice();
  15322. } else {
  15323. dst[ u ][ p ] = property;
  15324. }
  15325. }
  15326. }
  15327. return dst;
  15328. }
  15329. function mergeUniforms( uniforms ) {
  15330. const merged = {};
  15331. for ( let u = 0; u < uniforms.length; u ++ ) {
  15332. const tmp = cloneUniforms( uniforms[ u ] );
  15333. for ( const p in tmp ) {
  15334. merged[ p ] = tmp[ p ];
  15335. }
  15336. }
  15337. return merged;
  15338. }
  15339. function cloneUniformsGroups( src ) {
  15340. const dst = [];
  15341. for ( let u = 0; u < src.length; u ++ ) {
  15342. dst.push( src[ u ].clone() );
  15343. }
  15344. return dst;
  15345. }
  15346. function getUnlitUniformColorSpace( renderer ) {
  15347. const currentRenderTarget = renderer.getRenderTarget();
  15348. if ( currentRenderTarget === null ) {
  15349. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15350. return renderer.outputColorSpace;
  15351. }
  15352. // https://github.com/mrdoob/three.js/issues/27868
  15353. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15354. return currentRenderTarget.texture.colorSpace;
  15355. }
  15356. return ColorManagement.workingColorSpace;
  15357. }
  15358. // Legacy
  15359. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15360. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15361. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15362. /**
  15363. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15364. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15365. * effect not included with any of the built-in materials.
  15366. *
  15367. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15368. *
  15369. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15370. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15371. * you don't want that, use {@link RawShaderMaterial} instead.
  15372. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15373. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15374. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15375. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15376. * - The loop variable has to be *i*.
  15377. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15378. * value of *i* for the given iteration and can be used in preprocessor
  15379. * statements.
  15380. *
  15381. * ```js
  15382. * const material = new THREE.ShaderMaterial( {
  15383. * uniforms: {
  15384. * time: { value: 1.0 },
  15385. * resolution: { value: new THREE.Vector2() }
  15386. * },
  15387. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15388. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15389. * } );
  15390. * ```
  15391. *
  15392. * @augments Material
  15393. */
  15394. class ShaderMaterial extends Material {
  15395. /**
  15396. * Constructs a new shader material.
  15397. *
  15398. * @param {Object} [parameters] - An object with one or more properties
  15399. * defining the material's appearance. Any property of the material
  15400. * (including any property from inherited materials) can be passed
  15401. * in here. Color values can be passed any type of value accepted
  15402. * by {@link Color#set}.
  15403. */
  15404. constructor( parameters ) {
  15405. super();
  15406. /**
  15407. * This flag can be used for type testing.
  15408. *
  15409. * @type {boolean}
  15410. * @readonly
  15411. * @default true
  15412. */
  15413. this.isShaderMaterial = true;
  15414. this.type = 'ShaderMaterial';
  15415. /**
  15416. * Defines custom constants using `#define` directives within the GLSL code
  15417. * for both the vertex shader and the fragment shader; each key/value pair
  15418. * yields another directive.
  15419. * ```js
  15420. * defines: {
  15421. * FOO: 15,
  15422. * BAR: true
  15423. * }
  15424. * ```
  15425. * Yields the lines:
  15426. * ```
  15427. * #define FOO 15
  15428. * #define BAR true
  15429. * ```
  15430. *
  15431. * @type {Object}
  15432. */
  15433. this.defines = {};
  15434. /**
  15435. * An object of the form:
  15436. * ```js
  15437. * {
  15438. * "uniform1": { value: 1.0 },
  15439. * "uniform2": { value: 2 }
  15440. * }
  15441. * ```
  15442. * specifying the uniforms to be passed to the shader code; keys are uniform
  15443. * names, values are definitions of the form
  15444. * ```
  15445. * {
  15446. * value: 1.0
  15447. * }
  15448. * ```
  15449. * where `value` is the value of the uniform. Names must match the name of
  15450. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15451. * on every frame, so updating the value of the uniform will immediately
  15452. * update the value available to the GLSL code.
  15453. *
  15454. * @type {Object}
  15455. */
  15456. this.uniforms = {};
  15457. /**
  15458. * An array holding uniforms groups for configuring UBOs.
  15459. *
  15460. * @type {Array<UniformsGroup>}
  15461. */
  15462. this.uniformsGroups = [];
  15463. /**
  15464. * Vertex shader GLSL code. This is the actual code for the shader.
  15465. *
  15466. * @type {string}
  15467. */
  15468. this.vertexShader = default_vertex;
  15469. /**
  15470. * Fragment shader GLSL code. This is the actual code for the shader.
  15471. *
  15472. * @type {string}
  15473. */
  15474. this.fragmentShader = default_fragment;
  15475. /**
  15476. * Controls line thickness or lines.
  15477. *
  15478. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15479. * width of one pixel.
  15480. *
  15481. * @type {number}
  15482. * @default 1
  15483. */
  15484. this.linewidth = 1;
  15485. /**
  15486. * Renders the geometry as a wireframe.
  15487. *
  15488. * @type {boolean}
  15489. * @default false
  15490. */
  15491. this.wireframe = false;
  15492. /**
  15493. * Controls the thickness of the wireframe.
  15494. *
  15495. * WebGL and WebGPU ignore this property and always render
  15496. * 1 pixel wide lines.
  15497. *
  15498. * @type {number}
  15499. * @default 1
  15500. */
  15501. this.wireframeLinewidth = 1;
  15502. /**
  15503. * Define whether the material color is affected by global fog settings; `true`
  15504. * to pass fog uniforms to the shader.
  15505. *
  15506. * @type {boolean}
  15507. * @default false
  15508. */
  15509. this.fog = false;
  15510. /**
  15511. * Defines whether this material uses lighting; `true` to pass uniform data
  15512. * related to lighting to this shader.
  15513. *
  15514. * @type {boolean}
  15515. * @default false
  15516. */
  15517. this.lights = false;
  15518. /**
  15519. * Defines whether this material supports clipping; `true` to let the renderer
  15520. * pass the clippingPlanes uniform.
  15521. *
  15522. * @type {boolean}
  15523. * @default false
  15524. */
  15525. this.clipping = false;
  15526. /**
  15527. * Overwritten and set to `true` by default.
  15528. *
  15529. * @type {boolean}
  15530. * @default true
  15531. */
  15532. this.forceSinglePass = true;
  15533. /**
  15534. * This object allows to enable certain WebGL 2 extensions.
  15535. *
  15536. * - clipCullDistance: set to `true` to use vertex shader clipping
  15537. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15538. *
  15539. * @type {{clipCullDistance:false,multiDraw:false}}
  15540. */
  15541. this.extensions = {
  15542. clipCullDistance: false, // set to use vertex shader clipping
  15543. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15544. };
  15545. /**
  15546. * When the rendered geometry doesn't include these attributes but the
  15547. * material does, these default values will be passed to the shaders. This
  15548. * avoids errors when buffer data is missing.
  15549. *
  15550. * - color: [ 1, 1, 1 ]
  15551. * - uv: [ 0, 0 ]
  15552. * - uv1: [ 0, 0 ]
  15553. *
  15554. * @type {Object}
  15555. */
  15556. this.defaultAttributeValues = {
  15557. 'color': [ 1, 1, 1 ],
  15558. 'uv': [ 0, 0 ],
  15559. 'uv1': [ 0, 0 ]
  15560. };
  15561. /**
  15562. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15563. * to bind a generic vertex index to an attribute variable.
  15564. *
  15565. * @type {string|undefined}
  15566. * @default undefined
  15567. */
  15568. this.index0AttributeName = undefined;
  15569. /**
  15570. * Can be used to force a uniform update while changing uniforms in
  15571. * {@link Object3D#onBeforeRender}.
  15572. *
  15573. * @type {boolean}
  15574. * @default false
  15575. */
  15576. this.uniformsNeedUpdate = false;
  15577. /**
  15578. * Defines the GLSL version of custom shader code.
  15579. *
  15580. * @type {?(GLSL1|GLSL3)}
  15581. * @default null
  15582. */
  15583. this.glslVersion = null;
  15584. if ( parameters !== undefined ) {
  15585. this.setValues( parameters );
  15586. }
  15587. }
  15588. copy( source ) {
  15589. super.copy( source );
  15590. this.fragmentShader = source.fragmentShader;
  15591. this.vertexShader = source.vertexShader;
  15592. this.uniforms = cloneUniforms( source.uniforms );
  15593. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15594. this.defines = Object.assign( {}, source.defines );
  15595. this.wireframe = source.wireframe;
  15596. this.wireframeLinewidth = source.wireframeLinewidth;
  15597. this.fog = source.fog;
  15598. this.lights = source.lights;
  15599. this.clipping = source.clipping;
  15600. this.extensions = Object.assign( {}, source.extensions );
  15601. this.glslVersion = source.glslVersion;
  15602. return this;
  15603. }
  15604. toJSON( meta ) {
  15605. const data = super.toJSON( meta );
  15606. data.glslVersion = this.glslVersion;
  15607. data.uniforms = {};
  15608. for ( const name in this.uniforms ) {
  15609. const uniform = this.uniforms[ name ];
  15610. const value = uniform.value;
  15611. if ( value && value.isTexture ) {
  15612. data.uniforms[ name ] = {
  15613. type: 't',
  15614. value: value.toJSON( meta ).uuid
  15615. };
  15616. } else if ( value && value.isColor ) {
  15617. data.uniforms[ name ] = {
  15618. type: 'c',
  15619. value: value.getHex()
  15620. };
  15621. } else if ( value && value.isVector2 ) {
  15622. data.uniforms[ name ] = {
  15623. type: 'v2',
  15624. value: value.toArray()
  15625. };
  15626. } else if ( value && value.isVector3 ) {
  15627. data.uniforms[ name ] = {
  15628. type: 'v3',
  15629. value: value.toArray()
  15630. };
  15631. } else if ( value && value.isVector4 ) {
  15632. data.uniforms[ name ] = {
  15633. type: 'v4',
  15634. value: value.toArray()
  15635. };
  15636. } else if ( value && value.isMatrix3 ) {
  15637. data.uniforms[ name ] = {
  15638. type: 'm3',
  15639. value: value.toArray()
  15640. };
  15641. } else if ( value && value.isMatrix4 ) {
  15642. data.uniforms[ name ] = {
  15643. type: 'm4',
  15644. value: value.toArray()
  15645. };
  15646. } else {
  15647. data.uniforms[ name ] = {
  15648. value: value
  15649. };
  15650. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15651. }
  15652. }
  15653. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15654. data.vertexShader = this.vertexShader;
  15655. data.fragmentShader = this.fragmentShader;
  15656. data.lights = this.lights;
  15657. data.clipping = this.clipping;
  15658. const extensions = {};
  15659. for ( const key in this.extensions ) {
  15660. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15661. }
  15662. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15663. return data;
  15664. }
  15665. }
  15666. /**
  15667. * Abstract base class for cameras. This class should always be inherited
  15668. * when you build a new camera.
  15669. *
  15670. * @abstract
  15671. * @augments Object3D
  15672. */
  15673. class Camera extends Object3D {
  15674. /**
  15675. * Constructs a new camera.
  15676. */
  15677. constructor() {
  15678. super();
  15679. /**
  15680. * This flag can be used for type testing.
  15681. *
  15682. * @type {boolean}
  15683. * @readonly
  15684. * @default true
  15685. */
  15686. this.isCamera = true;
  15687. this.type = 'Camera';
  15688. /**
  15689. * The inverse of the camera's world matrix.
  15690. *
  15691. * @type {Matrix4}
  15692. */
  15693. this.matrixWorldInverse = new Matrix4();
  15694. /**
  15695. * The camera's projection matrix.
  15696. *
  15697. * @type {Matrix4}
  15698. */
  15699. this.projectionMatrix = new Matrix4();
  15700. /**
  15701. * The inverse of the camera's projection matrix.
  15702. *
  15703. * @type {Matrix4}
  15704. */
  15705. this.projectionMatrixInverse = new Matrix4();
  15706. /**
  15707. * The coordinate system in which the camera is used.
  15708. *
  15709. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15710. */
  15711. this.coordinateSystem = WebGLCoordinateSystem;
  15712. }
  15713. copy( source, recursive ) {
  15714. super.copy( source, recursive );
  15715. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15716. this.projectionMatrix.copy( source.projectionMatrix );
  15717. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15718. this.coordinateSystem = source.coordinateSystem;
  15719. return this;
  15720. }
  15721. /**
  15722. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15723. *
  15724. * This method is overwritten since cameras have a different forward vector compared to other
  15725. * 3D objects. A camera looks down its local, negative z-axis by default.
  15726. *
  15727. * @param {Vector3} target - The target vector the result is stored to.
  15728. * @return {Vector3} The 3D object's direction in world space.
  15729. */
  15730. getWorldDirection( target ) {
  15731. return super.getWorldDirection( target ).negate();
  15732. }
  15733. updateMatrixWorld( force ) {
  15734. super.updateMatrixWorld( force );
  15735. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15736. }
  15737. updateWorldMatrix( updateParents, updateChildren ) {
  15738. super.updateWorldMatrix( updateParents, updateChildren );
  15739. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15740. }
  15741. clone() {
  15742. return new this.constructor().copy( this );
  15743. }
  15744. }
  15745. const _v3$1 = /*@__PURE__*/ new Vector3();
  15746. const _minTarget = /*@__PURE__*/ new Vector2();
  15747. const _maxTarget = /*@__PURE__*/ new Vector2();
  15748. /**
  15749. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15750. *
  15751. * This projection mode is designed to mimic the way the human eye sees. It
  15752. * is the most common projection mode used for rendering a 3D scene.
  15753. *
  15754. * ```js
  15755. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15756. * scene.add( camera );
  15757. * ```
  15758. *
  15759. * @augments Camera
  15760. */
  15761. class PerspectiveCamera extends Camera {
  15762. /**
  15763. * Constructs a new perspective camera.
  15764. *
  15765. * @param {number} [fov=50] - The vertical field of view.
  15766. * @param {number} [aspect=1] - The aspect ratio.
  15767. * @param {number} [near=0.1] - The camera's near plane.
  15768. * @param {number} [far=2000] - The camera's far plane.
  15769. */
  15770. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15771. super();
  15772. /**
  15773. * This flag can be used for type testing.
  15774. *
  15775. * @type {boolean}
  15776. * @readonly
  15777. * @default true
  15778. */
  15779. this.isPerspectiveCamera = true;
  15780. this.type = 'PerspectiveCamera';
  15781. /**
  15782. * The vertical field of view, from bottom to top of view,
  15783. * in degrees.
  15784. *
  15785. * @type {number}
  15786. * @default 50
  15787. */
  15788. this.fov = fov;
  15789. /**
  15790. * The zoom factor of the camera.
  15791. *
  15792. * @type {number}
  15793. * @default 1
  15794. */
  15795. this.zoom = 1;
  15796. /**
  15797. * The camera's near plane. The valid range is greater than `0`
  15798. * and less than the current value of {@link PerspectiveCamera#far}.
  15799. *
  15800. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  15801. * valid value for a perspective camera's near plane.
  15802. *
  15803. * @type {number}
  15804. * @default 0.1
  15805. */
  15806. this.near = near;
  15807. /**
  15808. * The camera's far plane. Must be greater than the
  15809. * current value of {@link PerspectiveCamera#near}.
  15810. *
  15811. * @type {number}
  15812. * @default 2000
  15813. */
  15814. this.far = far;
  15815. /**
  15816. * Object distance used for stereoscopy and depth-of-field effects. This
  15817. * parameter does not influence the projection matrix unless a
  15818. * {@link StereoCamera} is being used.
  15819. *
  15820. * @type {number}
  15821. * @default 10
  15822. */
  15823. this.focus = 10;
  15824. /**
  15825. * The aspect ratio, usually the canvas width / canvas height.
  15826. *
  15827. * @type {number}
  15828. * @default 1
  15829. */
  15830. this.aspect = aspect;
  15831. /**
  15832. * Represents the frustum window specification. This property should not be edited
  15833. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  15834. *
  15835. * @type {?Object}
  15836. * @default null
  15837. */
  15838. this.view = null;
  15839. /**
  15840. * Film size used for the larger axis. Default is `35` (millimeters). This
  15841. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  15842. * is set to a nonzero value.
  15843. *
  15844. * @type {number}
  15845. * @default 35
  15846. */
  15847. this.filmGauge = 35;
  15848. /**
  15849. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  15850. *
  15851. * @type {number}
  15852. * @default 0
  15853. */
  15854. this.filmOffset = 0;
  15855. this.updateProjectionMatrix();
  15856. }
  15857. copy( source, recursive ) {
  15858. super.copy( source, recursive );
  15859. this.fov = source.fov;
  15860. this.zoom = source.zoom;
  15861. this.near = source.near;
  15862. this.far = source.far;
  15863. this.focus = source.focus;
  15864. this.aspect = source.aspect;
  15865. this.view = source.view === null ? null : Object.assign( {}, source.view );
  15866. this.filmGauge = source.filmGauge;
  15867. this.filmOffset = source.filmOffset;
  15868. return this;
  15869. }
  15870. /**
  15871. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  15872. *
  15873. * The default film gauge is 35, so that the focal length can be specified for
  15874. * a 35mm (full frame) camera.
  15875. *
  15876. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  15877. */
  15878. setFocalLength( focalLength ) {
  15879. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  15880. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  15881. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  15882. this.updateProjectionMatrix();
  15883. }
  15884. /**
  15885. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  15886. * {@link PerspectiveCamera#filmGauge}.
  15887. *
  15888. * @return {number} The computed focal length.
  15889. */
  15890. getFocalLength() {
  15891. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  15892. return 0.5 * this.getFilmHeight() / vExtentSlope;
  15893. }
  15894. /**
  15895. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  15896. *
  15897. * @return {number} The effective FOV.
  15898. */
  15899. getEffectiveFOV() {
  15900. return RAD2DEG * 2 * Math.atan(
  15901. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  15902. }
  15903. /**
  15904. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  15905. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  15906. *
  15907. * @return {number} The film width.
  15908. */
  15909. getFilmWidth() {
  15910. // film not completely covered in portrait format (aspect < 1)
  15911. return this.filmGauge * Math.min( this.aspect, 1 );
  15912. }
  15913. /**
  15914. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  15915. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  15916. *
  15917. * @return {number} The film width.
  15918. */
  15919. getFilmHeight() {
  15920. // film not completely covered in landscape format (aspect > 1)
  15921. return this.filmGauge / Math.max( this.aspect, 1 );
  15922. }
  15923. /**
  15924. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  15925. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  15926. *
  15927. * @param {number} distance - The viewing distance.
  15928. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  15929. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  15930. */
  15931. getViewBounds( distance, minTarget, maxTarget ) {
  15932. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  15933. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  15934. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  15935. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  15936. }
  15937. /**
  15938. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  15939. *
  15940. * @param {number} distance - The viewing distance.
  15941. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  15942. * @returns {Vector2} The view size.
  15943. */
  15944. getViewSize( distance, target ) {
  15945. this.getViewBounds( distance, _minTarget, _maxTarget );
  15946. return target.subVectors( _maxTarget, _minTarget );
  15947. }
  15948. /**
  15949. * Sets an offset in a larger frustum. This is useful for multi-window or
  15950. * multi-monitor/multi-machine setups.
  15951. *
  15952. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  15953. * the monitors are in grid like this
  15954. *```
  15955. * +---+---+---+
  15956. * | A | B | C |
  15957. * +---+---+---+
  15958. * | D | E | F |
  15959. * +---+---+---+
  15960. *```
  15961. * then for each monitor you would call it like this:
  15962. *```js
  15963. * const w = 1920;
  15964. * const h = 1080;
  15965. * const fullWidth = w * 3;
  15966. * const fullHeight = h * 2;
  15967. *
  15968. * // --A--
  15969. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  15970. * // --B--
  15971. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  15972. * // --C--
  15973. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  15974. * // --D--
  15975. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  15976. * // --E--
  15977. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  15978. * // --F--
  15979. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  15980. * ```
  15981. *
  15982. * Note there is no reason monitors have to be the same size or in a grid.
  15983. *
  15984. * @param {number} fullWidth - The full width of multiview setup.
  15985. * @param {number} fullHeight - The full height of multiview setup.
  15986. * @param {number} x - The horizontal offset of the subcamera.
  15987. * @param {number} y - The vertical offset of the subcamera.
  15988. * @param {number} width - The width of subcamera.
  15989. * @param {number} height - The height of subcamera.
  15990. */
  15991. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  15992. this.aspect = fullWidth / fullHeight;
  15993. if ( this.view === null ) {
  15994. this.view = {
  15995. enabled: true,
  15996. fullWidth: 1,
  15997. fullHeight: 1,
  15998. offsetX: 0,
  15999. offsetY: 0,
  16000. width: 1,
  16001. height: 1
  16002. };
  16003. }
  16004. this.view.enabled = true;
  16005. this.view.fullWidth = fullWidth;
  16006. this.view.fullHeight = fullHeight;
  16007. this.view.offsetX = x;
  16008. this.view.offsetY = y;
  16009. this.view.width = width;
  16010. this.view.height = height;
  16011. this.updateProjectionMatrix();
  16012. }
  16013. /**
  16014. * Removes the view offset from the projection matrix.
  16015. */
  16016. clearViewOffset() {
  16017. if ( this.view !== null ) {
  16018. this.view.enabled = false;
  16019. }
  16020. this.updateProjectionMatrix();
  16021. }
  16022. /**
  16023. * Updates the camera's projection matrix. Must be called after any change of
  16024. * camera properties.
  16025. */
  16026. updateProjectionMatrix() {
  16027. const near = this.near;
  16028. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16029. let height = 2 * top;
  16030. let width = this.aspect * height;
  16031. let left = - 0.5 * width;
  16032. const view = this.view;
  16033. if ( this.view !== null && this.view.enabled ) {
  16034. const fullWidth = view.fullWidth,
  16035. fullHeight = view.fullHeight;
  16036. left += view.offsetX * width / fullWidth;
  16037. top -= view.offsetY * height / fullHeight;
  16038. width *= view.width / fullWidth;
  16039. height *= view.height / fullHeight;
  16040. }
  16041. const skew = this.filmOffset;
  16042. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16043. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  16044. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16045. }
  16046. toJSON( meta ) {
  16047. const data = super.toJSON( meta );
  16048. data.object.fov = this.fov;
  16049. data.object.zoom = this.zoom;
  16050. data.object.near = this.near;
  16051. data.object.far = this.far;
  16052. data.object.focus = this.focus;
  16053. data.object.aspect = this.aspect;
  16054. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16055. data.object.filmGauge = this.filmGauge;
  16056. data.object.filmOffset = this.filmOffset;
  16057. return data;
  16058. }
  16059. }
  16060. const fov = - 90; // negative fov is not an error
  16061. const aspect = 1;
  16062. /**
  16063. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16064. * cube render target. The render target can then be used as an environment map for rendering
  16065. * realtime reflections in your scene.
  16066. *
  16067. * ```js
  16068. * // Create cube render target
  16069. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16070. *
  16071. * // Create cube camera
  16072. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16073. * scene.add( cubeCamera );
  16074. *
  16075. * // Create car
  16076. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16077. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16078. * scene.add( car );
  16079. *
  16080. * // Update the render target cube
  16081. * car.visible = false;
  16082. * cubeCamera.position.copy( car.position );
  16083. * cubeCamera.update( renderer, scene );
  16084. *
  16085. * // Render the scene
  16086. * car.visible = true;
  16087. * renderer.render( scene, camera );
  16088. * ```
  16089. *
  16090. * @augments Object3D
  16091. */
  16092. class CubeCamera extends Object3D {
  16093. /**
  16094. * Constructs a new cube camera.
  16095. *
  16096. * @param {number} near - The camera's near plane.
  16097. * @param {number} far - The camera's far plane.
  16098. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16099. */
  16100. constructor( near, far, renderTarget ) {
  16101. super();
  16102. this.type = 'CubeCamera';
  16103. /**
  16104. * A reference to the cube render target.
  16105. *
  16106. * @type {WebGLCubeRenderTarget}
  16107. */
  16108. this.renderTarget = renderTarget;
  16109. /**
  16110. * The current active coordinate system.
  16111. *
  16112. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16113. * @default null
  16114. */
  16115. this.coordinateSystem = null;
  16116. /**
  16117. * The current active mipmap level
  16118. *
  16119. * @type {number}
  16120. * @default 0
  16121. */
  16122. this.activeMipmapLevel = 0;
  16123. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16124. cameraPX.layers = this.layers;
  16125. this.add( cameraPX );
  16126. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16127. cameraNX.layers = this.layers;
  16128. this.add( cameraNX );
  16129. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16130. cameraPY.layers = this.layers;
  16131. this.add( cameraPY );
  16132. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16133. cameraNY.layers = this.layers;
  16134. this.add( cameraNY );
  16135. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16136. cameraPZ.layers = this.layers;
  16137. this.add( cameraPZ );
  16138. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16139. cameraNZ.layers = this.layers;
  16140. this.add( cameraNZ );
  16141. }
  16142. /**
  16143. * Must be called when the coordinate system of the cube camera is changed.
  16144. */
  16145. updateCoordinateSystem() {
  16146. const coordinateSystem = this.coordinateSystem;
  16147. const cameras = this.children.concat();
  16148. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16149. for ( const camera of cameras ) this.remove( camera );
  16150. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16151. cameraPX.up.set( 0, 1, 0 );
  16152. cameraPX.lookAt( 1, 0, 0 );
  16153. cameraNX.up.set( 0, 1, 0 );
  16154. cameraNX.lookAt( - 1, 0, 0 );
  16155. cameraPY.up.set( 0, 0, - 1 );
  16156. cameraPY.lookAt( 0, 1, 0 );
  16157. cameraNY.up.set( 0, 0, 1 );
  16158. cameraNY.lookAt( 0, - 1, 0 );
  16159. cameraPZ.up.set( 0, 1, 0 );
  16160. cameraPZ.lookAt( 0, 0, 1 );
  16161. cameraNZ.up.set( 0, 1, 0 );
  16162. cameraNZ.lookAt( 0, 0, - 1 );
  16163. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16164. cameraPX.up.set( 0, - 1, 0 );
  16165. cameraPX.lookAt( - 1, 0, 0 );
  16166. cameraNX.up.set( 0, - 1, 0 );
  16167. cameraNX.lookAt( 1, 0, 0 );
  16168. cameraPY.up.set( 0, 0, 1 );
  16169. cameraPY.lookAt( 0, 1, 0 );
  16170. cameraNY.up.set( 0, 0, - 1 );
  16171. cameraNY.lookAt( 0, - 1, 0 );
  16172. cameraPZ.up.set( 0, - 1, 0 );
  16173. cameraPZ.lookAt( 0, 0, 1 );
  16174. cameraNZ.up.set( 0, - 1, 0 );
  16175. cameraNZ.lookAt( 0, 0, - 1 );
  16176. } else {
  16177. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16178. }
  16179. for ( const camera of cameras ) {
  16180. this.add( camera );
  16181. camera.updateMatrixWorld();
  16182. }
  16183. }
  16184. /**
  16185. * Calling this method will render the given scene with the given renderer
  16186. * into the cube render target of the camera.
  16187. *
  16188. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16189. * @param {Scene} scene - The scene to render.
  16190. */
  16191. update( renderer, scene ) {
  16192. if ( this.parent === null ) this.updateMatrixWorld();
  16193. const { renderTarget, activeMipmapLevel } = this;
  16194. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16195. this.coordinateSystem = renderer.coordinateSystem;
  16196. this.updateCoordinateSystem();
  16197. }
  16198. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16199. const currentRenderTarget = renderer.getRenderTarget();
  16200. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16201. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16202. const currentXrEnabled = renderer.xr.enabled;
  16203. renderer.xr.enabled = false;
  16204. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16205. renderTarget.texture.generateMipmaps = false;
  16206. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16207. renderer.render( scene, cameraPX );
  16208. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16209. renderer.render( scene, cameraNX );
  16210. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16211. renderer.render( scene, cameraPY );
  16212. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16213. renderer.render( scene, cameraNY );
  16214. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16215. renderer.render( scene, cameraPZ );
  16216. // mipmaps are generated during the last call of render()
  16217. // at this point, all sides of the cube render target are defined
  16218. renderTarget.texture.generateMipmaps = generateMipmaps;
  16219. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16220. renderer.render( scene, cameraNZ );
  16221. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16222. renderer.xr.enabled = currentXrEnabled;
  16223. renderTarget.texture.needsPMREMUpdate = true;
  16224. }
  16225. }
  16226. /**
  16227. * Creates a cube texture made up of six images.
  16228. *
  16229. * ```js
  16230. * const loader = new THREE.CubeTextureLoader();
  16231. * loader.setPath( 'textures/cube/pisa/' );
  16232. *
  16233. * const textureCube = loader.load( [
  16234. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16235. * ] );
  16236. *
  16237. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16238. * ```
  16239. *
  16240. * @augments Texture
  16241. */
  16242. class CubeTexture extends Texture {
  16243. /**
  16244. * Constructs a new cube texture.
  16245. *
  16246. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16247. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16248. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16249. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16250. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16251. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16252. * @param {number} [format=RGBAFormat] - The texture format.
  16253. * @param {number} [type=UnsignedByteType] - The texture type.
  16254. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16255. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16256. */
  16257. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16258. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16259. /**
  16260. * This flag can be used for type testing.
  16261. *
  16262. * @type {boolean}
  16263. * @readonly
  16264. * @default true
  16265. */
  16266. this.isCubeTexture = true;
  16267. /**
  16268. * If set to `true`, the texture is flipped along the vertical axis when
  16269. * uploaded to the GPU.
  16270. *
  16271. * Overwritten and set to `false` by default.
  16272. *
  16273. * @type {boolean}
  16274. * @default false
  16275. */
  16276. this.flipY = false;
  16277. }
  16278. /**
  16279. * Alias for {@link CubeTexture#image}.
  16280. *
  16281. * @type {Array<Image>}
  16282. */
  16283. get images() {
  16284. return this.image;
  16285. }
  16286. set images( value ) {
  16287. this.image = value;
  16288. }
  16289. }
  16290. /**
  16291. * A cube render target used in context of {@link WebGLRenderer}.
  16292. *
  16293. * @augments WebGLRenderTarget
  16294. */
  16295. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16296. /**
  16297. * Constructs a new cube render target.
  16298. *
  16299. * @param {number} [size=1] - The size of the render target.
  16300. * @param {RenderTarget~Options} [options] - The configuration object.
  16301. */
  16302. constructor( size = 1, options = {} ) {
  16303. super( size, size, options );
  16304. /**
  16305. * This flag can be used for type testing.
  16306. *
  16307. * @type {boolean}
  16308. * @readonly
  16309. * @default true
  16310. */
  16311. this.isWebGLCubeRenderTarget = true;
  16312. const image = { width: size, height: size, depth: 1 };
  16313. const images = [ image, image, image, image, image, image ];
  16314. /**
  16315. * Overwritten with a different texture type.
  16316. *
  16317. * @type {DataArrayTexture}
  16318. */
  16319. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  16320. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16321. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16322. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16323. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16324. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16325. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16326. this.texture.isRenderTargetTexture = true;
  16327. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  16328. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  16329. }
  16330. /**
  16331. * Converts the given equirectangular texture to a cube map.
  16332. *
  16333. * @param {WebGLRenderer} renderer - The renderer.
  16334. * @param {Texture} texture - The equirectangular texture.
  16335. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16336. */
  16337. fromEquirectangularTexture( renderer, texture ) {
  16338. this.texture.type = texture.type;
  16339. this.texture.colorSpace = texture.colorSpace;
  16340. this.texture.generateMipmaps = texture.generateMipmaps;
  16341. this.texture.minFilter = texture.minFilter;
  16342. this.texture.magFilter = texture.magFilter;
  16343. const shader = {
  16344. uniforms: {
  16345. tEquirect: { value: null },
  16346. },
  16347. vertexShader: /* glsl */`
  16348. varying vec3 vWorldDirection;
  16349. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16350. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16351. }
  16352. void main() {
  16353. vWorldDirection = transformDirection( position, modelMatrix );
  16354. #include <begin_vertex>
  16355. #include <project_vertex>
  16356. }
  16357. `,
  16358. fragmentShader: /* glsl */`
  16359. uniform sampler2D tEquirect;
  16360. varying vec3 vWorldDirection;
  16361. #include <common>
  16362. void main() {
  16363. vec3 direction = normalize( vWorldDirection );
  16364. vec2 sampleUV = equirectUv( direction );
  16365. gl_FragColor = texture2D( tEquirect, sampleUV );
  16366. }
  16367. `
  16368. };
  16369. const geometry = new BoxGeometry( 5, 5, 5 );
  16370. const material = new ShaderMaterial( {
  16371. name: 'CubemapFromEquirect',
  16372. uniforms: cloneUniforms( shader.uniforms ),
  16373. vertexShader: shader.vertexShader,
  16374. fragmentShader: shader.fragmentShader,
  16375. side: BackSide,
  16376. blending: NoBlending
  16377. } );
  16378. material.uniforms.tEquirect.value = texture;
  16379. const mesh = new Mesh( geometry, material );
  16380. const currentMinFilter = texture.minFilter;
  16381. // Avoid blurred poles
  16382. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16383. const camera = new CubeCamera( 1, 10, this );
  16384. camera.update( renderer, mesh );
  16385. texture.minFilter = currentMinFilter;
  16386. mesh.geometry.dispose();
  16387. mesh.material.dispose();
  16388. return this;
  16389. }
  16390. /**
  16391. * Clears this cube render target.
  16392. *
  16393. * @param {WebGLRenderer} renderer - The renderer.
  16394. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16395. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16396. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16397. */
  16398. clear( renderer, color = true, depth = true, stencil = true ) {
  16399. const currentRenderTarget = renderer.getRenderTarget();
  16400. for ( let i = 0; i < 6; i ++ ) {
  16401. renderer.setRenderTarget( this, i );
  16402. renderer.clear( color, depth, stencil );
  16403. }
  16404. renderer.setRenderTarget( currentRenderTarget );
  16405. }
  16406. }
  16407. /**
  16408. * This is almost identical to an {@link Object3D}. Its purpose is to
  16409. * make working with groups of objects syntactically clearer.
  16410. *
  16411. * ```js
  16412. * // Create a group and add the two cubes.
  16413. * // These cubes can now be rotated / scaled etc as a group.
  16414. * const group = new THREE.Group();
  16415. *
  16416. * group.add( meshA );
  16417. * group.add( meshB );
  16418. *
  16419. * scene.add( group );
  16420. * ```
  16421. *
  16422. * @augments Object3D
  16423. */
  16424. class Group extends Object3D {
  16425. constructor() {
  16426. super();
  16427. /**
  16428. * This flag can be used for type testing.
  16429. *
  16430. * @type {boolean}
  16431. * @readonly
  16432. * @default true
  16433. */
  16434. this.isGroup = true;
  16435. this.type = 'Group';
  16436. }
  16437. }
  16438. const _moveEvent = { type: 'move' };
  16439. /**
  16440. * Class for representing a XR controller with its
  16441. * different coordinate systems.
  16442. *
  16443. * @private
  16444. */
  16445. class WebXRController {
  16446. /**
  16447. * Constructs a new XR controller.
  16448. */
  16449. constructor() {
  16450. /**
  16451. * A group representing the target ray space
  16452. * of the XR controller.
  16453. *
  16454. * @private
  16455. * @type {?Group}
  16456. * @default null
  16457. */
  16458. this._targetRay = null;
  16459. /**
  16460. * A group representing the grip space
  16461. * of the XR controller.
  16462. *
  16463. * @private
  16464. * @type {?Group}
  16465. * @default null
  16466. */
  16467. this._grip = null;
  16468. /**
  16469. * A group representing the hand space
  16470. * of the XR controller.
  16471. *
  16472. * @private
  16473. * @type {?Group}
  16474. * @default null
  16475. */
  16476. this._hand = null;
  16477. }
  16478. /**
  16479. * Returns a group representing the hand space of the XR controller.
  16480. *
  16481. * @return {Group} A group representing the hand space of the XR controller.
  16482. */
  16483. getHandSpace() {
  16484. if ( this._hand === null ) {
  16485. this._hand = new Group();
  16486. this._hand.matrixAutoUpdate = false;
  16487. this._hand.visible = false;
  16488. this._hand.joints = {};
  16489. this._hand.inputState = { pinching: false };
  16490. }
  16491. return this._hand;
  16492. }
  16493. /**
  16494. * Returns a group representing the target ray space of the XR controller.
  16495. *
  16496. * @return {Group} A group representing the target ray space of the XR controller.
  16497. */
  16498. getTargetRaySpace() {
  16499. if ( this._targetRay === null ) {
  16500. this._targetRay = new Group();
  16501. this._targetRay.matrixAutoUpdate = false;
  16502. this._targetRay.visible = false;
  16503. this._targetRay.hasLinearVelocity = false;
  16504. this._targetRay.linearVelocity = new Vector3();
  16505. this._targetRay.hasAngularVelocity = false;
  16506. this._targetRay.angularVelocity = new Vector3();
  16507. }
  16508. return this._targetRay;
  16509. }
  16510. /**
  16511. * Returns a group representing the grip space of the XR controller.
  16512. *
  16513. * @return {Group} A group representing the grip space of the XR controller.
  16514. */
  16515. getGripSpace() {
  16516. if ( this._grip === null ) {
  16517. this._grip = new Group();
  16518. this._grip.matrixAutoUpdate = false;
  16519. this._grip.visible = false;
  16520. this._grip.hasLinearVelocity = false;
  16521. this._grip.linearVelocity = new Vector3();
  16522. this._grip.hasAngularVelocity = false;
  16523. this._grip.angularVelocity = new Vector3();
  16524. }
  16525. return this._grip;
  16526. }
  16527. /**
  16528. * Dispatches the given event to the groups representing
  16529. * the different coordinate spaces of the XR controller.
  16530. *
  16531. * @param {Object} event - The event to dispatch.
  16532. * @return {WebXRController} A reference to this instance.
  16533. */
  16534. dispatchEvent( event ) {
  16535. if ( this._targetRay !== null ) {
  16536. this._targetRay.dispatchEvent( event );
  16537. }
  16538. if ( this._grip !== null ) {
  16539. this._grip.dispatchEvent( event );
  16540. }
  16541. if ( this._hand !== null ) {
  16542. this._hand.dispatchEvent( event );
  16543. }
  16544. return this;
  16545. }
  16546. /**
  16547. * Connects the controller with the given XR input source.
  16548. *
  16549. * @param {XRInputSource} inputSource - The input source.
  16550. * @return {WebXRController} A reference to this instance.
  16551. */
  16552. connect( inputSource ) {
  16553. if ( inputSource && inputSource.hand ) {
  16554. const hand = this._hand;
  16555. if ( hand ) {
  16556. for ( const inputjoint of inputSource.hand.values() ) {
  16557. // Initialize hand with joints when connected
  16558. this._getHandJoint( hand, inputjoint );
  16559. }
  16560. }
  16561. }
  16562. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16563. return this;
  16564. }
  16565. /**
  16566. * Disconnects the controller from the given XR input source.
  16567. *
  16568. * @param {XRInputSource} inputSource - The input source.
  16569. * @return {WebXRController} A reference to this instance.
  16570. */
  16571. disconnect( inputSource ) {
  16572. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16573. if ( this._targetRay !== null ) {
  16574. this._targetRay.visible = false;
  16575. }
  16576. if ( this._grip !== null ) {
  16577. this._grip.visible = false;
  16578. }
  16579. if ( this._hand !== null ) {
  16580. this._hand.visible = false;
  16581. }
  16582. return this;
  16583. }
  16584. /**
  16585. * Updates the controller with the given input source, XR frame and reference space.
  16586. * This updates the transformations of the groups that represent the different
  16587. * coordinate systems of the controller.
  16588. *
  16589. * @param {XRInputSource} inputSource - The input source.
  16590. * @param {XRFrame} frame - The XR frame.
  16591. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16592. * @return {WebXRController} A reference to this instance.
  16593. */
  16594. update( inputSource, frame, referenceSpace ) {
  16595. let inputPose = null;
  16596. let gripPose = null;
  16597. let handPose = null;
  16598. const targetRay = this._targetRay;
  16599. const grip = this._grip;
  16600. const hand = this._hand;
  16601. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16602. if ( hand && inputSource.hand ) {
  16603. handPose = true;
  16604. for ( const inputjoint of inputSource.hand.values() ) {
  16605. // Update the joints groups with the XRJoint poses
  16606. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16607. // The transform of this joint will be updated with the joint pose on each frame
  16608. const joint = this._getHandJoint( hand, inputjoint );
  16609. if ( jointPose !== null ) {
  16610. joint.matrix.fromArray( jointPose.transform.matrix );
  16611. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16612. joint.matrixWorldNeedsUpdate = true;
  16613. joint.jointRadius = jointPose.radius;
  16614. }
  16615. joint.visible = jointPose !== null;
  16616. }
  16617. // Custom events
  16618. // Check pinchz
  16619. const indexTip = hand.joints[ 'index-finger-tip' ];
  16620. const thumbTip = hand.joints[ 'thumb-tip' ];
  16621. const distance = indexTip.position.distanceTo( thumbTip.position );
  16622. const distanceToPinch = 0.02;
  16623. const threshold = 0.005;
  16624. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16625. hand.inputState.pinching = false;
  16626. this.dispatchEvent( {
  16627. type: 'pinchend',
  16628. handedness: inputSource.handedness,
  16629. target: this
  16630. } );
  16631. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16632. hand.inputState.pinching = true;
  16633. this.dispatchEvent( {
  16634. type: 'pinchstart',
  16635. handedness: inputSource.handedness,
  16636. target: this
  16637. } );
  16638. }
  16639. } else {
  16640. if ( grip !== null && inputSource.gripSpace ) {
  16641. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16642. if ( gripPose !== null ) {
  16643. grip.matrix.fromArray( gripPose.transform.matrix );
  16644. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16645. grip.matrixWorldNeedsUpdate = true;
  16646. if ( gripPose.linearVelocity ) {
  16647. grip.hasLinearVelocity = true;
  16648. grip.linearVelocity.copy( gripPose.linearVelocity );
  16649. } else {
  16650. grip.hasLinearVelocity = false;
  16651. }
  16652. if ( gripPose.angularVelocity ) {
  16653. grip.hasAngularVelocity = true;
  16654. grip.angularVelocity.copy( gripPose.angularVelocity );
  16655. } else {
  16656. grip.hasAngularVelocity = false;
  16657. }
  16658. }
  16659. }
  16660. }
  16661. if ( targetRay !== null ) {
  16662. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16663. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16664. if ( inputPose === null && gripPose !== null ) {
  16665. inputPose = gripPose;
  16666. }
  16667. if ( inputPose !== null ) {
  16668. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16669. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16670. targetRay.matrixWorldNeedsUpdate = true;
  16671. if ( inputPose.linearVelocity ) {
  16672. targetRay.hasLinearVelocity = true;
  16673. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16674. } else {
  16675. targetRay.hasLinearVelocity = false;
  16676. }
  16677. if ( inputPose.angularVelocity ) {
  16678. targetRay.hasAngularVelocity = true;
  16679. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16680. } else {
  16681. targetRay.hasAngularVelocity = false;
  16682. }
  16683. this.dispatchEvent( _moveEvent );
  16684. }
  16685. }
  16686. }
  16687. if ( targetRay !== null ) {
  16688. targetRay.visible = ( inputPose !== null );
  16689. }
  16690. if ( grip !== null ) {
  16691. grip.visible = ( gripPose !== null );
  16692. }
  16693. if ( hand !== null ) {
  16694. hand.visible = ( handPose !== null );
  16695. }
  16696. return this;
  16697. }
  16698. /**
  16699. * Returns a group representing the hand joint for the given input joint.
  16700. *
  16701. * @private
  16702. * @param {Group} hand - The group representing the hand space.
  16703. * @param {XRHandJoint} inputjoint - The XR frame.
  16704. * @return {Group} A group representing the hand joint for the given input joint.
  16705. */
  16706. _getHandJoint( hand, inputjoint ) {
  16707. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16708. const joint = new Group();
  16709. joint.matrixAutoUpdate = false;
  16710. joint.visible = false;
  16711. hand.joints[ inputjoint.jointName ] = joint;
  16712. hand.add( joint );
  16713. }
  16714. return hand.joints[ inputjoint.jointName ];
  16715. }
  16716. }
  16717. /**
  16718. * This class can be used to define an exponential squared fog,
  16719. * which gives a clear view near the camera and a faster than exponentially
  16720. * densening fog farther from the camera.
  16721. *
  16722. * ```js
  16723. * const scene = new THREE.Scene();
  16724. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16725. * ```
  16726. */
  16727. class FogExp2 {
  16728. /**
  16729. * Constructs a new fog.
  16730. *
  16731. * @param {number|Color} color - The fog's color.
  16732. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16733. */
  16734. constructor( color, density = 0.00025 ) {
  16735. /**
  16736. * This flag can be used for type testing.
  16737. *
  16738. * @type {boolean}
  16739. * @readonly
  16740. * @default true
  16741. */
  16742. this.isFogExp2 = true;
  16743. /**
  16744. * The name of the fog.
  16745. *
  16746. * @type {string}
  16747. */
  16748. this.name = '';
  16749. /**
  16750. * The fog's color.
  16751. *
  16752. * @type {Color}
  16753. */
  16754. this.color = new Color( color );
  16755. /**
  16756. * Defines how fast the fog will grow dense.
  16757. *
  16758. * @type {number}
  16759. * @default 0.00025
  16760. */
  16761. this.density = density;
  16762. }
  16763. /**
  16764. * Returns a new fog with copied values from this instance.
  16765. *
  16766. * @return {FogExp2} A clone of this instance.
  16767. */
  16768. clone() {
  16769. return new FogExp2( this.color, this.density );
  16770. }
  16771. /**
  16772. * Serializes the fog into JSON.
  16773. *
  16774. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16775. * @return {Object} A JSON object representing the serialized fog
  16776. */
  16777. toJSON( /* meta */ ) {
  16778. return {
  16779. type: 'FogExp2',
  16780. name: this.name,
  16781. color: this.color.getHex(),
  16782. density: this.density
  16783. };
  16784. }
  16785. }
  16786. /**
  16787. * This class can be used to define a linear fog that grows linearly denser
  16788. * with the distance.
  16789. *
  16790. * ```js
  16791. * const scene = new THREE.Scene();
  16792. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  16793. * ```
  16794. */
  16795. class Fog {
  16796. /**
  16797. * Constructs a new fog.
  16798. *
  16799. * @param {number|Color} color - The fog's color.
  16800. * @param {number} [near=1] - The minimum distance to start applying fog.
  16801. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  16802. */
  16803. constructor( color, near = 1, far = 1000 ) {
  16804. /**
  16805. * This flag can be used for type testing.
  16806. *
  16807. * @type {boolean}
  16808. * @readonly
  16809. * @default true
  16810. */
  16811. this.isFog = true;
  16812. /**
  16813. * The name of the fog.
  16814. *
  16815. * @type {string}
  16816. */
  16817. this.name = '';
  16818. /**
  16819. * The fog's color.
  16820. *
  16821. * @type {Color}
  16822. */
  16823. this.color = new Color( color );
  16824. /**
  16825. * The minimum distance to start applying fog. Objects that are less than
  16826. * `near` units from the active camera won't be affected by fog.
  16827. *
  16828. * @type {number}
  16829. * @default 1
  16830. */
  16831. this.near = near;
  16832. /**
  16833. * The maximum distance at which fog stops being calculated and applied.
  16834. * Objects that are more than `far` units away from the active camera won't
  16835. * be affected by fog.
  16836. *
  16837. * @type {number}
  16838. * @default 1000
  16839. */
  16840. this.far = far;
  16841. }
  16842. /**
  16843. * Returns a new fog with copied values from this instance.
  16844. *
  16845. * @return {Fog} A clone of this instance.
  16846. */
  16847. clone() {
  16848. return new Fog( this.color, this.near, this.far );
  16849. }
  16850. /**
  16851. * Serializes the fog into JSON.
  16852. *
  16853. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16854. * @return {Object} A JSON object representing the serialized fog
  16855. */
  16856. toJSON( /* meta */ ) {
  16857. return {
  16858. type: 'Fog',
  16859. name: this.name,
  16860. color: this.color.getHex(),
  16861. near: this.near,
  16862. far: this.far
  16863. };
  16864. }
  16865. }
  16866. /**
  16867. * Scenes allow you to set up what is to be rendered and where by three.js.
  16868. * This is where you place 3D objects like meshes, lines or lights.
  16869. *
  16870. * @augments Object3D
  16871. */
  16872. class Scene extends Object3D {
  16873. /**
  16874. * Constructs a new scene.
  16875. */
  16876. constructor() {
  16877. super();
  16878. /**
  16879. * This flag can be used for type testing.
  16880. *
  16881. * @type {boolean}
  16882. * @readonly
  16883. * @default true
  16884. */
  16885. this.isScene = true;
  16886. this.type = 'Scene';
  16887. /**
  16888. * Defines the background of the scene. Valid inputs are:
  16889. *
  16890. * - A color for defining a uniform colored background.
  16891. * - A texture for defining a (flat) textured background.
  16892. * - Cube textures or equirectangular textures for defining a skybox.
  16893. *
  16894. * @type {?(Color|Texture)}
  16895. * @default null
  16896. */
  16897. this.background = null;
  16898. /**
  16899. * Sets the environment map for all physical materials in the scene. However,
  16900. * it's not possible to overwrite an existing texture assigned to the `envMap`
  16901. * material property.
  16902. *
  16903. * @type {?Texture}
  16904. * @default null
  16905. */
  16906. this.environment = null;
  16907. /**
  16908. * A fog instance defining the type of fog that affects everything
  16909. * rendered in the scene.
  16910. *
  16911. * @type {?(Fog|FogExp2)}
  16912. * @default null
  16913. */
  16914. this.fog = null;
  16915. /**
  16916. * Sets the blurriness of the background. Only influences environment maps
  16917. * assigned to {@link Scene#background}. Valid input is a float between `0`
  16918. * and `1`.
  16919. *
  16920. * @type {number}
  16921. * @default 0
  16922. */
  16923. this.backgroundBlurriness = 0;
  16924. /**
  16925. * Attenuates the color of the background. Only applies to background textures.
  16926. *
  16927. * @type {number}
  16928. * @default 1
  16929. */
  16930. this.backgroundIntensity = 1;
  16931. /**
  16932. * The rotation of the background in radians. Only influences environment maps
  16933. * assigned to {@link Scene#background}.
  16934. *
  16935. * @type {Euler}
  16936. * @default (0,0,0)
  16937. */
  16938. this.backgroundRotation = new Euler();
  16939. /**
  16940. * Attenuates the color of the environment. Only influences environment maps
  16941. * assigned to {@link Scene#environment}.
  16942. *
  16943. * @type {number}
  16944. * @default 1
  16945. */
  16946. this.environmentIntensity = 1;
  16947. /**
  16948. * The rotation of the environment map in radians. Only influences physical materials
  16949. * in the scene when {@link Scene#environment} is used.
  16950. *
  16951. * @type {Euler}
  16952. * @default (0,0,0)
  16953. */
  16954. this.environmentRotation = new Euler();
  16955. /**
  16956. * Forces everything in the scene to be rendered with the defined material. It is possible
  16957. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  16958. *
  16959. * @type {?Material}
  16960. * @default null
  16961. */
  16962. this.overrideMaterial = null;
  16963. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  16964. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  16965. }
  16966. }
  16967. copy( source, recursive ) {
  16968. super.copy( source, recursive );
  16969. if ( source.background !== null ) this.background = source.background.clone();
  16970. if ( source.environment !== null ) this.environment = source.environment.clone();
  16971. if ( source.fog !== null ) this.fog = source.fog.clone();
  16972. this.backgroundBlurriness = source.backgroundBlurriness;
  16973. this.backgroundIntensity = source.backgroundIntensity;
  16974. this.backgroundRotation.copy( source.backgroundRotation );
  16975. this.environmentIntensity = source.environmentIntensity;
  16976. this.environmentRotation.copy( source.environmentRotation );
  16977. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  16978. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16979. return this;
  16980. }
  16981. toJSON( meta ) {
  16982. const data = super.toJSON( meta );
  16983. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  16984. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  16985. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  16986. data.object.backgroundRotation = this.backgroundRotation.toArray();
  16987. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  16988. data.object.environmentRotation = this.environmentRotation.toArray();
  16989. return data;
  16990. }
  16991. }
  16992. /**
  16993. * "Interleaved" means that multiple attributes, possibly of different types,
  16994. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  16995. *
  16996. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  16997. */
  16998. class InterleavedBuffer {
  16999. /**
  17000. * Constructs a new interleaved buffer.
  17001. *
  17002. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17003. * @param {number} stride - The number of typed-array elements per vertex.
  17004. */
  17005. constructor( array, stride ) {
  17006. /**
  17007. * This flag can be used for type testing.
  17008. *
  17009. * @type {boolean}
  17010. * @readonly
  17011. * @default true
  17012. */
  17013. this.isInterleavedBuffer = true;
  17014. /**
  17015. * A typed array with a shared buffer storing attribute data.
  17016. *
  17017. * @type {TypedArray}
  17018. */
  17019. this.array = array;
  17020. /**
  17021. * The number of typed-array elements per vertex.
  17022. *
  17023. * @type {number}
  17024. */
  17025. this.stride = stride;
  17026. /**
  17027. * The total number of elements in the array
  17028. *
  17029. * @type {number}
  17030. * @readonly
  17031. */
  17032. this.count = array !== undefined ? array.length / stride : 0;
  17033. /**
  17034. * Defines the intended usage pattern of the data store for optimization purposes.
  17035. *
  17036. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17037. * instantiate a new one and set the desired usage before the next render.
  17038. *
  17039. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17040. * @default StaticDrawUsage
  17041. */
  17042. this.usage = StaticDrawUsage;
  17043. /**
  17044. * This can be used to only update some components of stored vectors (for example, just the
  17045. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17046. *
  17047. * @type {Array<Object>}
  17048. */
  17049. this.updateRanges = [];
  17050. /**
  17051. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17052. *
  17053. * @type {number}
  17054. */
  17055. this.version = 0;
  17056. /**
  17057. * The UUID of the interleaved buffer.
  17058. *
  17059. * @type {string}
  17060. * @readonly
  17061. */
  17062. this.uuid = generateUUID();
  17063. }
  17064. /**
  17065. * A callback function that is executed after the renderer has transferred the attribute array
  17066. * data to the GPU.
  17067. */
  17068. onUploadCallback() {}
  17069. /**
  17070. * Flag to indicate that this attribute has changed and should be re-sent to
  17071. * the GPU. Set this to `true` when you modify the value of the array.
  17072. *
  17073. * @type {number}
  17074. * @default false
  17075. * @param {boolean} value
  17076. */
  17077. set needsUpdate( value ) {
  17078. if ( value === true ) this.version ++;
  17079. }
  17080. /**
  17081. * Sets the usage of this interleaved buffer.
  17082. *
  17083. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17084. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17085. */
  17086. setUsage( value ) {
  17087. this.usage = value;
  17088. return this;
  17089. }
  17090. /**
  17091. * Adds a range of data in the data array to be updated on the GPU.
  17092. *
  17093. * @param {number} start - Position at which to start update.
  17094. * @param {number} count - The number of components to update.
  17095. */
  17096. addUpdateRange( start, count ) {
  17097. this.updateRanges.push( { start, count } );
  17098. }
  17099. /**
  17100. * Clears the update ranges.
  17101. */
  17102. clearUpdateRanges() {
  17103. this.updateRanges.length = 0;
  17104. }
  17105. /**
  17106. * Copies the values of the given interleaved buffer to this instance.
  17107. *
  17108. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17109. * @return {InterleavedBuffer} A reference to this instance.
  17110. */
  17111. copy( source ) {
  17112. this.array = new source.array.constructor( source.array );
  17113. this.count = source.count;
  17114. this.stride = source.stride;
  17115. this.usage = source.usage;
  17116. return this;
  17117. }
  17118. /**
  17119. * Copies a vector from the given interleaved buffer to this one. The start
  17120. * and destination position in the attribute buffers are represented by the
  17121. * given indices.
  17122. *
  17123. * @param {number} index1 - The destination index into this interleaved buffer.
  17124. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17125. * @param {number} index2 - The source index into the given interleaved buffer.
  17126. * @return {InterleavedBuffer} A reference to this instance.
  17127. */
  17128. copyAt( index1, interleavedBuffer, index2 ) {
  17129. index1 *= this.stride;
  17130. index2 *= interleavedBuffer.stride;
  17131. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17132. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17133. }
  17134. return this;
  17135. }
  17136. /**
  17137. * Sets the given array data in the interleaved buffer.
  17138. *
  17139. * @param {(TypedArray|Array)} value - The array data to set.
  17140. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17141. * @return {InterleavedBuffer} A reference to this instance.
  17142. */
  17143. set( value, offset = 0 ) {
  17144. this.array.set( value, offset );
  17145. return this;
  17146. }
  17147. /**
  17148. * Returns a new interleaved buffer with copied values from this instance.
  17149. *
  17150. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17151. * @return {InterleavedBuffer} A clone of this instance.
  17152. */
  17153. clone( data ) {
  17154. if ( data.arrayBuffers === undefined ) {
  17155. data.arrayBuffers = {};
  17156. }
  17157. if ( this.array.buffer._uuid === undefined ) {
  17158. this.array.buffer._uuid = generateUUID();
  17159. }
  17160. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17161. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17162. }
  17163. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17164. const ib = new this.constructor( array, this.stride );
  17165. ib.setUsage( this.usage );
  17166. return ib;
  17167. }
  17168. /**
  17169. * Sets the given callback function that is executed after the Renderer has transferred
  17170. * the array data to the GPU. Can be used to perform clean-up operations after
  17171. * the upload when data are not needed anymore on the CPU side.
  17172. *
  17173. * @param {Function} callback - The `onUpload()` callback.
  17174. * @return {InterleavedBuffer} A reference to this instance.
  17175. */
  17176. onUpload( callback ) {
  17177. this.onUploadCallback = callback;
  17178. return this;
  17179. }
  17180. /**
  17181. * Serializes the interleaved buffer into JSON.
  17182. *
  17183. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17184. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17185. */
  17186. toJSON( data ) {
  17187. if ( data.arrayBuffers === undefined ) {
  17188. data.arrayBuffers = {};
  17189. }
  17190. // generate UUID for array buffer if necessary
  17191. if ( this.array.buffer._uuid === undefined ) {
  17192. this.array.buffer._uuid = generateUUID();
  17193. }
  17194. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17195. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17196. }
  17197. //
  17198. return {
  17199. uuid: this.uuid,
  17200. buffer: this.array.buffer._uuid,
  17201. type: this.array.constructor.name,
  17202. stride: this.stride
  17203. };
  17204. }
  17205. }
  17206. const _vector$7 = /*@__PURE__*/ new Vector3();
  17207. /**
  17208. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17209. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17210. * different offsets into the buffer.
  17211. */
  17212. class InterleavedBufferAttribute {
  17213. /**
  17214. * Constructs a new interleaved buffer attribute.
  17215. *
  17216. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17217. * @param {number} itemSize - The item size.
  17218. * @param {number} offset - The attribute offset into the buffer.
  17219. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17220. */
  17221. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17222. /**
  17223. * This flag can be used for type testing.
  17224. *
  17225. * @type {boolean}
  17226. * @readonly
  17227. * @default true
  17228. */
  17229. this.isInterleavedBufferAttribute = true;
  17230. /**
  17231. * The name of the buffer attribute.
  17232. *
  17233. * @type {string}
  17234. */
  17235. this.name = '';
  17236. /**
  17237. * The buffer holding the interleaved data.
  17238. *
  17239. * @type {InterleavedBuffer}
  17240. */
  17241. this.data = interleavedBuffer;
  17242. /**
  17243. * The item size, see {@link BufferAttribute#itemSize}.
  17244. *
  17245. * @type {number}
  17246. */
  17247. this.itemSize = itemSize;
  17248. /**
  17249. * The attribute offset into the buffer.
  17250. *
  17251. * @type {number}
  17252. */
  17253. this.offset = offset;
  17254. /**
  17255. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17256. *
  17257. * @type {InterleavedBuffer}
  17258. */
  17259. this.normalized = normalized;
  17260. }
  17261. /**
  17262. * The item count of this buffer attribute.
  17263. *
  17264. * @type {number}
  17265. * @readonly
  17266. */
  17267. get count() {
  17268. return this.data.count;
  17269. }
  17270. /**
  17271. * The array holding the interleaved buffer attribute data.
  17272. *
  17273. * @type {TypedArray}
  17274. */
  17275. get array() {
  17276. return this.data.array;
  17277. }
  17278. /**
  17279. * Flag to indicate that this attribute has changed and should be re-sent to
  17280. * the GPU. Set this to `true` when you modify the value of the array.
  17281. *
  17282. * @type {number}
  17283. * @default false
  17284. * @param {boolean} value
  17285. */
  17286. set needsUpdate( value ) {
  17287. this.data.needsUpdate = value;
  17288. }
  17289. /**
  17290. * Applies the given 4x4 matrix to the given attribute. Only works with
  17291. * item size `3`.
  17292. *
  17293. * @param {Matrix4} m - The matrix to apply.
  17294. * @return {InterleavedBufferAttribute} A reference to this instance.
  17295. */
  17296. applyMatrix4( m ) {
  17297. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17298. _vector$7.fromBufferAttribute( this, i );
  17299. _vector$7.applyMatrix4( m );
  17300. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17301. }
  17302. return this;
  17303. }
  17304. /**
  17305. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17306. * item size `3`.
  17307. *
  17308. * @param {Matrix3} m - The normal matrix to apply.
  17309. * @return {InterleavedBufferAttribute} A reference to this instance.
  17310. */
  17311. applyNormalMatrix( m ) {
  17312. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17313. _vector$7.fromBufferAttribute( this, i );
  17314. _vector$7.applyNormalMatrix( m );
  17315. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17316. }
  17317. return this;
  17318. }
  17319. /**
  17320. * Applies the given 4x4 matrix to the given attribute. Only works with
  17321. * item size `3` and with direction vectors.
  17322. *
  17323. * @param {Matrix4} m - The matrix to apply.
  17324. * @return {InterleavedBufferAttribute} A reference to this instance.
  17325. */
  17326. transformDirection( m ) {
  17327. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17328. _vector$7.fromBufferAttribute( this, i );
  17329. _vector$7.transformDirection( m );
  17330. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17331. }
  17332. return this;
  17333. }
  17334. /**
  17335. * Returns the given component of the vector at the given index.
  17336. *
  17337. * @param {number} index - The index into the buffer attribute.
  17338. * @param {number} component - The component index.
  17339. * @return {number} The returned value.
  17340. */
  17341. getComponent( index, component ) {
  17342. let value = this.array[ index * this.data.stride + this.offset + component ];
  17343. if ( this.normalized ) value = denormalize( value, this.array );
  17344. return value;
  17345. }
  17346. /**
  17347. * Sets the given value to the given component of the vector at the given index.
  17348. *
  17349. * @param {number} index - The index into the buffer attribute.
  17350. * @param {number} component - The component index.
  17351. * @param {number} value - The value to set.
  17352. * @return {InterleavedBufferAttribute} A reference to this instance.
  17353. */
  17354. setComponent( index, component, value ) {
  17355. if ( this.normalized ) value = normalize( value, this.array );
  17356. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17357. return this;
  17358. }
  17359. /**
  17360. * Sets the x component of the vector at the given index.
  17361. *
  17362. * @param {number} index - The index into the buffer attribute.
  17363. * @param {number} x - The value to set.
  17364. * @return {InterleavedBufferAttribute} A reference to this instance.
  17365. */
  17366. setX( index, x ) {
  17367. if ( this.normalized ) x = normalize( x, this.array );
  17368. this.data.array[ index * this.data.stride + this.offset ] = x;
  17369. return this;
  17370. }
  17371. /**
  17372. * Sets the y component of the vector at the given index.
  17373. *
  17374. * @param {number} index - The index into the buffer attribute.
  17375. * @param {number} y - The value to set.
  17376. * @return {InterleavedBufferAttribute} A reference to this instance.
  17377. */
  17378. setY( index, y ) {
  17379. if ( this.normalized ) y = normalize( y, this.array );
  17380. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17381. return this;
  17382. }
  17383. /**
  17384. * Sets the z component of the vector at the given index.
  17385. *
  17386. * @param {number} index - The index into the buffer attribute.
  17387. * @param {number} z - The value to set.
  17388. * @return {InterleavedBufferAttribute} A reference to this instance.
  17389. */
  17390. setZ( index, z ) {
  17391. if ( this.normalized ) z = normalize( z, this.array );
  17392. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17393. return this;
  17394. }
  17395. /**
  17396. * Sets the w component of the vector at the given index.
  17397. *
  17398. * @param {number} index - The index into the buffer attribute.
  17399. * @param {number} w - The value to set.
  17400. * @return {InterleavedBufferAttribute} A reference to this instance.
  17401. */
  17402. setW( index, w ) {
  17403. if ( this.normalized ) w = normalize( w, this.array );
  17404. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17405. return this;
  17406. }
  17407. /**
  17408. * Returns the x component of the vector at the given index.
  17409. *
  17410. * @param {number} index - The index into the buffer attribute.
  17411. * @return {number} The x component.
  17412. */
  17413. getX( index ) {
  17414. let x = this.data.array[ index * this.data.stride + this.offset ];
  17415. if ( this.normalized ) x = denormalize( x, this.array );
  17416. return x;
  17417. }
  17418. /**
  17419. * Returns the y component of the vector at the given index.
  17420. *
  17421. * @param {number} index - The index into the buffer attribute.
  17422. * @return {number} The y component.
  17423. */
  17424. getY( index ) {
  17425. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17426. if ( this.normalized ) y = denormalize( y, this.array );
  17427. return y;
  17428. }
  17429. /**
  17430. * Returns the z component of the vector at the given index.
  17431. *
  17432. * @param {number} index - The index into the buffer attribute.
  17433. * @return {number} The z component.
  17434. */
  17435. getZ( index ) {
  17436. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17437. if ( this.normalized ) z = denormalize( z, this.array );
  17438. return z;
  17439. }
  17440. /**
  17441. * Returns the w component of the vector at the given index.
  17442. *
  17443. * @param {number} index - The index into the buffer attribute.
  17444. * @return {number} The w component.
  17445. */
  17446. getW( index ) {
  17447. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17448. if ( this.normalized ) w = denormalize( w, this.array );
  17449. return w;
  17450. }
  17451. /**
  17452. * Sets the x and y component of the vector at the given index.
  17453. *
  17454. * @param {number} index - The index into the buffer attribute.
  17455. * @param {number} x - The value for the x component to set.
  17456. * @param {number} y - The value for the y component to set.
  17457. * @return {InterleavedBufferAttribute} A reference to this instance.
  17458. */
  17459. setXY( index, x, y ) {
  17460. index = index * this.data.stride + this.offset;
  17461. if ( this.normalized ) {
  17462. x = normalize( x, this.array );
  17463. y = normalize( y, this.array );
  17464. }
  17465. this.data.array[ index + 0 ] = x;
  17466. this.data.array[ index + 1 ] = y;
  17467. return this;
  17468. }
  17469. /**
  17470. * Sets the x, y and z component of the vector at the given index.
  17471. *
  17472. * @param {number} index - The index into the buffer attribute.
  17473. * @param {number} x - The value for the x component to set.
  17474. * @param {number} y - The value for the y component to set.
  17475. * @param {number} z - The value for the z component to set.
  17476. * @return {InterleavedBufferAttribute} A reference to this instance.
  17477. */
  17478. setXYZ( index, x, y, z ) {
  17479. index = index * this.data.stride + this.offset;
  17480. if ( this.normalized ) {
  17481. x = normalize( x, this.array );
  17482. y = normalize( y, this.array );
  17483. z = normalize( z, this.array );
  17484. }
  17485. this.data.array[ index + 0 ] = x;
  17486. this.data.array[ index + 1 ] = y;
  17487. this.data.array[ index + 2 ] = z;
  17488. return this;
  17489. }
  17490. /**
  17491. * Sets the x, y, z and w component of the vector at the given index.
  17492. *
  17493. * @param {number} index - The index into the buffer attribute.
  17494. * @param {number} x - The value for the x component to set.
  17495. * @param {number} y - The value for the y component to set.
  17496. * @param {number} z - The value for the z component to set.
  17497. * @param {number} w - The value for the w component to set.
  17498. * @return {InterleavedBufferAttribute} A reference to this instance.
  17499. */
  17500. setXYZW( index, x, y, z, w ) {
  17501. index = index * this.data.stride + this.offset;
  17502. if ( this.normalized ) {
  17503. x = normalize( x, this.array );
  17504. y = normalize( y, this.array );
  17505. z = normalize( z, this.array );
  17506. w = normalize( w, this.array );
  17507. }
  17508. this.data.array[ index + 0 ] = x;
  17509. this.data.array[ index + 1 ] = y;
  17510. this.data.array[ index + 2 ] = z;
  17511. this.data.array[ index + 3 ] = w;
  17512. return this;
  17513. }
  17514. /**
  17515. * Returns a new buffer attribute with copied values from this instance.
  17516. *
  17517. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17518. *
  17519. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17520. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17521. */
  17522. clone( data ) {
  17523. if ( data === undefined ) {
  17524. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17525. const array = [];
  17526. for ( let i = 0; i < this.count; i ++ ) {
  17527. const index = i * this.data.stride + this.offset;
  17528. for ( let j = 0; j < this.itemSize; j ++ ) {
  17529. array.push( this.data.array[ index + j ] );
  17530. }
  17531. }
  17532. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17533. } else {
  17534. if ( data.interleavedBuffers === undefined ) {
  17535. data.interleavedBuffers = {};
  17536. }
  17537. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17538. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17539. }
  17540. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17541. }
  17542. }
  17543. /**
  17544. * Serializes the buffer attribute into JSON.
  17545. *
  17546. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17547. *
  17548. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17549. * @return {Object} A JSON object representing the serialized buffer attribute.
  17550. */
  17551. toJSON( data ) {
  17552. if ( data === undefined ) {
  17553. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17554. const array = [];
  17555. for ( let i = 0; i < this.count; i ++ ) {
  17556. const index = i * this.data.stride + this.offset;
  17557. for ( let j = 0; j < this.itemSize; j ++ ) {
  17558. array.push( this.data.array[ index + j ] );
  17559. }
  17560. }
  17561. // de-interleave data and save it as an ordinary buffer attribute for now
  17562. return {
  17563. itemSize: this.itemSize,
  17564. type: this.array.constructor.name,
  17565. array: array,
  17566. normalized: this.normalized
  17567. };
  17568. } else {
  17569. // save as true interleaved attribute
  17570. if ( data.interleavedBuffers === undefined ) {
  17571. data.interleavedBuffers = {};
  17572. }
  17573. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17574. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17575. }
  17576. return {
  17577. isInterleavedBufferAttribute: true,
  17578. itemSize: this.itemSize,
  17579. data: this.data.uuid,
  17580. offset: this.offset,
  17581. normalized: this.normalized
  17582. };
  17583. }
  17584. }
  17585. }
  17586. /**
  17587. * A material for rendering instances of {@link Sprite}.
  17588. *
  17589. * ```js
  17590. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17591. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17592. *
  17593. * const sprite = new THREE.Sprite( material );
  17594. * sprite.scale.set(200, 200, 1)
  17595. * scene.add( sprite );
  17596. * ```
  17597. *
  17598. * @augments Material
  17599. */
  17600. class SpriteMaterial extends Material {
  17601. /**
  17602. * Constructs a new sprite material.
  17603. *
  17604. * @param {Object} [parameters] - An object with one or more properties
  17605. * defining the material's appearance. Any property of the material
  17606. * (including any property from inherited materials) can be passed
  17607. * in here. Color values can be passed any type of value accepted
  17608. * by {@link Color#set}.
  17609. */
  17610. constructor( parameters ) {
  17611. super();
  17612. /**
  17613. * This flag can be used for type testing.
  17614. *
  17615. * @type {boolean}
  17616. * @readonly
  17617. * @default true
  17618. */
  17619. this.isSpriteMaterial = true;
  17620. this.type = 'SpriteMaterial';
  17621. /**
  17622. * Color of the material.
  17623. *
  17624. * @type {Color}
  17625. * @default (1,1,1)
  17626. */
  17627. this.color = new Color( 0xffffff );
  17628. /**
  17629. * The color map. May optionally include an alpha channel, typically combined
  17630. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17631. * color is modulated by the diffuse `color`.
  17632. *
  17633. * @type {?Texture}
  17634. * @default null
  17635. */
  17636. this.map = null;
  17637. /**
  17638. * The alpha map is a grayscale texture that controls the opacity across the
  17639. * surface (black: fully transparent; white: fully opaque).
  17640. *
  17641. * Only the color of the texture is used, ignoring the alpha channel if one
  17642. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17643. * when sampling this texture due to the extra bit of precision provided for
  17644. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17645. * luminance/alpha textures will also still work as expected.
  17646. *
  17647. * @type {?Texture}
  17648. * @default null
  17649. */
  17650. this.alphaMap = null;
  17651. /**
  17652. * The rotation of the sprite in radians.
  17653. *
  17654. * @type {number}
  17655. * @default 0
  17656. */
  17657. this.rotation = 0;
  17658. /**
  17659. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17660. *
  17661. * @type {boolean}
  17662. * @default true
  17663. */
  17664. this.sizeAttenuation = true;
  17665. /**
  17666. * Overwritten since sprite materials are transparent
  17667. * by default.
  17668. *
  17669. * @type {boolean}
  17670. * @default true
  17671. */
  17672. this.transparent = true;
  17673. /**
  17674. * Whether the material is affected by fog or not.
  17675. *
  17676. * @type {boolean}
  17677. * @default true
  17678. */
  17679. this.fog = true;
  17680. this.setValues( parameters );
  17681. }
  17682. copy( source ) {
  17683. super.copy( source );
  17684. this.color.copy( source.color );
  17685. this.map = source.map;
  17686. this.alphaMap = source.alphaMap;
  17687. this.rotation = source.rotation;
  17688. this.sizeAttenuation = source.sizeAttenuation;
  17689. this.fog = source.fog;
  17690. return this;
  17691. }
  17692. }
  17693. let _geometry;
  17694. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17695. const _worldScale = /*@__PURE__*/ new Vector3();
  17696. const _mvPosition = /*@__PURE__*/ new Vector3();
  17697. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17698. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17699. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17700. const _vA = /*@__PURE__*/ new Vector3();
  17701. const _vB = /*@__PURE__*/ new Vector3();
  17702. const _vC = /*@__PURE__*/ new Vector3();
  17703. const _uvA = /*@__PURE__*/ new Vector2();
  17704. const _uvB = /*@__PURE__*/ new Vector2();
  17705. const _uvC = /*@__PURE__*/ new Vector2();
  17706. /**
  17707. * A sprite is a plane that always faces towards the camera, generally with a
  17708. * partially transparent texture applied.
  17709. *
  17710. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17711. * have no effect.
  17712. *
  17713. * ```js
  17714. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17715. * const material = new THREE.SpriteMaterial( { map: map } );
  17716. *
  17717. * const sprite = new THREE.Sprite( material );
  17718. * scene.add( sprite );
  17719. * ```
  17720. *
  17721. * @augments Object3D
  17722. */
  17723. class Sprite extends Object3D {
  17724. /**
  17725. * Constructs a new sprite.
  17726. *
  17727. * @param {SpriteMaterial} [material] - The sprite material.
  17728. */
  17729. constructor( material = new SpriteMaterial() ) {
  17730. super();
  17731. /**
  17732. * This flag can be used for type testing.
  17733. *
  17734. * @type {boolean}
  17735. * @readonly
  17736. * @default true
  17737. */
  17738. this.isSprite = true;
  17739. this.type = 'Sprite';
  17740. if ( _geometry === undefined ) {
  17741. _geometry = new BufferGeometry();
  17742. const float32Array = new Float32Array( [
  17743. - 0.5, - 0.5, 0, 0, 0,
  17744. 0.5, - 0.5, 0, 1, 0,
  17745. 0.5, 0.5, 0, 1, 1,
  17746. - 0.5, 0.5, 0, 0, 1
  17747. ] );
  17748. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17749. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17750. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17751. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17752. }
  17753. /**
  17754. * The sprite geometry.
  17755. *
  17756. * @type {BufferGeometry}
  17757. */
  17758. this.geometry = _geometry;
  17759. /**
  17760. * The sprite material.
  17761. *
  17762. * @type {SpriteMaterial}
  17763. */
  17764. this.material = material;
  17765. /**
  17766. * The sprite's anchor point, and the point around which the sprite rotates.
  17767. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17768. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17769. *
  17770. * @type {Vector2}
  17771. * @default (0.5,0.5)
  17772. */
  17773. this.center = new Vector2( 0.5, 0.5 );
  17774. }
  17775. /**
  17776. * Computes intersection points between a casted ray and this sprite.
  17777. *
  17778. * @param {Raycaster} raycaster - The raycaster.
  17779. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17780. */
  17781. raycast( raycaster, intersects ) {
  17782. if ( raycaster.camera === null ) {
  17783. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17784. }
  17785. _worldScale.setFromMatrixScale( this.matrixWorld );
  17786. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17787. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17788. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17789. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17790. _worldScale.multiplyScalar( - _mvPosition.z );
  17791. }
  17792. const rotation = this.material.rotation;
  17793. let sin, cos;
  17794. if ( rotation !== 0 ) {
  17795. cos = Math.cos( rotation );
  17796. sin = Math.sin( rotation );
  17797. }
  17798. const center = this.center;
  17799. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17800. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17801. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17802. _uvA.set( 0, 0 );
  17803. _uvB.set( 1, 0 );
  17804. _uvC.set( 1, 1 );
  17805. // check first triangle
  17806. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17807. if ( intersect === null ) {
  17808. // check second triangle
  17809. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17810. _uvB.set( 0, 1 );
  17811. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17812. if ( intersect === null ) {
  17813. return;
  17814. }
  17815. }
  17816. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17817. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17818. intersects.push( {
  17819. distance: distance,
  17820. point: _intersectPoint.clone(),
  17821. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17822. face: null,
  17823. object: this
  17824. } );
  17825. }
  17826. copy( source, recursive ) {
  17827. super.copy( source, recursive );
  17828. if ( source.center !== undefined ) this.center.copy( source.center );
  17829. this.material = source.material;
  17830. return this;
  17831. }
  17832. }
  17833. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17834. // compute position in camera space
  17835. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17836. // to check if rotation is not zero
  17837. if ( sin !== undefined ) {
  17838. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17839. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17840. } else {
  17841. _rotatedPosition.copy( _alignedPosition );
  17842. }
  17843. vertexPosition.copy( mvPosition );
  17844. vertexPosition.x += _rotatedPosition.x;
  17845. vertexPosition.y += _rotatedPosition.y;
  17846. // transform to world space
  17847. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17848. }
  17849. const _v1$2 = /*@__PURE__*/ new Vector3();
  17850. const _v2$1 = /*@__PURE__*/ new Vector3();
  17851. /**
  17852. * A component for providing a basic Level of Detail (LOD) mechanism.
  17853. *
  17854. * Every LOD level is associated with an object, and rendering can be switched
  17855. * between them at the distances specified. Typically you would create, say,
  17856. * three meshes, one for far away (low detail), one for mid range (medium
  17857. * detail) and one for close up (high detail).
  17858. *
  17859. * ```js
  17860. * const lod = new THREE.LOD();
  17861. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17862. *
  17863. * //Create spheres with 3 levels of detail and create new LOD levels for them
  17864. * for( let i = 0; i < 3; i++ ) {
  17865. *
  17866. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  17867. * const mesh = new THREE.Mesh( geometry, material );
  17868. * lod.addLevel( mesh, i * 75 );
  17869. *
  17870. * }
  17871. *
  17872. * scene.add( lod );
  17873. * ```
  17874. *
  17875. * @augments Object3D
  17876. */
  17877. class LOD extends Object3D {
  17878. /**
  17879. * Constructs a new LOD.
  17880. */
  17881. constructor() {
  17882. super();
  17883. /**
  17884. * This flag can be used for type testing.
  17885. *
  17886. * @type {boolean}
  17887. * @readonly
  17888. * @default true
  17889. */
  17890. this.isLOD = true;
  17891. /**
  17892. * The current LOD index.
  17893. *
  17894. * @private
  17895. * @type {number}
  17896. * @default 0
  17897. */
  17898. this._currentLevel = 0;
  17899. this.type = 'LOD';
  17900. Object.defineProperties( this, {
  17901. /**
  17902. * This array holds the LOD levels.
  17903. *
  17904. * @name LOD#levels
  17905. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  17906. */
  17907. levels: {
  17908. enumerable: true,
  17909. value: []
  17910. }
  17911. } );
  17912. /**
  17913. * Whether the LOD object is updated automatically by the renderer per frame
  17914. * or not. If set to `false`, you have to call {@link LOD#update} in the
  17915. * render loop by yourself.
  17916. *
  17917. * @type {boolean}
  17918. * @default true
  17919. */
  17920. this.autoUpdate = true;
  17921. }
  17922. copy( source ) {
  17923. super.copy( source, false );
  17924. const levels = source.levels;
  17925. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17926. const level = levels[ i ];
  17927. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17928. }
  17929. this.autoUpdate = source.autoUpdate;
  17930. return this;
  17931. }
  17932. /**
  17933. * Adds a mesh that will display at a certain distance and greater. Typically
  17934. * the further away the distance, the lower the detail on the mesh.
  17935. *
  17936. * @param {Object3D} object - The 3D object to display at this level.
  17937. * @param {number} [distance=0] - The distance at which to display this level of detail.
  17938. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  17939. * @return {LOD} A reference to this instance.
  17940. */
  17941. addLevel( object, distance = 0, hysteresis = 0 ) {
  17942. distance = Math.abs( distance );
  17943. const levels = this.levels;
  17944. let l;
  17945. for ( l = 0; l < levels.length; l ++ ) {
  17946. if ( distance < levels[ l ].distance ) {
  17947. break;
  17948. }
  17949. }
  17950. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17951. this.add( object );
  17952. return this;
  17953. }
  17954. /**
  17955. * Removes an existing level, based on the distance from the camera.
  17956. * Returns `true` when the level has been removed. Otherwise `false`.
  17957. *
  17958. * @param {number} distance - Distance of the level to remove.
  17959. * @return {boolean} Whether the level has been removed or not.
  17960. */
  17961. removeLevel( distance ) {
  17962. const levels = this.levels;
  17963. for ( let i = 0; i < levels.length; i ++ ) {
  17964. if ( levels[ i ].distance === distance ) {
  17965. const removedElements = levels.splice( i, 1 );
  17966. this.remove( removedElements[ 0 ].object );
  17967. return true;
  17968. }
  17969. }
  17970. return false;
  17971. }
  17972. /**
  17973. * Returns the currently active LOD level index.
  17974. *
  17975. * @return {number} The current active LOD level index.
  17976. */
  17977. getCurrentLevel() {
  17978. return this._currentLevel;
  17979. }
  17980. /**
  17981. * Returns a reference to the first 3D object that is greater than
  17982. * the given distance.
  17983. *
  17984. * @param {number} distance - The LOD distance.
  17985. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  17986. */
  17987. getObjectForDistance( distance ) {
  17988. const levels = this.levels;
  17989. if ( levels.length > 0 ) {
  17990. let i, l;
  17991. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17992. let levelDistance = levels[ i ].distance;
  17993. if ( levels[ i ].object.visible ) {
  17994. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17995. }
  17996. if ( distance < levelDistance ) {
  17997. break;
  17998. }
  17999. }
  18000. return levels[ i - 1 ].object;
  18001. }
  18002. return null;
  18003. }
  18004. /**
  18005. * Computes intersection points between a casted ray and this LOD.
  18006. *
  18007. * @param {Raycaster} raycaster - The raycaster.
  18008. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18009. */
  18010. raycast( raycaster, intersects ) {
  18011. const levels = this.levels;
  18012. if ( levels.length > 0 ) {
  18013. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18014. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18015. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18016. }
  18017. }
  18018. /**
  18019. * Updates the LOD by computing which LOD level should be visible according
  18020. * to the current distance of the given camera.
  18021. *
  18022. * @param {Camera} camera - The camera the scene is rendered with.
  18023. */
  18024. update( camera ) {
  18025. const levels = this.levels;
  18026. if ( levels.length > 1 ) {
  18027. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18028. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18029. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18030. levels[ 0 ].object.visible = true;
  18031. let i, l;
  18032. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18033. let levelDistance = levels[ i ].distance;
  18034. if ( levels[ i ].object.visible ) {
  18035. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18036. }
  18037. if ( distance >= levelDistance ) {
  18038. levels[ i - 1 ].object.visible = false;
  18039. levels[ i ].object.visible = true;
  18040. } else {
  18041. break;
  18042. }
  18043. }
  18044. this._currentLevel = i - 1;
  18045. for ( ; i < l; i ++ ) {
  18046. levels[ i ].object.visible = false;
  18047. }
  18048. }
  18049. }
  18050. toJSON( meta ) {
  18051. const data = super.toJSON( meta );
  18052. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18053. data.object.levels = [];
  18054. const levels = this.levels;
  18055. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18056. const level = levels[ i ];
  18057. data.object.levels.push( {
  18058. object: level.object.uuid,
  18059. distance: level.distance,
  18060. hysteresis: level.hysteresis
  18061. } );
  18062. }
  18063. return data;
  18064. }
  18065. }
  18066. const _basePosition = /*@__PURE__*/ new Vector3();
  18067. const _skinIndex = /*@__PURE__*/ new Vector4();
  18068. const _skinWeight = /*@__PURE__*/ new Vector4();
  18069. const _vector3 = /*@__PURE__*/ new Vector3();
  18070. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18071. const _vertex = /*@__PURE__*/ new Vector3();
  18072. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18073. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18074. const _ray$2 = /*@__PURE__*/ new Ray();
  18075. /**
  18076. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18077. * vertices of the geometry with skinning/skeleton animation.
  18078. *
  18079. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18080. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18081. * vertex to a certain extend.
  18082. *
  18083. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18084. * or {@link FBXLoader } import respective models.
  18085. *
  18086. * @augments Mesh
  18087. */
  18088. class SkinnedMesh extends Mesh {
  18089. /**
  18090. * Constructs a new skinned mesh.
  18091. *
  18092. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18093. * @param {Material|Array<Material>} [material] - The mesh material.
  18094. */
  18095. constructor( geometry, material ) {
  18096. super( geometry, material );
  18097. /**
  18098. * This flag can be used for type testing.
  18099. *
  18100. * @type {boolean}
  18101. * @readonly
  18102. * @default true
  18103. */
  18104. this.isSkinnedMesh = true;
  18105. this.type = 'SkinnedMesh';
  18106. /**
  18107. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18108. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18109. * across multiple skinned meshes.
  18110. *
  18111. * @type {(AttachedBindMode|DetachedBindMode)}
  18112. * @default AttachedBindMode
  18113. */
  18114. this.bindMode = AttachedBindMode;
  18115. /**
  18116. * The base matrix that is used for the bound bone transforms.
  18117. *
  18118. * @type {Matrix4}
  18119. */
  18120. this.bindMatrix = new Matrix4();
  18121. /**
  18122. * The base matrix that is used for resetting the bound bone transforms.
  18123. *
  18124. * @type {Matrix4}
  18125. */
  18126. this.bindMatrixInverse = new Matrix4();
  18127. /**
  18128. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18129. *
  18130. * @type {?Box3}
  18131. * @default null
  18132. */
  18133. this.boundingBox = null;
  18134. /**
  18135. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18136. *
  18137. * @type {?Sphere}
  18138. * @default null
  18139. */
  18140. this.boundingSphere = null;
  18141. }
  18142. /**
  18143. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18144. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18145. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18146. * the current animation state.
  18147. */
  18148. computeBoundingBox() {
  18149. const geometry = this.geometry;
  18150. if ( this.boundingBox === null ) {
  18151. this.boundingBox = new Box3();
  18152. }
  18153. this.boundingBox.makeEmpty();
  18154. const positionAttribute = geometry.getAttribute( 'position' );
  18155. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18156. this.getVertexPosition( i, _vertex );
  18157. this.boundingBox.expandByPoint( _vertex );
  18158. }
  18159. }
  18160. /**
  18161. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18162. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18163. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18164. * per frame in order to reflect the current animation state.
  18165. */
  18166. computeBoundingSphere() {
  18167. const geometry = this.geometry;
  18168. if ( this.boundingSphere === null ) {
  18169. this.boundingSphere = new Sphere();
  18170. }
  18171. this.boundingSphere.makeEmpty();
  18172. const positionAttribute = geometry.getAttribute( 'position' );
  18173. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18174. this.getVertexPosition( i, _vertex );
  18175. this.boundingSphere.expandByPoint( _vertex );
  18176. }
  18177. }
  18178. copy( source, recursive ) {
  18179. super.copy( source, recursive );
  18180. this.bindMode = source.bindMode;
  18181. this.bindMatrix.copy( source.bindMatrix );
  18182. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18183. this.skeleton = source.skeleton;
  18184. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18185. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18186. return this;
  18187. }
  18188. raycast( raycaster, intersects ) {
  18189. const material = this.material;
  18190. const matrixWorld = this.matrixWorld;
  18191. if ( material === undefined ) return;
  18192. // test with bounding sphere in world space
  18193. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18194. _sphere$5.copy( this.boundingSphere );
  18195. _sphere$5.applyMatrix4( matrixWorld );
  18196. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18197. // convert ray to local space of skinned mesh
  18198. _inverseMatrix$2.copy( matrixWorld ).invert();
  18199. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18200. // test with bounding box in local space
  18201. if ( this.boundingBox !== null ) {
  18202. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18203. }
  18204. // test for intersections with geometry
  18205. this._computeIntersections( raycaster, intersects, _ray$2 );
  18206. }
  18207. getVertexPosition( index, target ) {
  18208. super.getVertexPosition( index, target );
  18209. this.applyBoneTransform( index, target );
  18210. return target;
  18211. }
  18212. /**
  18213. * Binds the given skeleton to the skinned mesh.
  18214. *
  18215. * @param {Skeleton} skeleton - The skeleton to bind.
  18216. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18217. * the skinned mesh's world matrix will be used instead.
  18218. */
  18219. bind( skeleton, bindMatrix ) {
  18220. this.skeleton = skeleton;
  18221. if ( bindMatrix === undefined ) {
  18222. this.updateMatrixWorld( true );
  18223. this.skeleton.calculateInverses();
  18224. bindMatrix = this.matrixWorld;
  18225. }
  18226. this.bindMatrix.copy( bindMatrix );
  18227. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18228. }
  18229. /**
  18230. * This method sets the skinned mesh in the rest pose).
  18231. */
  18232. pose() {
  18233. this.skeleton.pose();
  18234. }
  18235. /**
  18236. * Normalizes the skin weights which are defined as a buffer attribute
  18237. * in the skinned mesh's geometry.
  18238. */
  18239. normalizeSkinWeights() {
  18240. const vector = new Vector4();
  18241. const skinWeight = this.geometry.attributes.skinWeight;
  18242. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18243. vector.fromBufferAttribute( skinWeight, i );
  18244. const scale = 1.0 / vector.manhattanLength();
  18245. if ( scale !== Infinity ) {
  18246. vector.multiplyScalar( scale );
  18247. } else {
  18248. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18249. }
  18250. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18251. }
  18252. }
  18253. updateMatrixWorld( force ) {
  18254. super.updateMatrixWorld( force );
  18255. if ( this.bindMode === AttachedBindMode ) {
  18256. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18257. } else if ( this.bindMode === DetachedBindMode ) {
  18258. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18259. } else {
  18260. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18261. }
  18262. }
  18263. /**
  18264. * Applies the bone transform associated with the given index to the given
  18265. * vertex position. Returns the updated vector.
  18266. *
  18267. * @param {number} index - The vertex index.
  18268. * @param {Vector3} target - The target object that is used to store the method's result.
  18269. * the skinned mesh's world matrix will be used instead.
  18270. * @return {Vector3} The updated vertex position.
  18271. */
  18272. applyBoneTransform( index, target ) {
  18273. const skeleton = this.skeleton;
  18274. const geometry = this.geometry;
  18275. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18276. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18277. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18278. target.set( 0, 0, 0 );
  18279. for ( let i = 0; i < 4; i ++ ) {
  18280. const weight = _skinWeight.getComponent( i );
  18281. if ( weight !== 0 ) {
  18282. const boneIndex = _skinIndex.getComponent( i );
  18283. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18284. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18285. }
  18286. }
  18287. return target.applyMatrix4( this.bindMatrixInverse );
  18288. }
  18289. }
  18290. /**
  18291. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18292. * the {@link SkinnedMesh}.
  18293. *
  18294. * ```js
  18295. * const root = new THREE.Bone();
  18296. * const child = new THREE.Bone();
  18297. *
  18298. * root.add( child );
  18299. * child.position.y = 5;
  18300. * ```
  18301. *
  18302. * @augments Object3D
  18303. */
  18304. class Bone extends Object3D {
  18305. /**
  18306. * Constructs a new bone.
  18307. */
  18308. constructor() {
  18309. super();
  18310. /**
  18311. * This flag can be used for type testing.
  18312. *
  18313. * @type {boolean}
  18314. * @readonly
  18315. * @default true
  18316. */
  18317. this.isBone = true;
  18318. this.type = 'Bone';
  18319. }
  18320. }
  18321. /**
  18322. * Creates a texture directly from raw buffer data.
  18323. *
  18324. * The interpretation of the data depends on type and format: If the type is
  18325. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18326. * texel data. If the format is `RGBAFormat`, data needs four values for
  18327. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18328. *
  18329. * @augments Texture
  18330. */
  18331. class DataTexture extends Texture {
  18332. /**
  18333. * Constructs a new data texture.
  18334. *
  18335. * @param {?TypedArray} [data=null] - The buffer data.
  18336. * @param {number} [width=1] - The width of the texture.
  18337. * @param {number} [height=1] - The height of the texture.
  18338. * @param {number} [format=RGBAFormat] - The texture format.
  18339. * @param {number} [type=UnsignedByteType] - The texture type.
  18340. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18341. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18342. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18343. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18344. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18345. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18346. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18347. */
  18348. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18349. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18350. /**
  18351. * This flag can be used for type testing.
  18352. *
  18353. * @type {boolean}
  18354. * @readonly
  18355. * @default true
  18356. */
  18357. this.isDataTexture = true;
  18358. /**
  18359. * The image definition of a data texture.
  18360. *
  18361. * @type {{data:TypedArray,width:number,height:number}}
  18362. */
  18363. this.image = { data: data, width: width, height: height };
  18364. /**
  18365. * Whether to generate mipmaps (if possible) for a texture.
  18366. *
  18367. * Overwritten and set to `false` by default.
  18368. *
  18369. * @type {boolean}
  18370. * @default false
  18371. */
  18372. this.generateMipmaps = false;
  18373. /**
  18374. * If set to `true`, the texture is flipped along the vertical axis when
  18375. * uploaded to the GPU.
  18376. *
  18377. * Overwritten and set to `false` by default.
  18378. *
  18379. * @type {boolean}
  18380. * @default false
  18381. */
  18382. this.flipY = false;
  18383. /**
  18384. * Specifies the alignment requirements for the start of each pixel row in memory.
  18385. *
  18386. * Overwritten and set to `1` by default.
  18387. *
  18388. * @type {boolean}
  18389. * @default 1
  18390. */
  18391. this.unpackAlignment = 1;
  18392. }
  18393. }
  18394. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18395. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18396. /**
  18397. * Class for representing the armatures in `three.js`. The skeleton
  18398. * is defined by a hierarchy of bones.
  18399. *
  18400. * ```js
  18401. * const bones = [];
  18402. *
  18403. * const shoulder = new THREE.Bone();
  18404. * const elbow = new THREE.Bone();
  18405. * const hand = new THREE.Bone();
  18406. *
  18407. * shoulder.add( elbow );
  18408. * elbow.add( hand );
  18409. *
  18410. * bones.push( shoulder , elbow, hand);
  18411. *
  18412. * shoulder.position.y = -5;
  18413. * elbow.position.y = 0;
  18414. * hand.position.y = 5;
  18415. *
  18416. * const armSkeleton = new THREE.Skeleton( bones );
  18417. * ```
  18418. */
  18419. class Skeleton {
  18420. /**
  18421. * Constructs a new skeleton.
  18422. *
  18423. * @param {Array<Bone>} [bones] - An array of bones.
  18424. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18425. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18426. */
  18427. constructor( bones = [], boneInverses = [] ) {
  18428. this.uuid = generateUUID();
  18429. /**
  18430. * An array of bones defining the skeleton.
  18431. *
  18432. * @type {Array<Bone>}
  18433. */
  18434. this.bones = bones.slice( 0 );
  18435. /**
  18436. * An array of bone inverse matrices.
  18437. *
  18438. * @type {Array<Matrix4>}
  18439. */
  18440. this.boneInverses = boneInverses;
  18441. /**
  18442. * An array buffer holding the bone data.
  18443. * Input data for {@link Skeleton#boneTexture}.
  18444. *
  18445. * @type {?Float32Array}
  18446. * @default null
  18447. */
  18448. this.boneMatrices = null;
  18449. /**
  18450. * A texture holding the bone data for use
  18451. * in the vertex shader.
  18452. *
  18453. * @type {?DataTexture}
  18454. * @default null
  18455. */
  18456. this.boneTexture = null;
  18457. this.init();
  18458. }
  18459. /**
  18460. * Initializes the skeleton. This method gets automatically called by the constructor
  18461. * but depending on how the skeleton is created it might be necessary to call this method
  18462. * manually.
  18463. */
  18464. init() {
  18465. const bones = this.bones;
  18466. const boneInverses = this.boneInverses;
  18467. this.boneMatrices = new Float32Array( bones.length * 16 );
  18468. // calculate inverse bone matrices if necessary
  18469. if ( boneInverses.length === 0 ) {
  18470. this.calculateInverses();
  18471. } else {
  18472. // handle special case
  18473. if ( bones.length !== boneInverses.length ) {
  18474. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18475. this.boneInverses = [];
  18476. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18477. this.boneInverses.push( new Matrix4() );
  18478. }
  18479. }
  18480. }
  18481. }
  18482. /**
  18483. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18484. * and fills it with new matrices.
  18485. */
  18486. calculateInverses() {
  18487. this.boneInverses.length = 0;
  18488. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18489. const inverse = new Matrix4();
  18490. if ( this.bones[ i ] ) {
  18491. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18492. }
  18493. this.boneInverses.push( inverse );
  18494. }
  18495. }
  18496. /**
  18497. * Resets the skeleton to the base pose.
  18498. */
  18499. pose() {
  18500. // recover the bind-time world matrices
  18501. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18502. const bone = this.bones[ i ];
  18503. if ( bone ) {
  18504. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18505. }
  18506. }
  18507. // compute the local matrices, positions, rotations and scales
  18508. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18509. const bone = this.bones[ i ];
  18510. if ( bone ) {
  18511. if ( bone.parent && bone.parent.isBone ) {
  18512. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18513. bone.matrix.multiply( bone.matrixWorld );
  18514. } else {
  18515. bone.matrix.copy( bone.matrixWorld );
  18516. }
  18517. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18518. }
  18519. }
  18520. }
  18521. /**
  18522. * Resets the skeleton to the base pose.
  18523. */
  18524. update() {
  18525. const bones = this.bones;
  18526. const boneInverses = this.boneInverses;
  18527. const boneMatrices = this.boneMatrices;
  18528. const boneTexture = this.boneTexture;
  18529. // flatten bone matrices to array
  18530. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18531. // compute the offset between the current and the original transform
  18532. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18533. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18534. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18535. }
  18536. if ( boneTexture !== null ) {
  18537. boneTexture.needsUpdate = true;
  18538. }
  18539. }
  18540. /**
  18541. * Returns a new skeleton with copied values from this instance.
  18542. *
  18543. * @return {Skeleton} A clone of this instance.
  18544. */
  18545. clone() {
  18546. return new Skeleton( this.bones, this.boneInverses );
  18547. }
  18548. /**
  18549. * Computes a data texture for passing bone data to the vertex shader.
  18550. *
  18551. * @return {Skeleton} A reference of this instance.
  18552. */
  18553. computeBoneTexture() {
  18554. // layout (1 matrix = 4 pixels)
  18555. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18556. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18557. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18558. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18559. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18560. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18561. size = Math.ceil( size / 4 ) * 4;
  18562. size = Math.max( size, 4 );
  18563. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18564. boneMatrices.set( this.boneMatrices ); // copy current values
  18565. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18566. boneTexture.needsUpdate = true;
  18567. this.boneMatrices = boneMatrices;
  18568. this.boneTexture = boneTexture;
  18569. return this;
  18570. }
  18571. /**
  18572. * Searches through the skeleton's bone array and returns the first with a
  18573. * matching name.
  18574. *
  18575. * @param {string} name - The name of the bone.
  18576. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18577. */
  18578. getBoneByName( name ) {
  18579. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18580. const bone = this.bones[ i ];
  18581. if ( bone.name === name ) {
  18582. return bone;
  18583. }
  18584. }
  18585. return undefined;
  18586. }
  18587. /**
  18588. * Frees the GPU-related resources allocated by this instance. Call this
  18589. * method whenever this instance is no longer used in your app.
  18590. */
  18591. dispose( ) {
  18592. if ( this.boneTexture !== null ) {
  18593. this.boneTexture.dispose();
  18594. this.boneTexture = null;
  18595. }
  18596. }
  18597. /**
  18598. * Setups the skeleton by the given JSON and bones.
  18599. *
  18600. * @param {Object} json - The skeleton as serialized JSON.
  18601. * @param {Object<string, Bone>} bones - An array of bones.
  18602. * @return {Skeleton} A reference of this instance.
  18603. */
  18604. fromJSON( json, bones ) {
  18605. this.uuid = json.uuid;
  18606. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18607. const uuid = json.bones[ i ];
  18608. let bone = bones[ uuid ];
  18609. if ( bone === undefined ) {
  18610. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18611. bone = new Bone();
  18612. }
  18613. this.bones.push( bone );
  18614. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18615. }
  18616. this.init();
  18617. return this;
  18618. }
  18619. /**
  18620. * Serializes the skeleton into JSON.
  18621. *
  18622. * @return {Object} A JSON object representing the serialized skeleton.
  18623. * @see {@link ObjectLoader#parse}
  18624. */
  18625. toJSON() {
  18626. const data = {
  18627. metadata: {
  18628. version: 4.6,
  18629. type: 'Skeleton',
  18630. generator: 'Skeleton.toJSON'
  18631. },
  18632. bones: [],
  18633. boneInverses: []
  18634. };
  18635. data.uuid = this.uuid;
  18636. const bones = this.bones;
  18637. const boneInverses = this.boneInverses;
  18638. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18639. const bone = bones[ i ];
  18640. data.bones.push( bone.uuid );
  18641. const boneInverse = boneInverses[ i ];
  18642. data.boneInverses.push( boneInverse.toArray() );
  18643. }
  18644. return data;
  18645. }
  18646. }
  18647. /**
  18648. * An instanced version of a buffer attribute.
  18649. *
  18650. * @augments BufferAttribute
  18651. */
  18652. class InstancedBufferAttribute extends BufferAttribute {
  18653. /**
  18654. * Constructs a new instanced buffer attribute.
  18655. *
  18656. * @param {TypedArray} array - The array holding the attribute data.
  18657. * @param {number} itemSize - The item size.
  18658. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18659. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18660. */
  18661. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18662. super( array, itemSize, normalized );
  18663. /**
  18664. * This flag can be used for type testing.
  18665. *
  18666. * @type {boolean}
  18667. * @readonly
  18668. * @default true
  18669. */
  18670. this.isInstancedBufferAttribute = true;
  18671. /**
  18672. * Defines how often a value of this buffer attribute should be repeated. A
  18673. * value of one means that each value of the instanced attribute is used for
  18674. * a single instance. A value of two means that each value is used for two
  18675. * consecutive instances (and so on).
  18676. *
  18677. * @type {number}
  18678. * @default 1
  18679. */
  18680. this.meshPerAttribute = meshPerAttribute;
  18681. }
  18682. copy( source ) {
  18683. super.copy( source );
  18684. this.meshPerAttribute = source.meshPerAttribute;
  18685. return this;
  18686. }
  18687. toJSON() {
  18688. const data = super.toJSON();
  18689. data.meshPerAttribute = this.meshPerAttribute;
  18690. data.isInstancedBufferAttribute = true;
  18691. return data;
  18692. }
  18693. }
  18694. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18695. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18696. const _instanceIntersects = [];
  18697. const _box3 = /*@__PURE__*/ new Box3();
  18698. const _identity = /*@__PURE__*/ new Matrix4();
  18699. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18700. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18701. /**
  18702. * A special version of a mesh with instanced rendering support. Use
  18703. * this class if you have to render a large number of objects with the same
  18704. * geometry and material(s) but with different world transformations. The usage
  18705. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18706. * improve the overall rendering performance in your application.
  18707. *
  18708. * @augments Mesh
  18709. */
  18710. class InstancedMesh extends Mesh {
  18711. /**
  18712. * Constructs a new instanced mesh.
  18713. *
  18714. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18715. * @param {Material|Array<Material>} [material] - The mesh material.
  18716. * @param {number} count - The number of instances.
  18717. */
  18718. constructor( geometry, material, count ) {
  18719. super( geometry, material );
  18720. /**
  18721. * This flag can be used for type testing.
  18722. *
  18723. * @type {boolean}
  18724. * @readonly
  18725. * @default true
  18726. */
  18727. this.isInstancedMesh = true;
  18728. /**
  18729. * Represents the local transformation of all instances. You have to set its
  18730. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18731. * via {@link InstancedMesh#setMatrixAt}.
  18732. *
  18733. * @type {InstancedBufferAttribute}
  18734. */
  18735. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18736. /**
  18737. * Represents the color of all instances. You have to set its
  18738. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18739. * via {@link InstancedMesh#setColorAt}.
  18740. *
  18741. * @type {?InstancedBufferAttribute}
  18742. * @default null
  18743. */
  18744. this.instanceColor = null;
  18745. /**
  18746. * Represents the morph target weights of all instances. You have to set its
  18747. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18748. * via {@link InstancedMesh#setMorphAt}.
  18749. *
  18750. * @type {?DataTexture}
  18751. * @default null
  18752. */
  18753. this.morphTexture = null;
  18754. /**
  18755. * The number of instances.
  18756. *
  18757. * @type {number}
  18758. */
  18759. this.count = count;
  18760. /**
  18761. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18762. *
  18763. * @type {?Box3}
  18764. * @default null
  18765. */
  18766. this.boundingBox = null;
  18767. /**
  18768. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18769. *
  18770. * @type {?Sphere}
  18771. * @default null
  18772. */
  18773. this.boundingSphere = null;
  18774. for ( let i = 0; i < count; i ++ ) {
  18775. this.setMatrixAt( i, _identity );
  18776. }
  18777. }
  18778. /**
  18779. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18780. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18781. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18782. */
  18783. computeBoundingBox() {
  18784. const geometry = this.geometry;
  18785. const count = this.count;
  18786. if ( this.boundingBox === null ) {
  18787. this.boundingBox = new Box3();
  18788. }
  18789. if ( geometry.boundingBox === null ) {
  18790. geometry.computeBoundingBox();
  18791. }
  18792. this.boundingBox.makeEmpty();
  18793. for ( let i = 0; i < count; i ++ ) {
  18794. this.getMatrixAt( i, _instanceLocalMatrix );
  18795. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18796. this.boundingBox.union( _box3 );
  18797. }
  18798. }
  18799. /**
  18800. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18801. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18802. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18803. */
  18804. computeBoundingSphere() {
  18805. const geometry = this.geometry;
  18806. const count = this.count;
  18807. if ( this.boundingSphere === null ) {
  18808. this.boundingSphere = new Sphere();
  18809. }
  18810. if ( geometry.boundingSphere === null ) {
  18811. geometry.computeBoundingSphere();
  18812. }
  18813. this.boundingSphere.makeEmpty();
  18814. for ( let i = 0; i < count; i ++ ) {
  18815. this.getMatrixAt( i, _instanceLocalMatrix );
  18816. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18817. this.boundingSphere.union( _sphere$4 );
  18818. }
  18819. }
  18820. copy( source, recursive ) {
  18821. super.copy( source, recursive );
  18822. this.instanceMatrix.copy( source.instanceMatrix );
  18823. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18824. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18825. this.count = source.count;
  18826. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18827. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18828. return this;
  18829. }
  18830. /**
  18831. * Gets the color of the defined instance.
  18832. *
  18833. * @param {number} index - The instance index.
  18834. * @param {Color} color - The target object that is used to store the method's result.
  18835. */
  18836. getColorAt( index, color ) {
  18837. color.fromArray( this.instanceColor.array, index * 3 );
  18838. }
  18839. /**
  18840. * Gets the local transformation matrix of the defined instance.
  18841. *
  18842. * @param {number} index - The instance index.
  18843. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18844. */
  18845. getMatrixAt( index, matrix ) {
  18846. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18847. }
  18848. /**
  18849. * Gets the morph target weights of the defined instance.
  18850. *
  18851. * @param {number} index - The instance index.
  18852. * @param {Mesh} object - The target object that is used to store the method's result.
  18853. */
  18854. getMorphAt( index, object ) {
  18855. const objectInfluences = object.morphTargetInfluences;
  18856. const array = this.morphTexture.source.data.data;
  18857. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18858. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18859. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18860. objectInfluences[ i ] = array[ dataIndex + i ];
  18861. }
  18862. }
  18863. raycast( raycaster, intersects ) {
  18864. const matrixWorld = this.matrixWorld;
  18865. const raycastTimes = this.count;
  18866. _mesh$1.geometry = this.geometry;
  18867. _mesh$1.material = this.material;
  18868. if ( _mesh$1.material === undefined ) return;
  18869. // test with bounding sphere first
  18870. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18871. _sphere$4.copy( this.boundingSphere );
  18872. _sphere$4.applyMatrix4( matrixWorld );
  18873. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18874. // now test each instance
  18875. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18876. // calculate the world matrix for each instance
  18877. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18878. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18879. // the mesh represents this single instance
  18880. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18881. _mesh$1.raycast( raycaster, _instanceIntersects );
  18882. // process the result of raycast
  18883. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18884. const intersect = _instanceIntersects[ i ];
  18885. intersect.instanceId = instanceId;
  18886. intersect.object = this;
  18887. intersects.push( intersect );
  18888. }
  18889. _instanceIntersects.length = 0;
  18890. }
  18891. }
  18892. /**
  18893. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18894. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18895. *
  18896. * @param {number} index - The instance index.
  18897. * @param {Color} color - The instance color.
  18898. */
  18899. setColorAt( index, color ) {
  18900. if ( this.instanceColor === null ) {
  18901. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18902. }
  18903. color.toArray( this.instanceColor.array, index * 3 );
  18904. }
  18905. /**
  18906. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18907. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  18908. *
  18909. * @param {number} index - The instance index.
  18910. * @param {Matrix4} matrix - The the local transformation.
  18911. */
  18912. setMatrixAt( index, matrix ) {
  18913. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18914. }
  18915. /**
  18916. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18917. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18918. *
  18919. * @param {number} index - The instance index.
  18920. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18921. * of a single instance.
  18922. */
  18923. setMorphAt( index, object ) {
  18924. const objectInfluences = object.morphTargetInfluences;
  18925. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18926. if ( this.morphTexture === null ) {
  18927. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18928. }
  18929. const array = this.morphTexture.source.data.data;
  18930. let morphInfluencesSum = 0;
  18931. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18932. morphInfluencesSum += objectInfluences[ i ];
  18933. }
  18934. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18935. const dataIndex = len * index;
  18936. array[ dataIndex ] = morphBaseInfluence;
  18937. array.set( objectInfluences, dataIndex + 1 );
  18938. }
  18939. updateMorphTargets() {
  18940. }
  18941. /**
  18942. * Frees the GPU-related resources allocated by this instance. Call this
  18943. * method whenever this instance is no longer used in your app.
  18944. */
  18945. dispose() {
  18946. this.dispatchEvent( { type: 'dispose' } );
  18947. if ( this.morphTexture !== null ) {
  18948. this.morphTexture.dispose();
  18949. this.morphTexture = null;
  18950. }
  18951. }
  18952. }
  18953. const _vector1 = /*@__PURE__*/ new Vector3();
  18954. const _vector2 = /*@__PURE__*/ new Vector3();
  18955. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18956. /**
  18957. * A two dimensional surface that extends infinitely in 3D space, represented
  18958. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  18959. * by a unit length normal vector and a constant.
  18960. */
  18961. class Plane {
  18962. /**
  18963. * Constructs a new plane.
  18964. *
  18965. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18966. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18967. */
  18968. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18969. /**
  18970. * This flag can be used for type testing.
  18971. *
  18972. * @type {boolean}
  18973. * @readonly
  18974. * @default true
  18975. */
  18976. this.isPlane = true;
  18977. /**
  18978. * A unit length vector defining the normal of the plane.
  18979. *
  18980. * @type {Vector3}
  18981. */
  18982. this.normal = normal;
  18983. /**
  18984. * The signed distance from the origin to the plane.
  18985. *
  18986. * @type {number}
  18987. * @default 0
  18988. */
  18989. this.constant = constant;
  18990. }
  18991. /**
  18992. * Sets the plane components by copying the given values.
  18993. *
  18994. * @param {Vector3} normal - The normal.
  18995. * @param {number} constant - The constant.
  18996. * @return {Plane} A reference to this plane.
  18997. */
  18998. set( normal, constant ) {
  18999. this.normal.copy( normal );
  19000. this.constant = constant;
  19001. return this;
  19002. }
  19003. /**
  19004. * Sets the plane components by defining `x`, `y`, `z` as the
  19005. * plane normal and `w` as the constant.
  19006. *
  19007. * @param {number} x - The value for the normal's x component.
  19008. * @param {number} y - The value for the normal's y component.
  19009. * @param {number} z - The value for the normal's z component.
  19010. * @param {number} w - The constant value.
  19011. * @return {Plane} A reference to this plane.
  19012. */
  19013. setComponents( x, y, z, w ) {
  19014. this.normal.set( x, y, z );
  19015. this.constant = w;
  19016. return this;
  19017. }
  19018. /**
  19019. * Sets the plane from the given normal and coplanar point (that is a point
  19020. * that lies onto the plane).
  19021. *
  19022. * @param {Vector3} normal - The normal.
  19023. * @param {Vector3} point - A coplanar point.
  19024. * @return {Plane} A reference to this plane.
  19025. */
  19026. setFromNormalAndCoplanarPoint( normal, point ) {
  19027. this.normal.copy( normal );
  19028. this.constant = - point.dot( this.normal );
  19029. return this;
  19030. }
  19031. /**
  19032. * Sets the plane from three coplanar points. The winding order is
  19033. * assumed to be counter-clockwise, and determines the direction of
  19034. * the plane normal.
  19035. *
  19036. * @param {Vector3} a - The first coplanar point.
  19037. * @param {Vector3} b - The second coplanar point.
  19038. * @param {Vector3} c - The third coplanar point.
  19039. * @return {Plane} A reference to this plane.
  19040. */
  19041. setFromCoplanarPoints( a, b, c ) {
  19042. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19043. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19044. this.setFromNormalAndCoplanarPoint( normal, a );
  19045. return this;
  19046. }
  19047. /**
  19048. * Copies the values of the given plane to this instance.
  19049. *
  19050. * @param {Plane} plane - The plane to copy.
  19051. * @return {Plane} A reference to this plane.
  19052. */
  19053. copy( plane ) {
  19054. this.normal.copy( plane.normal );
  19055. this.constant = plane.constant;
  19056. return this;
  19057. }
  19058. /**
  19059. * Normalizes the plane normal and adjusts the constant accordingly.
  19060. *
  19061. * @return {Plane} A reference to this plane.
  19062. */
  19063. normalize() {
  19064. // Note: will lead to a divide by zero if the plane is invalid.
  19065. const inverseNormalLength = 1.0 / this.normal.length();
  19066. this.normal.multiplyScalar( inverseNormalLength );
  19067. this.constant *= inverseNormalLength;
  19068. return this;
  19069. }
  19070. /**
  19071. * Negates both the plane normal and the constant.
  19072. *
  19073. * @return {Plane} A reference to this plane.
  19074. */
  19075. negate() {
  19076. this.constant *= - 1;
  19077. this.normal.negate();
  19078. return this;
  19079. }
  19080. /**
  19081. * Returns the signed distance from the given point to this plane.
  19082. *
  19083. * @param {Vector3} point - The point to compute the distance for.
  19084. * @return {number} The signed distance.
  19085. */
  19086. distanceToPoint( point ) {
  19087. return this.normal.dot( point ) + this.constant;
  19088. }
  19089. /**
  19090. * Returns the signed distance from the given sphere to this plane.
  19091. *
  19092. * @param {Sphere} sphere - The sphere to compute the distance for.
  19093. * @return {number} The signed distance.
  19094. */
  19095. distanceToSphere( sphere ) {
  19096. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19097. }
  19098. /**
  19099. * Projects a the given point onto the plane.
  19100. *
  19101. * @param {Vector3} point - The point to project.
  19102. * @param {Vector3} target - The target vector that is used to store the method's result.
  19103. * @return {Vector3} The projected point on the plane.
  19104. */
  19105. projectPoint( point, target ) {
  19106. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19107. }
  19108. /**
  19109. * Returns the intersection point of the passed line and the plane. Returns
  19110. * `null` if the line does not intersect. Returns the line's starting point if
  19111. * the line is coplanar with the plane.
  19112. *
  19113. * @param {Line3} line - The line to compute the intersection for.
  19114. * @param {Vector3} target - The target vector that is used to store the method's result.
  19115. * @return {?Vector3} The intersection point.
  19116. */
  19117. intersectLine( line, target ) {
  19118. const direction = line.delta( _vector1 );
  19119. const denominator = this.normal.dot( direction );
  19120. if ( denominator === 0 ) {
  19121. // line is coplanar, return origin
  19122. if ( this.distanceToPoint( line.start ) === 0 ) {
  19123. return target.copy( line.start );
  19124. }
  19125. // Unsure if this is the correct method to handle this case.
  19126. return null;
  19127. }
  19128. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19129. if ( t < 0 || t > 1 ) {
  19130. return null;
  19131. }
  19132. return target.copy( line.start ).addScaledVector( direction, t );
  19133. }
  19134. /**
  19135. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19136. *
  19137. * @param {Line3} line - The line to test.
  19138. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19139. */
  19140. intersectsLine( line ) {
  19141. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19142. const startSign = this.distanceToPoint( line.start );
  19143. const endSign = this.distanceToPoint( line.end );
  19144. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19145. }
  19146. /**
  19147. * Returns `true` if the given bounding box intersects with the plane.
  19148. *
  19149. * @param {Box3} box - The bounding box to test.
  19150. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19151. */
  19152. intersectsBox( box ) {
  19153. return box.intersectsPlane( this );
  19154. }
  19155. /**
  19156. * Returns `true` if the given bounding sphere intersects with the plane.
  19157. *
  19158. * @param {Sphere} sphere - The bounding sphere to test.
  19159. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19160. */
  19161. intersectsSphere( sphere ) {
  19162. return sphere.intersectsPlane( this );
  19163. }
  19164. /**
  19165. * Returns a coplanar vector to the plane, by calculating the
  19166. * projection of the normal at the origin onto the plane.
  19167. *
  19168. * @param {Vector3} target - The target vector that is used to store the method's result.
  19169. * @return {Vector3} The coplanar point.
  19170. */
  19171. coplanarPoint( target ) {
  19172. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19173. }
  19174. /**
  19175. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19176. *
  19177. * The optional normal matrix can be pre-computed like so:
  19178. * ```js
  19179. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19180. * ```
  19181. *
  19182. * @param {Matrix4} matrix - The transformation matrix.
  19183. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19184. * @return {Plane} A reference to this plane.
  19185. */
  19186. applyMatrix4( matrix, optionalNormalMatrix ) {
  19187. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19188. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19189. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19190. this.constant = - referencePoint.dot( normal );
  19191. return this;
  19192. }
  19193. /**
  19194. * Translates the plane by the distance defined by the given offset vector.
  19195. * Note that this only affects the plane constant and will not affect the normal vector.
  19196. *
  19197. * @param {Vector3} offset - The offset vector.
  19198. * @return {Plane} A reference to this plane.
  19199. */
  19200. translate( offset ) {
  19201. this.constant -= offset.dot( this.normal );
  19202. return this;
  19203. }
  19204. /**
  19205. * Returns `true` if this plane is equal with the given one.
  19206. *
  19207. * @param {Plane} plane - The plane to test for equality.
  19208. * @return {boolean} Whether this plane is equal with the given one.
  19209. */
  19210. equals( plane ) {
  19211. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19212. }
  19213. /**
  19214. * Returns a new plane with copied values from this instance.
  19215. *
  19216. * @return {Plane} A clone of this instance.
  19217. */
  19218. clone() {
  19219. return new this.constructor().copy( this );
  19220. }
  19221. }
  19222. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19223. const _vector$6 = /*@__PURE__*/ new Vector3();
  19224. /**
  19225. * Frustums are used to determine what is inside the camera's field of view.
  19226. * They help speed up the rendering process - objects which lie outside a camera's
  19227. * frustum can safely be excluded from rendering.
  19228. *
  19229. * This class is mainly intended for use internally by a renderer.
  19230. */
  19231. class Frustum {
  19232. /**
  19233. * Constructs a new frustum.
  19234. *
  19235. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19236. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19237. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19238. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19239. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19240. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19241. */
  19242. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19243. /**
  19244. * This array holds the planes that enclose the frustum.
  19245. *
  19246. * @type {Array<Plane>}
  19247. */
  19248. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19249. }
  19250. /**
  19251. * Sets the frustum planes by copying the given planes.
  19252. *
  19253. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19254. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19255. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19256. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19257. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19258. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19259. * @return {Frustum} A reference to this frustum.
  19260. */
  19261. set( p0, p1, p2, p3, p4, p5 ) {
  19262. const planes = this.planes;
  19263. planes[ 0 ].copy( p0 );
  19264. planes[ 1 ].copy( p1 );
  19265. planes[ 2 ].copy( p2 );
  19266. planes[ 3 ].copy( p3 );
  19267. planes[ 4 ].copy( p4 );
  19268. planes[ 5 ].copy( p5 );
  19269. return this;
  19270. }
  19271. /**
  19272. * Copies the values of the given frustum to this instance.
  19273. *
  19274. * @param {Frustum} frustum - The frustum to copy.
  19275. * @return {Frustum} A reference to this frustum.
  19276. */
  19277. copy( frustum ) {
  19278. const planes = this.planes;
  19279. for ( let i = 0; i < 6; i ++ ) {
  19280. planes[ i ].copy( frustum.planes[ i ] );
  19281. }
  19282. return this;
  19283. }
  19284. /**
  19285. * Sets the frustum planes from the given projection matrix.
  19286. *
  19287. * @param {Matrix4} m - The projection matrix.
  19288. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19289. * @return {Frustum} A reference to this frustum.
  19290. */
  19291. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  19292. const planes = this.planes;
  19293. const me = m.elements;
  19294. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19295. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19296. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19297. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19298. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19299. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19300. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19301. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19302. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  19303. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19304. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  19305. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19306. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  19307. } else {
  19308. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19309. }
  19310. return this;
  19311. }
  19312. /**
  19313. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19314. *
  19315. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19316. *
  19317. * @param {Object3D} object - The 3D object to test.
  19318. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19319. */
  19320. intersectsObject( object ) {
  19321. if ( object.boundingSphere !== undefined ) {
  19322. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19323. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19324. } else {
  19325. const geometry = object.geometry;
  19326. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19327. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19328. }
  19329. return this.intersectsSphere( _sphere$3 );
  19330. }
  19331. /**
  19332. * Returns `true` if the given sprite is intersecting this frustum.
  19333. *
  19334. * @param {Sprite} sprite - The sprite to test.
  19335. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19336. */
  19337. intersectsSprite( sprite ) {
  19338. _sphere$3.center.set( 0, 0, 0 );
  19339. _sphere$3.radius = 0.7071067811865476;
  19340. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19341. return this.intersectsSphere( _sphere$3 );
  19342. }
  19343. /**
  19344. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19345. *
  19346. * @param {Sphere} sphere - The bounding sphere to test.
  19347. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19348. */
  19349. intersectsSphere( sphere ) {
  19350. const planes = this.planes;
  19351. const center = sphere.center;
  19352. const negRadius = - sphere.radius;
  19353. for ( let i = 0; i < 6; i ++ ) {
  19354. const distance = planes[ i ].distanceToPoint( center );
  19355. if ( distance < negRadius ) {
  19356. return false;
  19357. }
  19358. }
  19359. return true;
  19360. }
  19361. /**
  19362. * Returns `true` if the given bounding box is intersecting this frustum.
  19363. *
  19364. * @param {Box3} box - The bounding box to test.
  19365. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19366. */
  19367. intersectsBox( box ) {
  19368. const planes = this.planes;
  19369. for ( let i = 0; i < 6; i ++ ) {
  19370. const plane = planes[ i ];
  19371. // corner at max distance
  19372. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19373. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19374. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19375. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19376. return false;
  19377. }
  19378. }
  19379. return true;
  19380. }
  19381. /**
  19382. * Returns `true` if the given point lies within the frustum.
  19383. *
  19384. * @param {Vector3} point - The point to test.
  19385. * @return {boolean} Whether the point lies within this frustum or not.
  19386. */
  19387. containsPoint( point ) {
  19388. const planes = this.planes;
  19389. for ( let i = 0; i < 6; i ++ ) {
  19390. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19391. return false;
  19392. }
  19393. }
  19394. return true;
  19395. }
  19396. /**
  19397. * Returns a new frustum with copied values from this instance.
  19398. *
  19399. * @return {Frustum} A clone of this instance.
  19400. */
  19401. clone() {
  19402. return new this.constructor().copy( this );
  19403. }
  19404. }
  19405. function ascIdSort( a, b ) {
  19406. return a - b;
  19407. }
  19408. function sortOpaque( a, b ) {
  19409. return a.z - b.z;
  19410. }
  19411. function sortTransparent( a, b ) {
  19412. return b.z - a.z;
  19413. }
  19414. class MultiDrawRenderList {
  19415. constructor() {
  19416. this.index = 0;
  19417. this.pool = [];
  19418. this.list = [];
  19419. }
  19420. push( start, count, z, index ) {
  19421. const pool = this.pool;
  19422. const list = this.list;
  19423. if ( this.index >= pool.length ) {
  19424. pool.push( {
  19425. start: - 1,
  19426. count: - 1,
  19427. z: - 1,
  19428. index: - 1,
  19429. } );
  19430. }
  19431. const item = pool[ this.index ];
  19432. list.push( item );
  19433. this.index ++;
  19434. item.start = start;
  19435. item.count = count;
  19436. item.z = z;
  19437. item.index = index;
  19438. }
  19439. reset() {
  19440. this.list.length = 0;
  19441. this.index = 0;
  19442. }
  19443. }
  19444. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19445. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19446. const _frustum = /*@__PURE__*/ new Frustum();
  19447. const _box$1 = /*@__PURE__*/ new Box3();
  19448. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19449. const _vector$5 = /*@__PURE__*/ new Vector3();
  19450. const _forward = /*@__PURE__*/ new Vector3();
  19451. const _temp = /*@__PURE__*/ new Vector3();
  19452. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19453. const _mesh = /*@__PURE__*/ new Mesh();
  19454. const _batchIntersects = [];
  19455. // copies data from attribute "src" into "target" starting at "targetOffset"
  19456. function copyAttributeData( src, target, targetOffset = 0 ) {
  19457. const itemSize = target.itemSize;
  19458. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19459. // use the component getters and setters if the array data cannot
  19460. // be copied directly
  19461. const vertexCount = src.count;
  19462. for ( let i = 0; i < vertexCount; i ++ ) {
  19463. for ( let c = 0; c < itemSize; c ++ ) {
  19464. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19465. }
  19466. }
  19467. } else {
  19468. // faster copy approach using typed array set function
  19469. target.array.set( src.array, targetOffset * itemSize );
  19470. }
  19471. target.needsUpdate = true;
  19472. }
  19473. // safely copies array contents to a potentially smaller array
  19474. function copyArrayContents( src, target ) {
  19475. if ( src.constructor !== target.constructor ) {
  19476. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19477. const len = Math.min( src.length, target.length );
  19478. for ( let i = 0; i < len; i ++ ) {
  19479. target[ i ] = src[ i ];
  19480. }
  19481. } else {
  19482. // if the arrays use the same data layout we can use a fast block copy
  19483. const len = Math.min( src.length, target.length );
  19484. target.set( new src.constructor( src.buffer, 0, len ) );
  19485. }
  19486. }
  19487. /**
  19488. * A special version of a mesh with multi draw batch rendering support. Use
  19489. * this class if you have to render a large number of objects with the same
  19490. * material but with different geometries or world transformations. The usage of
  19491. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19492. * rendering performance in your application.
  19493. *
  19494. * ```js
  19495. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19496. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19497. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19498. *
  19499. * // initialize and add geometries into the batched mesh
  19500. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19501. * const boxGeometryId = batchedMesh.addGeometry( box );
  19502. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19503. *
  19504. * // create instances of those geometries
  19505. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19506. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19507. *
  19508. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19509. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19510. *
  19511. * // position the geometries
  19512. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19513. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19514. *
  19515. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19516. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19517. *
  19518. * scene.add( batchedMesh );
  19519. * ```
  19520. *
  19521. * @augments Mesh
  19522. */
  19523. class BatchedMesh extends Mesh {
  19524. /**
  19525. * Constructs a new batched mesh.
  19526. *
  19527. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19528. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19529. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19530. * @param {Material|Array<Material>} [material] - The mesh material.
  19531. */
  19532. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19533. super( new BufferGeometry(), material );
  19534. /**
  19535. * This flag can be used for type testing.
  19536. *
  19537. * @type {boolean}
  19538. * @readonly
  19539. * @default true
  19540. */
  19541. this.isBatchedMesh = true;
  19542. /**
  19543. * When set ot `true`, the individual objects of a batch are frustum culled.
  19544. *
  19545. * @type {boolean}
  19546. * @default true
  19547. */
  19548. this.perObjectFrustumCulled = true;
  19549. /**
  19550. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19551. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19552. * rendered front to back.
  19553. *
  19554. * @type {boolean}
  19555. * @default true
  19556. */
  19557. this.sortObjects = true;
  19558. /**
  19559. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19560. *
  19561. * @type {?Box3}
  19562. * @default null
  19563. */
  19564. this.boundingBox = null;
  19565. /**
  19566. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19567. *
  19568. * @type {?Sphere}
  19569. * @default null
  19570. */
  19571. this.boundingSphere = null;
  19572. /**
  19573. * Takes a sort a function that is run before render. The function takes a list of instances to
  19574. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19575. * sort with.
  19576. *
  19577. * @type {?Function}
  19578. * @default null
  19579. */
  19580. this.customSort = null;
  19581. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19582. this._instanceInfo = [];
  19583. this._geometryInfo = [];
  19584. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19585. this._availableInstanceIds = [];
  19586. this._availableGeometryIds = [];
  19587. // used to track where the next point is that geometry should be inserted
  19588. this._nextIndexStart = 0;
  19589. this._nextVertexStart = 0;
  19590. this._geometryCount = 0;
  19591. // flags
  19592. this._visibilityChanged = true;
  19593. this._geometryInitialized = false;
  19594. // cached user options
  19595. this._maxInstanceCount = maxInstanceCount;
  19596. this._maxVertexCount = maxVertexCount;
  19597. this._maxIndexCount = maxIndexCount;
  19598. // buffers for multi draw
  19599. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19600. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19601. this._multiDrawCount = 0;
  19602. this._multiDrawInstances = null;
  19603. // Local matrix per geometry by using data texture
  19604. this._matricesTexture = null;
  19605. this._indirectTexture = null;
  19606. this._colorsTexture = null;
  19607. this._initMatricesTexture();
  19608. this._initIndirectTexture();
  19609. }
  19610. /**
  19611. * The maximum number of individual instances that can be stored in the batch.
  19612. *
  19613. * @type {number}
  19614. * @readonly
  19615. */
  19616. get maxInstanceCount() {
  19617. return this._maxInstanceCount;
  19618. }
  19619. /**
  19620. * The instance count.
  19621. *
  19622. * @type {number}
  19623. * @readonly
  19624. */
  19625. get instanceCount() {
  19626. return this._instanceInfo.length - this._availableInstanceIds.length;
  19627. }
  19628. /**
  19629. * The number of unused vertices.
  19630. *
  19631. * @type {number}
  19632. * @readonly
  19633. */
  19634. get unusedVertexCount() {
  19635. return this._maxVertexCount - this._nextVertexStart;
  19636. }
  19637. /**
  19638. * The number of unused indices.
  19639. *
  19640. * @type {number}
  19641. * @readonly
  19642. */
  19643. get unusedIndexCount() {
  19644. return this._maxIndexCount - this._nextIndexStart;
  19645. }
  19646. _initMatricesTexture() {
  19647. // layout (1 matrix = 4 pixels)
  19648. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19649. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19650. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19651. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19652. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19653. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19654. size = Math.ceil( size / 4 ) * 4;
  19655. size = Math.max( size, 4 );
  19656. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19657. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19658. this._matricesTexture = matricesTexture;
  19659. }
  19660. _initIndirectTexture() {
  19661. let size = Math.sqrt( this._maxInstanceCount );
  19662. size = Math.ceil( size );
  19663. const indirectArray = new Uint32Array( size * size );
  19664. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19665. this._indirectTexture = indirectTexture;
  19666. }
  19667. _initColorsTexture() {
  19668. let size = Math.sqrt( this._maxInstanceCount );
  19669. size = Math.ceil( size );
  19670. // 4 floats per RGBA pixel initialized to white
  19671. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19672. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19673. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19674. this._colorsTexture = colorsTexture;
  19675. }
  19676. _initializeGeometry( reference ) {
  19677. const geometry = this.geometry;
  19678. const maxVertexCount = this._maxVertexCount;
  19679. const maxIndexCount = this._maxIndexCount;
  19680. if ( this._geometryInitialized === false ) {
  19681. for ( const attributeName in reference.attributes ) {
  19682. const srcAttribute = reference.getAttribute( attributeName );
  19683. const { array, itemSize, normalized } = srcAttribute;
  19684. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19685. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19686. geometry.setAttribute( attributeName, dstAttribute );
  19687. }
  19688. if ( reference.getIndex() !== null ) {
  19689. // Reserve last u16 index for primitive restart.
  19690. const indexArray = maxVertexCount > 65535
  19691. ? new Uint32Array( maxIndexCount )
  19692. : new Uint16Array( maxIndexCount );
  19693. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19694. }
  19695. this._geometryInitialized = true;
  19696. }
  19697. }
  19698. // Make sure the geometry is compatible with the existing combined geometry attributes
  19699. _validateGeometry( geometry ) {
  19700. // check to ensure the geometries are using consistent attributes and indices
  19701. const batchGeometry = this.geometry;
  19702. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19703. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19704. }
  19705. for ( const attributeName in batchGeometry.attributes ) {
  19706. if ( ! geometry.hasAttribute( attributeName ) ) {
  19707. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19708. }
  19709. const srcAttribute = geometry.getAttribute( attributeName );
  19710. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19711. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19712. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19713. }
  19714. }
  19715. }
  19716. /**
  19717. * Validates the instance defined by the given ID.
  19718. *
  19719. * @param {number} instanceId - The the instance to validate.
  19720. */
  19721. validateInstanceId( instanceId ) {
  19722. const instanceInfo = this._instanceInfo;
  19723. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19724. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19725. }
  19726. }
  19727. /**
  19728. * Validates the geometry defined by the given ID.
  19729. *
  19730. * @param {number} geometryId - The the geometry to validate.
  19731. */
  19732. validateGeometryId( geometryId ) {
  19733. const geometryInfoList = this._geometryInfo;
  19734. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19735. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19736. }
  19737. }
  19738. /**
  19739. * Takes a sort a function that is run before render. The function takes a list of instances to
  19740. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19741. *
  19742. * @param {Function} func - The custom sort function.
  19743. * @return {BatchedMesh} A reference to this batched mesh.
  19744. */
  19745. setCustomSort( func ) {
  19746. this.customSort = func;
  19747. return this;
  19748. }
  19749. /**
  19750. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19751. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19752. * otherwise they are `null`.
  19753. */
  19754. computeBoundingBox() {
  19755. if ( this.boundingBox === null ) {
  19756. this.boundingBox = new Box3();
  19757. }
  19758. const boundingBox = this.boundingBox;
  19759. const instanceInfo = this._instanceInfo;
  19760. boundingBox.makeEmpty();
  19761. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19762. if ( instanceInfo[ i ].active === false ) continue;
  19763. const geometryId = instanceInfo[ i ].geometryIndex;
  19764. this.getMatrixAt( i, _matrix$1 );
  19765. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19766. boundingBox.union( _box$1 );
  19767. }
  19768. }
  19769. /**
  19770. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19771. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19772. * otherwise they are `null`.
  19773. */
  19774. computeBoundingSphere() {
  19775. if ( this.boundingSphere === null ) {
  19776. this.boundingSphere = new Sphere();
  19777. }
  19778. const boundingSphere = this.boundingSphere;
  19779. const instanceInfo = this._instanceInfo;
  19780. boundingSphere.makeEmpty();
  19781. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19782. if ( instanceInfo[ i ].active === false ) continue;
  19783. const geometryId = instanceInfo[ i ].geometryIndex;
  19784. this.getMatrixAt( i, _matrix$1 );
  19785. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19786. boundingSphere.union( _sphere$2 );
  19787. }
  19788. }
  19789. /**
  19790. * Adds a new instance to the batch using the geometry of the given ID and returns
  19791. * a new id referring to the new instance to be used by other functions.
  19792. *
  19793. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19794. * @return {number} The instance ID.
  19795. */
  19796. addInstance( geometryId ) {
  19797. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19798. // ensure we're not over geometry
  19799. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19800. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19801. }
  19802. const instanceInfo = {
  19803. visible: true,
  19804. active: true,
  19805. geometryIndex: geometryId,
  19806. };
  19807. let drawId = null;
  19808. // Prioritize using previously freed instance ids
  19809. if ( this._availableInstanceIds.length > 0 ) {
  19810. this._availableInstanceIds.sort( ascIdSort );
  19811. drawId = this._availableInstanceIds.shift();
  19812. this._instanceInfo[ drawId ] = instanceInfo;
  19813. } else {
  19814. drawId = this._instanceInfo.length;
  19815. this._instanceInfo.push( instanceInfo );
  19816. }
  19817. const matricesTexture = this._matricesTexture;
  19818. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19819. matricesTexture.needsUpdate = true;
  19820. const colorsTexture = this._colorsTexture;
  19821. if ( colorsTexture ) {
  19822. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19823. colorsTexture.needsUpdate = true;
  19824. }
  19825. this._visibilityChanged = true;
  19826. return drawId;
  19827. }
  19828. /**
  19829. * Adds the given geometry to the batch and returns the associated
  19830. * geometry id referring to it to be used in other functions.
  19831. *
  19832. * @param {BufferGeometry} geometry - The geometry to add.
  19833. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19834. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19835. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19836. * Defaults to the length of the given geometry vertex buffer.
  19837. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19838. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19839. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19840. * the length of the given geometry index buffer.
  19841. * @return {number} The geometry ID.
  19842. */
  19843. addGeometry( geometry, reservedVertexCount = - 1, reservedIndexCount = - 1 ) {
  19844. this._initializeGeometry( geometry );
  19845. this._validateGeometry( geometry );
  19846. const geometryInfo = {
  19847. // geometry information
  19848. vertexStart: - 1,
  19849. vertexCount: - 1,
  19850. reservedVertexCount: - 1,
  19851. indexStart: - 1,
  19852. indexCount: - 1,
  19853. reservedIndexCount: - 1,
  19854. // draw range information
  19855. start: - 1,
  19856. count: - 1,
  19857. // state
  19858. boundingBox: null,
  19859. boundingSphere: null,
  19860. active: true,
  19861. };
  19862. const geometryInfoList = this._geometryInfo;
  19863. geometryInfo.vertexStart = this._nextVertexStart;
  19864. geometryInfo.reservedVertexCount = reservedVertexCount === - 1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19865. const index = geometry.getIndex();
  19866. const hasIndex = index !== null;
  19867. if ( hasIndex ) {
  19868. geometryInfo.indexStart = this._nextIndexStart;
  19869. geometryInfo.reservedIndexCount = reservedIndexCount === - 1 ? index.count : reservedIndexCount;
  19870. }
  19871. if (
  19872. geometryInfo.indexStart !== - 1 &&
  19873. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19874. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19875. ) {
  19876. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19877. }
  19878. // update id
  19879. let geometryId;
  19880. if ( this._availableGeometryIds.length > 0 ) {
  19881. this._availableGeometryIds.sort( ascIdSort );
  19882. geometryId = this._availableGeometryIds.shift();
  19883. geometryInfoList[ geometryId ] = geometryInfo;
  19884. } else {
  19885. geometryId = this._geometryCount;
  19886. this._geometryCount ++;
  19887. geometryInfoList.push( geometryInfo );
  19888. }
  19889. // update the geometry
  19890. this.setGeometryAt( geometryId, geometry );
  19891. // increment the next geometry position
  19892. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19893. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19894. return geometryId;
  19895. }
  19896. /**
  19897. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19898. * is not enough space reserved for geometry. Calling this will change all instances that are
  19899. * rendering that geometry.
  19900. *
  19901. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19902. * @param {BufferGeometry} geometry - The new geometry.
  19903. * @return {number} The geometry ID.
  19904. */
  19905. setGeometryAt( geometryId, geometry ) {
  19906. if ( geometryId >= this._geometryCount ) {
  19907. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19908. }
  19909. this._validateGeometry( geometry );
  19910. const batchGeometry = this.geometry;
  19911. const hasIndex = batchGeometry.getIndex() !== null;
  19912. const dstIndex = batchGeometry.getIndex();
  19913. const srcIndex = geometry.getIndex();
  19914. const geometryInfo = this._geometryInfo[ geometryId ];
  19915. if (
  19916. hasIndex &&
  19917. srcIndex.count > geometryInfo.reservedIndexCount ||
  19918. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19919. ) {
  19920. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19921. }
  19922. // copy geometry buffer data over
  19923. const vertexStart = geometryInfo.vertexStart;
  19924. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19925. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19926. for ( const attributeName in batchGeometry.attributes ) {
  19927. // copy attribute data
  19928. const srcAttribute = geometry.getAttribute( attributeName );
  19929. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19930. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19931. // fill the rest in with zeroes
  19932. const itemSize = srcAttribute.itemSize;
  19933. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19934. const index = vertexStart + i;
  19935. for ( let c = 0; c < itemSize; c ++ ) {
  19936. dstAttribute.setComponent( index, c, 0 );
  19937. }
  19938. }
  19939. dstAttribute.needsUpdate = true;
  19940. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19941. }
  19942. // copy index
  19943. if ( hasIndex ) {
  19944. const indexStart = geometryInfo.indexStart;
  19945. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19946. geometryInfo.indexCount = geometry.getIndex().count;
  19947. // copy index data over
  19948. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19949. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19950. }
  19951. // fill the rest in with zeroes
  19952. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19953. dstIndex.setX( indexStart + i, vertexStart );
  19954. }
  19955. dstIndex.needsUpdate = true;
  19956. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19957. }
  19958. // update the draw range
  19959. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19960. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19961. // store the bounding boxes
  19962. geometryInfo.boundingBox = null;
  19963. if ( geometry.boundingBox !== null ) {
  19964. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19965. }
  19966. geometryInfo.boundingSphere = null;
  19967. if ( geometry.boundingSphere !== null ) {
  19968. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19969. }
  19970. this._visibilityChanged = true;
  19971. return geometryId;
  19972. }
  19973. /**
  19974. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19975. * this geometry will also be removed as a side effect.
  19976. *
  19977. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19978. * @return {BatchedMesh} A reference to this batched mesh.
  19979. */
  19980. deleteGeometry( geometryId ) {
  19981. const geometryInfoList = this._geometryInfo;
  19982. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19983. return this;
  19984. }
  19985. // delete any instances associated with this geometry
  19986. const instanceInfo = this._instanceInfo;
  19987. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19988. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19989. this.deleteInstance( i );
  19990. }
  19991. }
  19992. geometryInfoList[ geometryId ].active = false;
  19993. this._availableGeometryIds.push( geometryId );
  19994. this._visibilityChanged = true;
  19995. return this;
  19996. }
  19997. /**
  19998. * Deletes an existing instance from the batch using the given ID.
  19999. *
  20000. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20001. * @return {BatchedMesh} A reference to this batched mesh.
  20002. */
  20003. deleteInstance( instanceId ) {
  20004. this.validateInstanceId( instanceId );
  20005. this._instanceInfo[ instanceId ].active = false;
  20006. this._availableInstanceIds.push( instanceId );
  20007. this._visibilityChanged = true;
  20008. return this;
  20009. }
  20010. /**
  20011. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20012. * previously deleted geometry, freeing up space to add new geometry.
  20013. *
  20014. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20015. * @return {BatchedMesh} A reference to this batched mesh.
  20016. */
  20017. optimize() {
  20018. // track the next indices to copy data to
  20019. let nextVertexStart = 0;
  20020. let nextIndexStart = 0;
  20021. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20022. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20023. const geometryInfoList = this._geometryInfo;
  20024. const indices = geometryInfoList
  20025. .map( ( e, i ) => i )
  20026. .sort( ( a, b ) => {
  20027. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20028. } );
  20029. const geometry = this.geometry;
  20030. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20031. // if a geometry range is inactive then don't copy anything
  20032. const index = indices[ i ];
  20033. const geometryInfo = geometryInfoList[ index ];
  20034. if ( geometryInfo.active === false ) {
  20035. continue;
  20036. }
  20037. // if a geometry contains an index buffer then shift it, as well
  20038. if ( geometry.index !== null ) {
  20039. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20040. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20041. const index = geometry.index;
  20042. const array = index.array;
  20043. // shift the index pointers based on how the vertex data will shift
  20044. // adjusting the index must happen first so the original vertex start value is available
  20045. const elementDelta = nextVertexStart - vertexStart;
  20046. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20047. array[ j ] = array[ j ] + elementDelta;
  20048. }
  20049. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20050. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20051. geometryInfo.indexStart = nextIndexStart;
  20052. }
  20053. nextIndexStart += geometryInfo.reservedIndexCount;
  20054. }
  20055. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20056. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20057. const { vertexStart, reservedVertexCount } = geometryInfo;
  20058. const attributes = geometry.attributes;
  20059. for ( const key in attributes ) {
  20060. const attribute = attributes[ key ];
  20061. const { array, itemSize } = attribute;
  20062. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20063. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20064. }
  20065. geometryInfo.vertexStart = nextVertexStart;
  20066. }
  20067. nextVertexStart += geometryInfo.reservedVertexCount;
  20068. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20069. // step the next geometry points to the shifted position
  20070. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20071. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20072. }
  20073. return this;
  20074. }
  20075. /**
  20076. * Returns the bounding box for the given geometry.
  20077. *
  20078. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20079. * @param {Box3} target - The target object that is used to store the method's result.
  20080. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20081. */
  20082. getBoundingBoxAt( geometryId, target ) {
  20083. if ( geometryId >= this._geometryCount ) {
  20084. return null;
  20085. }
  20086. // compute bounding box
  20087. const geometry = this.geometry;
  20088. const geometryInfo = this._geometryInfo[ geometryId ];
  20089. if ( geometryInfo.boundingBox === null ) {
  20090. const box = new Box3();
  20091. const index = geometry.index;
  20092. const position = geometry.attributes.position;
  20093. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20094. let iv = i;
  20095. if ( index ) {
  20096. iv = index.getX( iv );
  20097. }
  20098. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20099. }
  20100. geometryInfo.boundingBox = box;
  20101. }
  20102. target.copy( geometryInfo.boundingBox );
  20103. return target;
  20104. }
  20105. /**
  20106. * Returns the bounding sphere for the given geometry.
  20107. *
  20108. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20109. * @param {Sphere} target - The target object that is used to store the method's result.
  20110. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20111. */
  20112. getBoundingSphereAt( geometryId, target ) {
  20113. if ( geometryId >= this._geometryCount ) {
  20114. return null;
  20115. }
  20116. // compute bounding sphere
  20117. const geometry = this.geometry;
  20118. const geometryInfo = this._geometryInfo[ geometryId ];
  20119. if ( geometryInfo.boundingSphere === null ) {
  20120. const sphere = new Sphere();
  20121. this.getBoundingBoxAt( geometryId, _box$1 );
  20122. _box$1.getCenter( sphere.center );
  20123. const index = geometry.index;
  20124. const position = geometry.attributes.position;
  20125. let maxRadiusSq = 0;
  20126. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20127. let iv = i;
  20128. if ( index ) {
  20129. iv = index.getX( iv );
  20130. }
  20131. _vector$5.fromBufferAttribute( position, iv );
  20132. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20133. }
  20134. sphere.radius = Math.sqrt( maxRadiusSq );
  20135. geometryInfo.boundingSphere = sphere;
  20136. }
  20137. target.copy( geometryInfo.boundingSphere );
  20138. return target;
  20139. }
  20140. /**
  20141. * Sets the given local transformation matrix to the defined instance.
  20142. * Negatively scaled matrices are not supported.
  20143. *
  20144. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20145. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20146. * @return {BatchedMesh} A reference to this batched mesh.
  20147. */
  20148. setMatrixAt( instanceId, matrix ) {
  20149. this.validateInstanceId( instanceId );
  20150. const matricesTexture = this._matricesTexture;
  20151. const matricesArray = this._matricesTexture.image.data;
  20152. matrix.toArray( matricesArray, instanceId * 16 );
  20153. matricesTexture.needsUpdate = true;
  20154. return this;
  20155. }
  20156. /**
  20157. * Returns the local transformation matrix of the defined instance.
  20158. *
  20159. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20160. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20161. * @return {Matrix4} The instance's local transformation matrix.
  20162. */
  20163. getMatrixAt( instanceId, matrix ) {
  20164. this.validateInstanceId( instanceId );
  20165. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20166. }
  20167. /**
  20168. * Sets the given color to the defined instance.
  20169. *
  20170. * @param {number} instanceId - The ID of an instance to set the color of.
  20171. * @param {Color} color - The color to set the instance to.
  20172. * @return {BatchedMesh} A reference to this batched mesh.
  20173. */
  20174. setColorAt( instanceId, color ) {
  20175. this.validateInstanceId( instanceId );
  20176. if ( this._colorsTexture === null ) {
  20177. this._initColorsTexture();
  20178. }
  20179. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20180. this._colorsTexture.needsUpdate = true;
  20181. return this;
  20182. }
  20183. /**
  20184. * Returns the color of the defined instance.
  20185. *
  20186. * @param {number} instanceId - The ID of an instance to get the color of.
  20187. * @param {Color} color - The target object that is used to store the method's result.
  20188. * @return {Color} The instance's color.
  20189. */
  20190. getColorAt( instanceId, color ) {
  20191. this.validateInstanceId( instanceId );
  20192. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20193. }
  20194. /**
  20195. * Sets the visibility of the instance.
  20196. *
  20197. * @param {number} instanceId - The id of the instance to set the visibility of.
  20198. * @param {boolean} visible - Whether the instance is visible or not.
  20199. * @return {BatchedMesh} A reference to this batched mesh.
  20200. */
  20201. setVisibleAt( instanceId, visible ) {
  20202. this.validateInstanceId( instanceId );
  20203. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20204. return this;
  20205. }
  20206. this._instanceInfo[ instanceId ].visible = visible;
  20207. this._visibilityChanged = true;
  20208. return this;
  20209. }
  20210. /**
  20211. * Returns the visibility state of the defined instance.
  20212. *
  20213. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20214. * @return {boolean} Whether the instance is visible or not.
  20215. */
  20216. getVisibleAt( instanceId ) {
  20217. this.validateInstanceId( instanceId );
  20218. return this._instanceInfo[ instanceId ].visible;
  20219. }
  20220. /**
  20221. * Sets the geometry ID of the instance at the given index.
  20222. *
  20223. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20224. * @param {number} geometryId - The geometry ID to be use by the instance.
  20225. * @return {BatchedMesh} A reference to this batched mesh.
  20226. */
  20227. setGeometryIdAt( instanceId, geometryId ) {
  20228. this.validateInstanceId( instanceId );
  20229. this.validateGeometryId( geometryId );
  20230. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20231. return this;
  20232. }
  20233. /**
  20234. * Returns the geometry ID of the defined instance.
  20235. *
  20236. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20237. * @return {number} The instance's geometry ID.
  20238. */
  20239. getGeometryIdAt( instanceId ) {
  20240. this.validateInstanceId( instanceId );
  20241. return this._instanceInfo[ instanceId ].geometryIndex;
  20242. }
  20243. /**
  20244. * Get the range representing the subset of triangles related to the attached geometry,
  20245. * indicating the starting offset and count, or `null` if invalid.
  20246. *
  20247. * @param {number} geometryId - The id of the geometry to get the range of.
  20248. * @param {Object} [target] - The target object that is used to store the method's result.
  20249. * @return {{
  20250. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20251. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20252. * start:number,count:number
  20253. * }} The result object with range data.
  20254. */
  20255. getGeometryRangeAt( geometryId, target = {} ) {
  20256. this.validateGeometryId( geometryId );
  20257. const geometryInfo = this._geometryInfo[ geometryId ];
  20258. target.vertexStart = geometryInfo.vertexStart;
  20259. target.vertexCount = geometryInfo.vertexCount;
  20260. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20261. target.indexStart = geometryInfo.indexStart;
  20262. target.indexCount = geometryInfo.indexCount;
  20263. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20264. target.start = geometryInfo.start;
  20265. target.count = geometryInfo.count;
  20266. return target;
  20267. }
  20268. /**
  20269. * Resizes the necessary buffers to support the provided number of instances.
  20270. * If the provided arguments shrink the number of instances but there are not enough
  20271. * unused Ids at the end of the list then an error is thrown.
  20272. *
  20273. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20274. */
  20275. setInstanceCount( maxInstanceCount ) {
  20276. // shrink the available instances as much as possible
  20277. const availableInstanceIds = this._availableInstanceIds;
  20278. const instanceInfo = this._instanceInfo;
  20279. availableInstanceIds.sort( ascIdSort );
  20280. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  20281. instanceInfo.pop();
  20282. availableInstanceIds.pop();
  20283. }
  20284. // throw an error if it can't be shrunk to the desired size
  20285. if ( maxInstanceCount < instanceInfo.length ) {
  20286. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20287. }
  20288. // copy the multi draw counts
  20289. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20290. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20291. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20292. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20293. this._multiDrawCounts = multiDrawCounts;
  20294. this._multiDrawStarts = multiDrawStarts;
  20295. this._maxInstanceCount = maxInstanceCount;
  20296. // update texture data for instance sampling
  20297. const indirectTexture = this._indirectTexture;
  20298. const matricesTexture = this._matricesTexture;
  20299. const colorsTexture = this._colorsTexture;
  20300. indirectTexture.dispose();
  20301. this._initIndirectTexture();
  20302. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20303. matricesTexture.dispose();
  20304. this._initMatricesTexture();
  20305. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20306. if ( colorsTexture ) {
  20307. colorsTexture.dispose();
  20308. this._initColorsTexture();
  20309. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20310. }
  20311. }
  20312. /**
  20313. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20314. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20315. * end of the geometry attributes then an error is thrown.
  20316. *
  20317. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20318. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20319. */
  20320. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20321. // Check if we can shrink to the requested vertex attribute size
  20322. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20323. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20324. if ( requiredVertexLength > maxVertexCount ) {
  20325. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20326. }
  20327. // Check if we can shrink to the requested index attribute size
  20328. if ( this.geometry.index ) {
  20329. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20330. if ( requiredIndexLength > maxIndexCount ) {
  20331. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20332. }
  20333. }
  20334. //
  20335. // dispose of the previous geometry
  20336. const oldGeometry = this.geometry;
  20337. oldGeometry.dispose();
  20338. // recreate the geometry needed based on the previous variant
  20339. this._maxVertexCount = maxVertexCount;
  20340. this._maxIndexCount = maxIndexCount;
  20341. if ( this._geometryInitialized ) {
  20342. this._geometryInitialized = false;
  20343. this.geometry = new BufferGeometry();
  20344. this._initializeGeometry( oldGeometry );
  20345. }
  20346. // copy data from the previous geometry
  20347. const geometry = this.geometry;
  20348. if ( oldGeometry.index ) {
  20349. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20350. }
  20351. for ( const key in oldGeometry.attributes ) {
  20352. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20353. }
  20354. }
  20355. raycast( raycaster, intersects ) {
  20356. const instanceInfo = this._instanceInfo;
  20357. const geometryInfoList = this._geometryInfo;
  20358. const matrixWorld = this.matrixWorld;
  20359. const batchGeometry = this.geometry;
  20360. // iterate over each geometry
  20361. _mesh.material = this.material;
  20362. _mesh.geometry.index = batchGeometry.index;
  20363. _mesh.geometry.attributes = batchGeometry.attributes;
  20364. if ( _mesh.geometry.boundingBox === null ) {
  20365. _mesh.geometry.boundingBox = new Box3();
  20366. }
  20367. if ( _mesh.geometry.boundingSphere === null ) {
  20368. _mesh.geometry.boundingSphere = new Sphere();
  20369. }
  20370. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20371. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20372. continue;
  20373. }
  20374. const geometryId = instanceInfo[ i ].geometryIndex;
  20375. const geometryInfo = geometryInfoList[ geometryId ];
  20376. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20377. // get the intersects
  20378. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20379. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20380. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20381. _mesh.raycast( raycaster, _batchIntersects );
  20382. // add batch id to the intersects
  20383. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20384. const intersect = _batchIntersects[ j ];
  20385. intersect.object = this;
  20386. intersect.batchId = i;
  20387. intersects.push( intersect );
  20388. }
  20389. _batchIntersects.length = 0;
  20390. }
  20391. _mesh.material = null;
  20392. _mesh.geometry.index = null;
  20393. _mesh.geometry.attributes = {};
  20394. _mesh.geometry.setDrawRange( 0, Infinity );
  20395. }
  20396. copy( source ) {
  20397. super.copy( source );
  20398. this.geometry = source.geometry.clone();
  20399. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20400. this.sortObjects = source.sortObjects;
  20401. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20402. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20403. this._geometryInfo = source._geometryInfo.map( info => ( {
  20404. ...info,
  20405. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20406. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20407. } ) );
  20408. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20409. this._maxInstanceCount = source._maxInstanceCount;
  20410. this._maxVertexCount = source._maxVertexCount;
  20411. this._maxIndexCount = source._maxIndexCount;
  20412. this._geometryInitialized = source._geometryInitialized;
  20413. this._geometryCount = source._geometryCount;
  20414. this._multiDrawCounts = source._multiDrawCounts.slice();
  20415. this._multiDrawStarts = source._multiDrawStarts.slice();
  20416. this._matricesTexture = source._matricesTexture.clone();
  20417. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20418. if ( this._colorsTexture !== null ) {
  20419. this._colorsTexture = source._colorsTexture.clone();
  20420. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20421. }
  20422. return this;
  20423. }
  20424. /**
  20425. * Frees the GPU-related resources allocated by this instance. Call this
  20426. * method whenever this instance is no longer used in your app.
  20427. */
  20428. dispose() {
  20429. // Assuming the geometry is not shared with other meshes
  20430. this.geometry.dispose();
  20431. this._matricesTexture.dispose();
  20432. this._matricesTexture = null;
  20433. this._indirectTexture.dispose();
  20434. this._indirectTexture = null;
  20435. if ( this._colorsTexture !== null ) {
  20436. this._colorsTexture.dispose();
  20437. this._colorsTexture = null;
  20438. }
  20439. }
  20440. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20441. // if visibility has not changed and frustum culling and object sorting is not required
  20442. // then skip iterating over all items
  20443. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20444. return;
  20445. }
  20446. // the indexed version of the multi draw function requires specifying the start
  20447. // offset in bytes.
  20448. const index = geometry.getIndex();
  20449. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20450. const instanceInfo = this._instanceInfo;
  20451. const multiDrawStarts = this._multiDrawStarts;
  20452. const multiDrawCounts = this._multiDrawCounts;
  20453. const geometryInfoList = this._geometryInfo;
  20454. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20455. const indirectTexture = this._indirectTexture;
  20456. const indirectArray = indirectTexture.image.data;
  20457. // prepare the frustum in the local frame
  20458. if ( perObjectFrustumCulled ) {
  20459. _matrix$1
  20460. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20461. .multiply( this.matrixWorld );
  20462. _frustum.setFromProjectionMatrix(
  20463. _matrix$1,
  20464. renderer.coordinateSystem
  20465. );
  20466. }
  20467. let multiDrawCount = 0;
  20468. if ( this.sortObjects ) {
  20469. // get the camera position in the local frame
  20470. _matrix$1.copy( this.matrixWorld ).invert();
  20471. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20472. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20473. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20474. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20475. const geometryId = instanceInfo[ i ].geometryIndex;
  20476. // get the bounds in world space
  20477. this.getMatrixAt( i, _matrix$1 );
  20478. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20479. // determine whether the batched geometry is within the frustum
  20480. let culled = false;
  20481. if ( perObjectFrustumCulled ) {
  20482. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20483. }
  20484. if ( ! culled ) {
  20485. // get the distance from camera used for sorting
  20486. const geometryInfo = geometryInfoList[ geometryId ];
  20487. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  20488. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20489. }
  20490. }
  20491. }
  20492. // Sort the draw ranges and prep for rendering
  20493. const list = _renderList.list;
  20494. const customSort = this.customSort;
  20495. if ( customSort === null ) {
  20496. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20497. } else {
  20498. customSort.call( this, list, camera );
  20499. }
  20500. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20501. const item = list[ i ];
  20502. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20503. multiDrawCounts[ multiDrawCount ] = item.count;
  20504. indirectArray[ multiDrawCount ] = item.index;
  20505. multiDrawCount ++;
  20506. }
  20507. _renderList.reset();
  20508. } else {
  20509. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20510. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20511. const geometryId = instanceInfo[ i ].geometryIndex;
  20512. // determine whether the batched geometry is within the frustum
  20513. let culled = false;
  20514. if ( perObjectFrustumCulled ) {
  20515. // get the bounds in world space
  20516. this.getMatrixAt( i, _matrix$1 );
  20517. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20518. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20519. }
  20520. if ( ! culled ) {
  20521. const geometryInfo = geometryInfoList[ geometryId ];
  20522. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20523. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20524. indirectArray[ multiDrawCount ] = i;
  20525. multiDrawCount ++;
  20526. }
  20527. }
  20528. }
  20529. }
  20530. indirectTexture.needsUpdate = true;
  20531. this._multiDrawCount = multiDrawCount;
  20532. this._visibilityChanged = false;
  20533. }
  20534. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20535. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20536. }
  20537. }
  20538. /**
  20539. * A material for rendering line primitives.
  20540. *
  20541. * Materials define the appearance of renderable 3D objects.
  20542. *
  20543. * ```js
  20544. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20545. * ```
  20546. *
  20547. * @augments Material
  20548. */
  20549. class LineBasicMaterial extends Material {
  20550. /**
  20551. * Constructs a new line basic material.
  20552. *
  20553. * @param {Object} [parameters] - An object with one or more properties
  20554. * defining the material's appearance. Any property of the material
  20555. * (including any property from inherited materials) can be passed
  20556. * in here. Color values can be passed any type of value accepted
  20557. * by {@link Color#set}.
  20558. */
  20559. constructor( parameters ) {
  20560. super();
  20561. /**
  20562. * This flag can be used for type testing.
  20563. *
  20564. * @type {boolean}
  20565. * @readonly
  20566. * @default true
  20567. */
  20568. this.isLineBasicMaterial = true;
  20569. this.type = 'LineBasicMaterial';
  20570. /**
  20571. * Color of the material.
  20572. *
  20573. * @type {Color}
  20574. * @default (1,1,1)
  20575. */
  20576. this.color = new Color( 0xffffff );
  20577. /**
  20578. * Sets the color of the lines using data from a texture. The texture map
  20579. * color is modulated by the diffuse `color`.
  20580. *
  20581. * @type {?Texture}
  20582. * @default null
  20583. */
  20584. this.map = null;
  20585. /**
  20586. * Controls line thickness or lines.
  20587. *
  20588. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20589. * ignore this setting and always render line primitives with a
  20590. * width of one pixel.
  20591. *
  20592. * @type {number}
  20593. * @default 1
  20594. */
  20595. this.linewidth = 1;
  20596. /**
  20597. * Defines appearance of line ends.
  20598. *
  20599. * Can only be used with {@link SVGRenderer}.
  20600. *
  20601. * @type {('butt'|'round'|'square')}
  20602. * @default 'round'
  20603. */
  20604. this.linecap = 'round';
  20605. /**
  20606. * Defines appearance of line joints.
  20607. *
  20608. * Can only be used with {@link SVGRenderer}.
  20609. *
  20610. * @type {('round'|'bevel'|'miter')}
  20611. * @default 'round'
  20612. */
  20613. this.linejoin = 'round';
  20614. /**
  20615. * Whether the material is affected by fog or not.
  20616. *
  20617. * @type {boolean}
  20618. * @default true
  20619. */
  20620. this.fog = true;
  20621. this.setValues( parameters );
  20622. }
  20623. copy( source ) {
  20624. super.copy( source );
  20625. this.color.copy( source.color );
  20626. this.map = source.map;
  20627. this.linewidth = source.linewidth;
  20628. this.linecap = source.linecap;
  20629. this.linejoin = source.linejoin;
  20630. this.fog = source.fog;
  20631. return this;
  20632. }
  20633. }
  20634. const _vStart = /*@__PURE__*/ new Vector3();
  20635. const _vEnd = /*@__PURE__*/ new Vector3();
  20636. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20637. const _ray$1 = /*@__PURE__*/ new Ray();
  20638. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20639. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20640. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20641. /**
  20642. * A continuous line. The line are rendered by connecting consecutive
  20643. * vertices with straight lines.
  20644. *
  20645. * ```js
  20646. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20647. *
  20648. * const points = [];
  20649. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20650. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20651. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20652. *
  20653. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20654. *
  20655. * const line = new THREE.Line( geometry, material );
  20656. * scene.add( line );
  20657. * ```
  20658. *
  20659. * @augments Object3D
  20660. */
  20661. class Line extends Object3D {
  20662. /**
  20663. * Constructs a new line.
  20664. *
  20665. * @param {BufferGeometry} [geometry] - The line geometry.
  20666. * @param {Material|Array<Material>} [material] - The line material.
  20667. */
  20668. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20669. super();
  20670. /**
  20671. * This flag can be used for type testing.
  20672. *
  20673. * @type {boolean}
  20674. * @readonly
  20675. * @default true
  20676. */
  20677. this.isLine = true;
  20678. this.type = 'Line';
  20679. /**
  20680. * The line geometry.
  20681. *
  20682. * @type {BufferGeometry}
  20683. */
  20684. this.geometry = geometry;
  20685. /**
  20686. * The line material.
  20687. *
  20688. * @type {Material|Array<Material>}
  20689. * @default LineBasicMaterial
  20690. */
  20691. this.material = material;
  20692. /**
  20693. * A dictionary representing the morph targets in the geometry. The key is the
  20694. * morph targets name, the value its attribute index. This member is `undefined`
  20695. * by default and only set when morph targets are detected in the geometry.
  20696. *
  20697. * @type {Object<String,number>|undefined}
  20698. * @default undefined
  20699. */
  20700. this.morphTargetDictionary = undefined;
  20701. /**
  20702. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20703. * is applied. This member is `undefined` by default and only set when morph targets are
  20704. * detected in the geometry.
  20705. *
  20706. * @type {Array<number>|undefined}
  20707. * @default undefined
  20708. */
  20709. this.morphTargetInfluences = undefined;
  20710. this.updateMorphTargets();
  20711. }
  20712. copy( source, recursive ) {
  20713. super.copy( source, recursive );
  20714. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20715. this.geometry = source.geometry;
  20716. return this;
  20717. }
  20718. /**
  20719. * Computes an array of distance values which are necessary for rendering dashed lines.
  20720. * For each vertex in the geometry, the method calculates the cumulative length from the
  20721. * current point to the very beginning of the line.
  20722. *
  20723. * @return {Line} A reference to this line.
  20724. */
  20725. computeLineDistances() {
  20726. const geometry = this.geometry;
  20727. // we assume non-indexed geometry
  20728. if ( geometry.index === null ) {
  20729. const positionAttribute = geometry.attributes.position;
  20730. const lineDistances = [ 0 ];
  20731. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20732. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20733. _vEnd.fromBufferAttribute( positionAttribute, i );
  20734. lineDistances[ i ] = lineDistances[ i - 1 ];
  20735. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20736. }
  20737. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20738. } else {
  20739. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20740. }
  20741. return this;
  20742. }
  20743. /**
  20744. * Computes intersection points between a casted ray and this line.
  20745. *
  20746. * @param {Raycaster} raycaster - The raycaster.
  20747. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20748. */
  20749. raycast( raycaster, intersects ) {
  20750. const geometry = this.geometry;
  20751. const matrixWorld = this.matrixWorld;
  20752. const threshold = raycaster.params.Line.threshold;
  20753. const drawRange = geometry.drawRange;
  20754. // Checking boundingSphere distance to ray
  20755. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20756. _sphere$1.copy( geometry.boundingSphere );
  20757. _sphere$1.applyMatrix4( matrixWorld );
  20758. _sphere$1.radius += threshold;
  20759. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20760. //
  20761. _inverseMatrix$1.copy( matrixWorld ).invert();
  20762. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20763. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20764. const localThresholdSq = localThreshold * localThreshold;
  20765. const step = this.isLineSegments ? 2 : 1;
  20766. const index = geometry.index;
  20767. const attributes = geometry.attributes;
  20768. const positionAttribute = attributes.position;
  20769. if ( index !== null ) {
  20770. const start = Math.max( 0, drawRange.start );
  20771. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20772. for ( let i = start, l = end - 1; i < l; i += step ) {
  20773. const a = index.getX( i );
  20774. const b = index.getX( i + 1 );
  20775. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20776. if ( intersect ) {
  20777. intersects.push( intersect );
  20778. }
  20779. }
  20780. if ( this.isLineLoop ) {
  20781. const a = index.getX( end - 1 );
  20782. const b = index.getX( start );
  20783. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20784. if ( intersect ) {
  20785. intersects.push( intersect );
  20786. }
  20787. }
  20788. } else {
  20789. const start = Math.max( 0, drawRange.start );
  20790. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20791. for ( let i = start, l = end - 1; i < l; i += step ) {
  20792. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20793. if ( intersect ) {
  20794. intersects.push( intersect );
  20795. }
  20796. }
  20797. if ( this.isLineLoop ) {
  20798. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20799. if ( intersect ) {
  20800. intersects.push( intersect );
  20801. }
  20802. }
  20803. }
  20804. }
  20805. /**
  20806. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20807. * to make sure existing morph targets can influence this 3D object.
  20808. */
  20809. updateMorphTargets() {
  20810. const geometry = this.geometry;
  20811. const morphAttributes = geometry.morphAttributes;
  20812. const keys = Object.keys( morphAttributes );
  20813. if ( keys.length > 0 ) {
  20814. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20815. if ( morphAttribute !== undefined ) {
  20816. this.morphTargetInfluences = [];
  20817. this.morphTargetDictionary = {};
  20818. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20819. const name = morphAttribute[ m ].name || String( m );
  20820. this.morphTargetInfluences.push( 0 );
  20821. this.morphTargetDictionary[ name ] = m;
  20822. }
  20823. }
  20824. }
  20825. }
  20826. }
  20827. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20828. const positionAttribute = object.geometry.attributes.position;
  20829. _vStart.fromBufferAttribute( positionAttribute, a );
  20830. _vEnd.fromBufferAttribute( positionAttribute, b );
  20831. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20832. if ( distSq > thresholdSq ) return;
  20833. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20834. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20835. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20836. return {
  20837. distance: distance,
  20838. // What do we want? intersection point on the ray or on the segment??
  20839. // point: raycaster.ray.at( distance ),
  20840. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20841. index: i,
  20842. face: null,
  20843. faceIndex: null,
  20844. barycoord: null,
  20845. object: object
  20846. };
  20847. }
  20848. const _start = /*@__PURE__*/ new Vector3();
  20849. const _end = /*@__PURE__*/ new Vector3();
  20850. /**
  20851. * A series of lines drawn between pairs of vertices.
  20852. *
  20853. * @augments Line
  20854. */
  20855. class LineSegments extends Line {
  20856. /**
  20857. * Constructs a new line segments.
  20858. *
  20859. * @param {BufferGeometry} [geometry] - The line geometry.
  20860. * @param {Material|Array<Material>} [material] - The line material.
  20861. */
  20862. constructor( geometry, material ) {
  20863. super( geometry, material );
  20864. /**
  20865. * This flag can be used for type testing.
  20866. *
  20867. * @type {boolean}
  20868. * @readonly
  20869. * @default true
  20870. */
  20871. this.isLineSegments = true;
  20872. this.type = 'LineSegments';
  20873. }
  20874. computeLineDistances() {
  20875. const geometry = this.geometry;
  20876. // we assume non-indexed geometry
  20877. if ( geometry.index === null ) {
  20878. const positionAttribute = geometry.attributes.position;
  20879. const lineDistances = [];
  20880. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20881. _start.fromBufferAttribute( positionAttribute, i );
  20882. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20883. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20884. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20885. }
  20886. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20887. } else {
  20888. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20889. }
  20890. return this;
  20891. }
  20892. }
  20893. /**
  20894. * A continuous line. This is nearly the same as {@link Line} the only difference
  20895. * is that the last vertex is connected with the first vertex in order to close
  20896. * the line to form a loop.
  20897. *
  20898. * @augments Line
  20899. */
  20900. class LineLoop extends Line {
  20901. /**
  20902. * Constructs a new line loop.
  20903. *
  20904. * @param {BufferGeometry} [geometry] - The line geometry.
  20905. * @param {Material|Array<Material>} [material] - The line material.
  20906. */
  20907. constructor( geometry, material ) {
  20908. super( geometry, material );
  20909. /**
  20910. * This flag can be used for type testing.
  20911. *
  20912. * @type {boolean}
  20913. * @readonly
  20914. * @default true
  20915. */
  20916. this.isLineLoop = true;
  20917. this.type = 'LineLoop';
  20918. }
  20919. }
  20920. /**
  20921. * A material for rendering point primitives.
  20922. *
  20923. * Materials define the appearance of renderable 3D objects.
  20924. *
  20925. * ```js
  20926. * const vertices = [];
  20927. *
  20928. * for ( let i = 0; i < 10000; i ++ ) {
  20929. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20930. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20931. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20932. *
  20933. * vertices.push( x, y, z );
  20934. * }
  20935. *
  20936. * const geometry = new THREE.BufferGeometry();
  20937. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20938. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20939. * const points = new THREE.Points( geometry, material );
  20940. * scene.add( points );
  20941. * ```
  20942. *
  20943. * @augments Material
  20944. */
  20945. class PointsMaterial extends Material {
  20946. /**
  20947. * Constructs a new points material.
  20948. *
  20949. * @param {Object} [parameters] - An object with one or more properties
  20950. * defining the material's appearance. Any property of the material
  20951. * (including any property from inherited materials) can be passed
  20952. * in here. Color values can be passed any type of value accepted
  20953. * by {@link Color#set}.
  20954. */
  20955. constructor( parameters ) {
  20956. super();
  20957. /**
  20958. * This flag can be used for type testing.
  20959. *
  20960. * @type {boolean}
  20961. * @readonly
  20962. * @default true
  20963. */
  20964. this.isPointsMaterial = true;
  20965. this.type = 'PointsMaterial';
  20966. /**
  20967. * Color of the material.
  20968. *
  20969. * @type {Color}
  20970. * @default (1,1,1)
  20971. */
  20972. this.color = new Color( 0xffffff );
  20973. /**
  20974. * The color map. May optionally include an alpha channel, typically combined
  20975. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20976. * color is modulated by the diffuse `color`.
  20977. *
  20978. * @type {?Texture}
  20979. * @default null
  20980. */
  20981. this.map = null;
  20982. /**
  20983. * The alpha map is a grayscale texture that controls the opacity across the
  20984. * surface (black: fully transparent; white: fully opaque).
  20985. *
  20986. * Only the color of the texture is used, ignoring the alpha channel if one
  20987. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20988. * when sampling this texture due to the extra bit of precision provided for
  20989. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20990. * luminance/alpha textures will also still work as expected.
  20991. *
  20992. * @type {?Texture}
  20993. * @default null
  20994. */
  20995. this.alphaMap = null;
  20996. /**
  20997. * Defines the size of the points in pixels.
  20998. *
  20999. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete}.
  21000. *
  21001. * @type {number}
  21002. * @default 1
  21003. */
  21004. this.size = 1;
  21005. /**
  21006. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21007. *
  21008. * @type {boolean}
  21009. * @default true
  21010. */
  21011. this.sizeAttenuation = true;
  21012. /**
  21013. * Whether the material is affected by fog or not.
  21014. *
  21015. * @type {boolean}
  21016. * @default true
  21017. */
  21018. this.fog = true;
  21019. this.setValues( parameters );
  21020. }
  21021. copy( source ) {
  21022. super.copy( source );
  21023. this.color.copy( source.color );
  21024. this.map = source.map;
  21025. this.alphaMap = source.alphaMap;
  21026. this.size = source.size;
  21027. this.sizeAttenuation = source.sizeAttenuation;
  21028. this.fog = source.fog;
  21029. return this;
  21030. }
  21031. }
  21032. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21033. const _ray = /*@__PURE__*/ new Ray();
  21034. const _sphere = /*@__PURE__*/ new Sphere();
  21035. const _position$2 = /*@__PURE__*/ new Vector3();
  21036. /**
  21037. * A class for displaying points or point clouds.
  21038. *
  21039. * @augments Object3D
  21040. */
  21041. class Points extends Object3D {
  21042. /**
  21043. * Constructs a new point cloud.
  21044. *
  21045. * @param {BufferGeometry} [geometry] - The points geometry.
  21046. * @param {Material|Array<Material>} [material] - The points material.
  21047. */
  21048. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21049. super();
  21050. /**
  21051. * This flag can be used for type testing.
  21052. *
  21053. * @type {boolean}
  21054. * @readonly
  21055. * @default true
  21056. */
  21057. this.isPoints = true;
  21058. this.type = 'Points';
  21059. /**
  21060. * The points geometry.
  21061. *
  21062. * @type {BufferGeometry}
  21063. */
  21064. this.geometry = geometry;
  21065. /**
  21066. * The line material.
  21067. *
  21068. * @type {Material|Array<Material>}
  21069. * @default PointsMaterial
  21070. */
  21071. this.material = material;
  21072. /**
  21073. * A dictionary representing the morph targets in the geometry. The key is the
  21074. * morph targets name, the value its attribute index. This member is `undefined`
  21075. * by default and only set when morph targets are detected in the geometry.
  21076. *
  21077. * @type {Object<String,number>|undefined}
  21078. * @default undefined
  21079. */
  21080. this.morphTargetDictionary = undefined;
  21081. /**
  21082. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21083. * is applied. This member is `undefined` by default and only set when morph targets are
  21084. * detected in the geometry.
  21085. *
  21086. * @type {Array<number>|undefined}
  21087. * @default undefined
  21088. */
  21089. this.morphTargetInfluences = undefined;
  21090. this.updateMorphTargets();
  21091. }
  21092. copy( source, recursive ) {
  21093. super.copy( source, recursive );
  21094. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21095. this.geometry = source.geometry;
  21096. return this;
  21097. }
  21098. /**
  21099. * Computes intersection points between a casted ray and this point cloud.
  21100. *
  21101. * @param {Raycaster} raycaster - The raycaster.
  21102. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21103. */
  21104. raycast( raycaster, intersects ) {
  21105. const geometry = this.geometry;
  21106. const matrixWorld = this.matrixWorld;
  21107. const threshold = raycaster.params.Points.threshold;
  21108. const drawRange = geometry.drawRange;
  21109. // Checking boundingSphere distance to ray
  21110. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21111. _sphere.copy( geometry.boundingSphere );
  21112. _sphere.applyMatrix4( matrixWorld );
  21113. _sphere.radius += threshold;
  21114. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21115. //
  21116. _inverseMatrix.copy( matrixWorld ).invert();
  21117. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21118. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21119. const localThresholdSq = localThreshold * localThreshold;
  21120. const index = geometry.index;
  21121. const attributes = geometry.attributes;
  21122. const positionAttribute = attributes.position;
  21123. if ( index !== null ) {
  21124. const start = Math.max( 0, drawRange.start );
  21125. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21126. for ( let i = start, il = end; i < il; i ++ ) {
  21127. const a = index.getX( i );
  21128. _position$2.fromBufferAttribute( positionAttribute, a );
  21129. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21130. }
  21131. } else {
  21132. const start = Math.max( 0, drawRange.start );
  21133. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21134. for ( let i = start, l = end; i < l; i ++ ) {
  21135. _position$2.fromBufferAttribute( positionAttribute, i );
  21136. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21137. }
  21138. }
  21139. }
  21140. /**
  21141. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21142. * to make sure existing morph targets can influence this 3D object.
  21143. */
  21144. updateMorphTargets() {
  21145. const geometry = this.geometry;
  21146. const morphAttributes = geometry.morphAttributes;
  21147. const keys = Object.keys( morphAttributes );
  21148. if ( keys.length > 0 ) {
  21149. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21150. if ( morphAttribute !== undefined ) {
  21151. this.morphTargetInfluences = [];
  21152. this.morphTargetDictionary = {};
  21153. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21154. const name = morphAttribute[ m ].name || String( m );
  21155. this.morphTargetInfluences.push( 0 );
  21156. this.morphTargetDictionary[ name ] = m;
  21157. }
  21158. }
  21159. }
  21160. }
  21161. }
  21162. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21163. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21164. if ( rayPointDistanceSq < localThresholdSq ) {
  21165. const intersectPoint = new Vector3();
  21166. _ray.closestPointToPoint( point, intersectPoint );
  21167. intersectPoint.applyMatrix4( matrixWorld );
  21168. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21169. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21170. intersects.push( {
  21171. distance: distance,
  21172. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21173. point: intersectPoint,
  21174. index: index,
  21175. face: null,
  21176. faceIndex: null,
  21177. barycoord: null,
  21178. object: object
  21179. } );
  21180. }
  21181. }
  21182. /**
  21183. * A texture for use with a video.
  21184. *
  21185. * ```js
  21186. * // assuming you have created a HTML video element with id="video"
  21187. * const video = document.getElementById( 'video' );
  21188. * const texture = new THREE.VideoTexture( video );
  21189. * ```
  21190. *
  21191. * Note: After the initial use of a texture, its dimensions, format, and type
  21192. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21193. *
  21194. * @augments Texture
  21195. */
  21196. class VideoTexture extends Texture {
  21197. /**
  21198. * Constructs a new video texture.
  21199. *
  21200. * @param {Video} video - The video element to use as a data source for the texture.
  21201. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21202. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21203. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21204. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21205. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21206. * @param {number} [format=RGBAFormat] - The texture format.
  21207. * @param {number} [type=UnsignedByteType] - The texture type.
  21208. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21209. */
  21210. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21211. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21212. /**
  21213. * This flag can be used for type testing.
  21214. *
  21215. * @type {boolean}
  21216. * @readonly
  21217. * @default true
  21218. */
  21219. this.isVideoTexture = true;
  21220. /**
  21221. * Whether to generate mipmaps (if possible) for a texture.
  21222. *
  21223. * Overwritten and set to `false` by default.
  21224. *
  21225. * @type {boolean}
  21226. * @default false
  21227. */
  21228. this.generateMipmaps = false;
  21229. const scope = this;
  21230. function updateVideo() {
  21231. scope.needsUpdate = true;
  21232. video.requestVideoFrameCallback( updateVideo );
  21233. }
  21234. if ( 'requestVideoFrameCallback' in video ) {
  21235. video.requestVideoFrameCallback( updateVideo );
  21236. }
  21237. }
  21238. clone() {
  21239. return new this.constructor( this.image ).copy( this );
  21240. }
  21241. /**
  21242. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21243. * to `true` every time a new frame is available.
  21244. *
  21245. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21246. */
  21247. update() {
  21248. const video = this.image;
  21249. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21250. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21251. this.needsUpdate = true;
  21252. }
  21253. }
  21254. }
  21255. /**
  21256. * This class can be used as an alternative way to define video data. Instead of using
  21257. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21258. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21259. * video frames are decoded with the WebCodecs API.
  21260. *
  21261. * ```js
  21262. * const texture = new THREE.VideoFrameTexture();
  21263. * texture.setFrame( frame );
  21264. * ```
  21265. *
  21266. * @augments VideoTexture
  21267. */
  21268. class VideoFrameTexture extends VideoTexture {
  21269. /**
  21270. * Constructs a new video frame texture.
  21271. *
  21272. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21273. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21274. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21275. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21276. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21277. * @param {number} [format=RGBAFormat] - The texture format.
  21278. * @param {number} [type=UnsignedByteType] - The texture type.
  21279. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21280. */
  21281. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21282. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21283. /**
  21284. * This flag can be used for type testing.
  21285. *
  21286. * @type {boolean}
  21287. * @readonly
  21288. * @default true
  21289. */
  21290. this.isVideoFrameTexture = true;
  21291. }
  21292. /**
  21293. * This method overwritten with an empty implementation since
  21294. * this type of texture is updated via `setFrame()`.
  21295. */
  21296. update() {}
  21297. clone() {
  21298. return new this.constructor().copy( this ); // restoring Texture.clone()
  21299. }
  21300. /**
  21301. * Sets the current frame of the video. This will automatically update the texture
  21302. * so the data can be used for rendering.
  21303. *
  21304. * @param {VideoFrame} frame - The video frame.
  21305. */
  21306. setFrame( frame ) {
  21307. this.image = frame;
  21308. this.needsUpdate = true;
  21309. }
  21310. }
  21311. /**
  21312. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21313. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21314. * as a texture for further usage.
  21315. *
  21316. * ```js
  21317. * const pixelRatio = window.devicePixelRatio;
  21318. * const textureSize = 128 * pixelRatio;
  21319. *
  21320. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21321. *
  21322. * // calculate start position for copying part of the frame data
  21323. * const vector = new Vector2();
  21324. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21325. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21326. *
  21327. * renderer.render( scene, camera );
  21328. *
  21329. * // copy part of the rendered frame into the framebuffer texture
  21330. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21331. * ```
  21332. *
  21333. * @augments Texture
  21334. */
  21335. class FramebufferTexture extends Texture {
  21336. /**
  21337. * Constructs a new framebuffer texture.
  21338. *
  21339. * @param {number} width - The width of the texture.
  21340. * @param {number} height - The height of the texture.
  21341. */
  21342. constructor( width, height ) {
  21343. super( { width, height } );
  21344. /**
  21345. * This flag can be used for type testing.
  21346. *
  21347. * @type {boolean}
  21348. * @readonly
  21349. * @default true
  21350. */
  21351. this.isFramebufferTexture = true;
  21352. /**
  21353. * How the texture is sampled when a texel covers more than one pixel.
  21354. *
  21355. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21356. *
  21357. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21358. * @default NearestFilter
  21359. */
  21360. this.magFilter = NearestFilter;
  21361. /**
  21362. * How the texture is sampled when a texel covers less than one pixel.
  21363. *
  21364. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21365. *
  21366. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21367. * @default NearestFilter
  21368. */
  21369. this.minFilter = NearestFilter;
  21370. /**
  21371. * Whether to generate mipmaps (if possible) for a texture.
  21372. *
  21373. * Overwritten and set to `false` by default.
  21374. *
  21375. * @type {boolean}
  21376. * @default false
  21377. */
  21378. this.generateMipmaps = false;
  21379. this.needsUpdate = true;
  21380. }
  21381. }
  21382. /**
  21383. * Creates a texture based on data in compressed form.
  21384. *
  21385. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21386. *
  21387. * @augments Texture
  21388. */
  21389. class CompressedTexture extends Texture {
  21390. /**
  21391. * Constructs a new compressed texture.
  21392. *
  21393. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21394. * the data and dimensions.
  21395. * @param {number} width - The width of the texture.
  21396. * @param {number} height - The height of the texture.
  21397. * @param {number} [format=RGBAFormat] - The texture format.
  21398. * @param {number} [type=UnsignedByteType] - The texture type.
  21399. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21400. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21401. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21402. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21403. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21404. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21405. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21406. */
  21407. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21408. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21409. /**
  21410. * This flag can be used for type testing.
  21411. *
  21412. * @type {boolean}
  21413. * @readonly
  21414. * @default true
  21415. */
  21416. this.isCompressedTexture = true;
  21417. /**
  21418. * The image property of a compressed texture just defines its dimensions.
  21419. *
  21420. * @type {{width:number,height:number}}
  21421. */
  21422. this.image = { width: width, height: height };
  21423. /**
  21424. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21425. *
  21426. * @type {Array<Object>}
  21427. */
  21428. this.mipmaps = mipmaps;
  21429. /**
  21430. * If set to `true`, the texture is flipped along the vertical axis when
  21431. * uploaded to the GPU.
  21432. *
  21433. * Overwritten and set to `false` by default since it is not possible to
  21434. * flip compressed textures.
  21435. *
  21436. * @type {boolean}
  21437. * @default false
  21438. * @readonly
  21439. */
  21440. this.flipY = false;
  21441. /**
  21442. * Whether to generate mipmaps (if possible) for a texture.
  21443. *
  21444. * Overwritten and set to `false` by default since it is not
  21445. * possible to generate mipmaps for compressed data. Mipmaps
  21446. * must be embedded in the compressed texture file.
  21447. *
  21448. * @type {boolean}
  21449. * @default false
  21450. * @readonly
  21451. */
  21452. this.generateMipmaps = false;
  21453. }
  21454. }
  21455. /**
  21456. * Creates a texture 2D array based on data in compressed form.
  21457. *
  21458. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21459. *
  21460. * @augments CompressedTexture
  21461. */
  21462. class CompressedArrayTexture extends CompressedTexture {
  21463. /**
  21464. * Constructs a new compressed array texture.
  21465. *
  21466. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21467. * the data and dimensions.
  21468. * @param {number} width - The width of the texture.
  21469. * @param {number} height - The height of the texture.
  21470. * @param {number} depth - The depth of the texture.
  21471. * @param {number} [format=RGBAFormat] - The min filter value.
  21472. * @param {number} [type=UnsignedByteType] - The min filter value.
  21473. */
  21474. constructor( mipmaps, width, height, depth, format, type ) {
  21475. super( mipmaps, width, height, format, type );
  21476. /**
  21477. * This flag can be used for type testing.
  21478. *
  21479. * @type {boolean}
  21480. * @readonly
  21481. * @default true
  21482. */
  21483. this.isCompressedArrayTexture = true;
  21484. /**
  21485. * The image property of a compressed texture just defines its dimensions.
  21486. *
  21487. * @name CompressedArrayTexture#image
  21488. * @type {{width:number,height:number,depth:number}}
  21489. */
  21490. this.image.depth = depth;
  21491. /**
  21492. * This defines how the texture is wrapped in the depth and corresponds to
  21493. * *W* in UVW mapping.
  21494. *
  21495. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21496. * @default ClampToEdgeWrapping
  21497. */
  21498. this.wrapR = ClampToEdgeWrapping;
  21499. /**
  21500. * A set of all layers which need to be updated in the texture.
  21501. *
  21502. * @type {Set<number>}
  21503. */
  21504. this.layerUpdates = new Set();
  21505. }
  21506. /**
  21507. * Describes that a specific layer of the texture needs to be updated.
  21508. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21509. * entire compressed texture array is sent to the GPU. Marking specific
  21510. * layers will only transmit subsets of all mipmaps associated with a
  21511. * specific depth in the array which is often much more performant.
  21512. *
  21513. * @param {number} layerIndex - The layer index that should be updated.
  21514. */
  21515. addLayerUpdate( layerIndex ) {
  21516. this.layerUpdates.add( layerIndex );
  21517. }
  21518. /**
  21519. * Resets the layer updates registry.
  21520. */
  21521. clearLayerUpdates() {
  21522. this.layerUpdates.clear();
  21523. }
  21524. }
  21525. /**
  21526. * Creates a cube texture based on data in compressed form.
  21527. *
  21528. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21529. *
  21530. * @augments CompressedTexture
  21531. */
  21532. class CompressedCubeTexture extends CompressedTexture {
  21533. /**
  21534. * Constructs a new compressed texture.
  21535. *
  21536. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21537. * @param {number} [format=RGBAFormat] - The texture format.
  21538. * @param {number} [type=UnsignedByteType] - The texture type.
  21539. */
  21540. constructor( images, format, type ) {
  21541. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21542. /**
  21543. * This flag can be used for type testing.
  21544. *
  21545. * @type {boolean}
  21546. * @readonly
  21547. * @default true
  21548. */
  21549. this.isCompressedCubeTexture = true;
  21550. /**
  21551. * This flag can be used for type testing.
  21552. *
  21553. * @type {boolean}
  21554. * @readonly
  21555. * @default true
  21556. */
  21557. this.isCubeTexture = true;
  21558. this.image = images;
  21559. }
  21560. }
  21561. /**
  21562. * Creates a texture from a canvas element.
  21563. *
  21564. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21565. * to `true` immediately since a canvas can directly be used for rendering.
  21566. *
  21567. * @augments Texture
  21568. */
  21569. class CanvasTexture extends Texture {
  21570. /**
  21571. * Constructs a new texture.
  21572. *
  21573. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21574. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21575. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21576. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21577. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21578. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21579. * @param {number} [format=RGBAFormat] - The texture format.
  21580. * @param {number} [type=UnsignedByteType] - The texture type.
  21581. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21582. */
  21583. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21584. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21585. /**
  21586. * This flag can be used for type testing.
  21587. *
  21588. * @type {boolean}
  21589. * @readonly
  21590. * @default true
  21591. */
  21592. this.isCanvasTexture = true;
  21593. this.needsUpdate = true;
  21594. }
  21595. }
  21596. /**
  21597. * This class can be used to automatically save the depth information of a
  21598. * rendering into a texture.
  21599. *
  21600. * @augments Texture
  21601. */
  21602. class DepthTexture extends Texture {
  21603. /**
  21604. * Constructs a new depth texture.
  21605. *
  21606. * @param {number} width - The width of the texture.
  21607. * @param {number} height - The height of the texture.
  21608. * @param {number} [type=UnsignedIntType] - The texture type.
  21609. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21610. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21611. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21612. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21613. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21614. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21615. * @param {number} [format=DepthFormat] - The texture format.
  21616. */
  21617. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21618. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21619. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21620. }
  21621. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21622. /**
  21623. * This flag can be used for type testing.
  21624. *
  21625. * @type {boolean}
  21626. * @readonly
  21627. * @default true
  21628. */
  21629. this.isDepthTexture = true;
  21630. /**
  21631. * The image property of a depth texture just defines its dimensions.
  21632. *
  21633. * @type {{width:number,height:number}}
  21634. */
  21635. this.image = { width: width, height: height };
  21636. /**
  21637. * If set to `true`, the texture is flipped along the vertical axis when
  21638. * uploaded to the GPU.
  21639. *
  21640. * Overwritten and set to `false` by default.
  21641. *
  21642. * @type {boolean}
  21643. * @default false
  21644. */
  21645. this.flipY = false;
  21646. /**
  21647. * Whether to generate mipmaps (if possible) for a texture.
  21648. *
  21649. * Overwritten and set to `false` by default.
  21650. *
  21651. * @type {boolean}
  21652. * @default false
  21653. */
  21654. this.generateMipmaps = false;
  21655. /**
  21656. * The depth compare function.
  21657. *
  21658. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21659. * @default null
  21660. */
  21661. this.compareFunction = null;
  21662. }
  21663. copy( source ) {
  21664. super.copy( source );
  21665. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21666. this.compareFunction = source.compareFunction;
  21667. return this;
  21668. }
  21669. toJSON( meta ) {
  21670. const data = super.toJSON( meta );
  21671. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21672. return data;
  21673. }
  21674. }
  21675. /**
  21676. * An abstract base class for creating an analytic curve object that contains methods
  21677. * for interpolation.
  21678. *
  21679. * @abstract
  21680. */
  21681. class Curve {
  21682. /**
  21683. * Constructs a new curve.
  21684. */
  21685. constructor() {
  21686. /**
  21687. * The type property is used for detecting the object type
  21688. * in context of serialization/deserialization.
  21689. *
  21690. * @type {string}
  21691. * @readonly
  21692. */
  21693. this.type = 'Curve';
  21694. /**
  21695. * This value determines the amount of divisions when calculating the
  21696. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  21697. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  21698. * recommended to increase the value of this property if the curve is very large.
  21699. *
  21700. * @type {number}
  21701. * @default 200
  21702. */
  21703. this.arcLengthDivisions = 200;
  21704. /**
  21705. * Must be set to `true` if the curve parameters have changed.
  21706. *
  21707. * @type {boolean}
  21708. * @default false
  21709. */
  21710. this.needsUpdate = false;
  21711. /**
  21712. * An internal cache that holds precomputed curve length values.
  21713. *
  21714. * @private
  21715. * @type {?Array<number>}
  21716. * @default null
  21717. */
  21718. this.cacheArcLengths = null;
  21719. }
  21720. /**
  21721. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  21722. * for the given interpolation factor.
  21723. *
  21724. * @abstract
  21725. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  21726. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21727. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  21728. */
  21729. getPoint( /* t, optionalTarget */ ) {
  21730. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  21731. }
  21732. /**
  21733. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  21734. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  21735. * of the curve which equidistant samples.
  21736. *
  21737. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  21738. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21739. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  21740. */
  21741. getPointAt( u, optionalTarget ) {
  21742. const t = this.getUtoTmapping( u );
  21743. return this.getPoint( t, optionalTarget );
  21744. }
  21745. /**
  21746. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  21747. * the curve shape.
  21748. *
  21749. * @param {number} [divisions=5] - The number of divisions.
  21750. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  21751. */
  21752. getPoints( divisions = 5 ) {
  21753. const points = [];
  21754. for ( let d = 0; d <= divisions; d ++ ) {
  21755. points.push( this.getPoint( d / divisions ) );
  21756. }
  21757. return points;
  21758. }
  21759. // Get sequence of points using getPointAt( u )
  21760. /**
  21761. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  21762. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  21763. * curve.
  21764. *
  21765. * @param {number} [divisions=5] - The number of divisions.
  21766. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  21767. */
  21768. getSpacedPoints( divisions = 5 ) {
  21769. const points = [];
  21770. for ( let d = 0; d <= divisions; d ++ ) {
  21771. points.push( this.getPointAt( d / divisions ) );
  21772. }
  21773. return points;
  21774. }
  21775. /**
  21776. * Returns the total arc length of the curve.
  21777. *
  21778. * @return {number} The length of the curve.
  21779. */
  21780. getLength() {
  21781. const lengths = this.getLengths();
  21782. return lengths[ lengths.length - 1 ];
  21783. }
  21784. /**
  21785. * Returns an array of cumulative segment lengths of the curve.
  21786. *
  21787. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  21788. * @return {Array<number>} An array holding the cumulative segment lengths.
  21789. */
  21790. getLengths( divisions = this.arcLengthDivisions ) {
  21791. if ( this.cacheArcLengths &&
  21792. ( this.cacheArcLengths.length === divisions + 1 ) &&
  21793. ! this.needsUpdate ) {
  21794. return this.cacheArcLengths;
  21795. }
  21796. this.needsUpdate = false;
  21797. const cache = [];
  21798. let current, last = this.getPoint( 0 );
  21799. let sum = 0;
  21800. cache.push( 0 );
  21801. for ( let p = 1; p <= divisions; p ++ ) {
  21802. current = this.getPoint( p / divisions );
  21803. sum += current.distanceTo( last );
  21804. cache.push( sum );
  21805. last = current;
  21806. }
  21807. this.cacheArcLengths = cache;
  21808. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21809. }
  21810. /**
  21811. * Update the cumulative segment distance cache. The method must be called
  21812. * every time curve parameters are changed. If an updated curve is part of a
  21813. * composed curve like {@link CurvePath}, this method must be called on the
  21814. * composed curve, too.
  21815. */
  21816. updateArcLengths() {
  21817. this.needsUpdate = true;
  21818. this.getLengths();
  21819. }
  21820. /**
  21821. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  21822. * interpolation factor in the same range that can be ued to sample equidistant points
  21823. * from a curve.
  21824. *
  21825. * @param {number} u - The interpolation factor.
  21826. * @param {?number} distance - An optional distance on the curve.
  21827. * @return {number} The updated interpolation factor.
  21828. */
  21829. getUtoTmapping( u, distance = null ) {
  21830. const arcLengths = this.getLengths();
  21831. let i = 0;
  21832. const il = arcLengths.length;
  21833. let targetArcLength; // The targeted u distance value to get
  21834. if ( distance ) {
  21835. targetArcLength = distance;
  21836. } else {
  21837. targetArcLength = u * arcLengths[ il - 1 ];
  21838. }
  21839. // binary search for the index with largest value smaller than target u distance
  21840. let low = 0, high = il - 1, comparison;
  21841. while ( low <= high ) {
  21842. 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
  21843. comparison = arcLengths[ i ] - targetArcLength;
  21844. if ( comparison < 0 ) {
  21845. low = i + 1;
  21846. } else if ( comparison > 0 ) {
  21847. high = i - 1;
  21848. } else {
  21849. high = i;
  21850. break;
  21851. // DONE
  21852. }
  21853. }
  21854. i = high;
  21855. if ( arcLengths[ i ] === targetArcLength ) {
  21856. return i / ( il - 1 );
  21857. }
  21858. // we could get finer grain at lengths, or use simple interpolation between two points
  21859. const lengthBefore = arcLengths[ i ];
  21860. const lengthAfter = arcLengths[ i + 1 ];
  21861. const segmentLength = lengthAfter - lengthBefore;
  21862. // determine where we are between the 'before' and 'after' points
  21863. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  21864. // add that fractional amount to t
  21865. const t = ( i + segmentFraction ) / ( il - 1 );
  21866. return t;
  21867. }
  21868. /**
  21869. * Returns a unit vector tangent for the given interpolation factor.
  21870. * If the derived curve does not implement its tangent derivation,
  21871. * two points a small delta apart will be used to find its gradient
  21872. * which seems to give a reasonable approximation.
  21873. *
  21874. * @param {number} t - The interpolation factor.
  21875. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21876. * @return {(Vector2|Vector3)} The tangent vector.
  21877. */
  21878. getTangent( t, optionalTarget ) {
  21879. const delta = 0.0001;
  21880. let t1 = t - delta;
  21881. let t2 = t + delta;
  21882. // Capping in case of danger
  21883. if ( t1 < 0 ) t1 = 0;
  21884. if ( t2 > 1 ) t2 = 1;
  21885. const pt1 = this.getPoint( t1 );
  21886. const pt2 = this.getPoint( t2 );
  21887. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  21888. tangent.copy( pt2 ).sub( pt1 ).normalize();
  21889. return tangent;
  21890. }
  21891. /**
  21892. * Same as {@link Curve#getTangent} but with equidistant samples.
  21893. *
  21894. * @param {number} u - The interpolation factor.
  21895. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  21896. * @return {(Vector2|Vector3)} The tangent vector.
  21897. * @see {@link Curve#getPointAt}
  21898. */
  21899. getTangentAt( u, optionalTarget ) {
  21900. const t = this.getUtoTmapping( u );
  21901. return this.getTangent( t, optionalTarget );
  21902. }
  21903. /**
  21904. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  21905. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  21906. *
  21907. * @param {number} segments - The number of segments.
  21908. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  21909. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  21910. */
  21911. computeFrenetFrames( segments, closed = false ) {
  21912. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21913. const normal = new Vector3();
  21914. const tangents = [];
  21915. const normals = [];
  21916. const binormals = [];
  21917. const vec = new Vector3();
  21918. const mat = new Matrix4();
  21919. // compute the tangent vectors for each segment on the curve
  21920. for ( let i = 0; i <= segments; i ++ ) {
  21921. const u = i / segments;
  21922. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  21923. }
  21924. // select an initial normal vector perpendicular to the first tangent vector,
  21925. // and in the direction of the minimum tangent xyz component
  21926. normals[ 0 ] = new Vector3();
  21927. binormals[ 0 ] = new Vector3();
  21928. let min = Number.MAX_VALUE;
  21929. const tx = Math.abs( tangents[ 0 ].x );
  21930. const ty = Math.abs( tangents[ 0 ].y );
  21931. const tz = Math.abs( tangents[ 0 ].z );
  21932. if ( tx <= min ) {
  21933. min = tx;
  21934. normal.set( 1, 0, 0 );
  21935. }
  21936. if ( ty <= min ) {
  21937. min = ty;
  21938. normal.set( 0, 1, 0 );
  21939. }
  21940. if ( tz <= min ) {
  21941. normal.set( 0, 0, 1 );
  21942. }
  21943. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  21944. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  21945. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  21946. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21947. for ( let i = 1; i <= segments; i ++ ) {
  21948. normals[ i ] = normals[ i - 1 ].clone();
  21949. binormals[ i ] = binormals[ i - 1 ].clone();
  21950. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  21951. if ( vec.length() > Number.EPSILON ) {
  21952. vec.normalize();
  21953. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  21954. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  21955. }
  21956. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21957. }
  21958. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21959. if ( closed === true ) {
  21960. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  21961. theta /= segments;
  21962. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  21963. theta = - theta;
  21964. }
  21965. for ( let i = 1; i <= segments; i ++ ) {
  21966. // twist a little...
  21967. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  21968. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  21969. }
  21970. }
  21971. return {
  21972. tangents: tangents,
  21973. normals: normals,
  21974. binormals: binormals
  21975. };
  21976. }
  21977. /**
  21978. * Returns a new curve with copied values from this instance.
  21979. *
  21980. * @return {Curve} A clone of this instance.
  21981. */
  21982. clone() {
  21983. return new this.constructor().copy( this );
  21984. }
  21985. /**
  21986. * Copies the values of the given curve to this instance.
  21987. *
  21988. * @param {Curve} source - The curve to copy.
  21989. * @return {Curve} A reference to this curve.
  21990. */
  21991. copy( source ) {
  21992. this.arcLengthDivisions = source.arcLengthDivisions;
  21993. return this;
  21994. }
  21995. /**
  21996. * Serializes the curve into JSON.
  21997. *
  21998. * @return {Object} A JSON object representing the serialized curve.
  21999. * @see {@link ObjectLoader#parse}
  22000. */
  22001. toJSON() {
  22002. const data = {
  22003. metadata: {
  22004. version: 4.6,
  22005. type: 'Curve',
  22006. generator: 'Curve.toJSON'
  22007. }
  22008. };
  22009. data.arcLengthDivisions = this.arcLengthDivisions;
  22010. data.type = this.type;
  22011. return data;
  22012. }
  22013. /**
  22014. * Deserializes the curve from the given JSON.
  22015. *
  22016. * @param {Object} json - The JSON holding the serialized curve.
  22017. * @return {Curve} A reference to this curve.
  22018. */
  22019. fromJSON( json ) {
  22020. this.arcLengthDivisions = json.arcLengthDivisions;
  22021. return this;
  22022. }
  22023. }
  22024. /**
  22025. * A curve representing an ellipse.
  22026. *
  22027. * ```js
  22028. * const curve = new THREE.EllipseCurve(
  22029. * 0, 0,
  22030. * 10, 10,
  22031. * 0, 2 * Math.PI,
  22032. * false,
  22033. * 0
  22034. * );
  22035. *
  22036. * const points = curve.getPoints( 50 );
  22037. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22038. *
  22039. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22040. *
  22041. * // Create the final object to add to the scene
  22042. * const ellipse = new THREE.Line( geometry, material );
  22043. * ```
  22044. *
  22045. * @augments Curve
  22046. */
  22047. class EllipseCurve extends Curve {
  22048. /**
  22049. * Constructs a new ellipse curve.
  22050. *
  22051. * @param {number} [aX=0] - The X center of the ellipse.
  22052. * @param {number} [aY=0] - The Y center of the ellipse.
  22053. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  22054. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  22055. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22056. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22057. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22058. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22059. */
  22060. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  22061. super();
  22062. /**
  22063. * This flag can be used for type testing.
  22064. *
  22065. * @type {boolean}
  22066. * @readonly
  22067. * @default true
  22068. */
  22069. this.isEllipseCurve = true;
  22070. this.type = 'EllipseCurve';
  22071. /**
  22072. * The X center of the ellipse.
  22073. *
  22074. * @type {number}
  22075. * @default 0
  22076. */
  22077. this.aX = aX;
  22078. /**
  22079. * The Y center of the ellipse.
  22080. *
  22081. * @type {number}
  22082. * @default 0
  22083. */
  22084. this.aY = aY;
  22085. /**
  22086. * The radius of the ellipse in the x direction.
  22087. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  22088. *
  22089. * @type {number}
  22090. * @default 1
  22091. */
  22092. this.xRadius = xRadius;
  22093. /**
  22094. * The radius of the ellipse in the y direction.
  22095. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  22096. *
  22097. * @type {number}
  22098. * @default 1
  22099. */
  22100. this.yRadius = yRadius;
  22101. /**
  22102. * The start angle of the curve in radians starting from the positive X axis.
  22103. *
  22104. * @type {number}
  22105. * @default 0
  22106. */
  22107. this.aStartAngle = aStartAngle;
  22108. /**
  22109. * The end angle of the curve in radians starting from the positive X axis.
  22110. *
  22111. * @type {number}
  22112. * @default Math.PI*2
  22113. */
  22114. this.aEndAngle = aEndAngle;
  22115. /**
  22116. * Whether the ellipse is drawn clockwise or not.
  22117. *
  22118. * @type {boolean}
  22119. * @default false
  22120. */
  22121. this.aClockwise = aClockwise;
  22122. /**
  22123. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22124. *
  22125. * @type {number}
  22126. * @default 0
  22127. */
  22128. this.aRotation = aRotation;
  22129. }
  22130. /**
  22131. * Returns a point on the curve.
  22132. *
  22133. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22134. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22135. * @return {Vector2} The position on the curve.
  22136. */
  22137. getPoint( t, optionalTarget = new Vector2() ) {
  22138. const point = optionalTarget;
  22139. const twoPi = Math.PI * 2;
  22140. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22141. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22142. // ensures that deltaAngle is 0 .. 2 PI
  22143. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22144. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22145. if ( deltaAngle < Number.EPSILON ) {
  22146. if ( samePoints ) {
  22147. deltaAngle = 0;
  22148. } else {
  22149. deltaAngle = twoPi;
  22150. }
  22151. }
  22152. if ( this.aClockwise === true && ! samePoints ) {
  22153. if ( deltaAngle === twoPi ) {
  22154. deltaAngle = - twoPi;
  22155. } else {
  22156. deltaAngle = deltaAngle - twoPi;
  22157. }
  22158. }
  22159. const angle = this.aStartAngle + t * deltaAngle;
  22160. let x = this.aX + this.xRadius * Math.cos( angle );
  22161. let y = this.aY + this.yRadius * Math.sin( angle );
  22162. if ( this.aRotation !== 0 ) {
  22163. const cos = Math.cos( this.aRotation );
  22164. const sin = Math.sin( this.aRotation );
  22165. const tx = x - this.aX;
  22166. const ty = y - this.aY;
  22167. // Rotate the point about the center of the ellipse.
  22168. x = tx * cos - ty * sin + this.aX;
  22169. y = tx * sin + ty * cos + this.aY;
  22170. }
  22171. return point.set( x, y );
  22172. }
  22173. copy( source ) {
  22174. super.copy( source );
  22175. this.aX = source.aX;
  22176. this.aY = source.aY;
  22177. this.xRadius = source.xRadius;
  22178. this.yRadius = source.yRadius;
  22179. this.aStartAngle = source.aStartAngle;
  22180. this.aEndAngle = source.aEndAngle;
  22181. this.aClockwise = source.aClockwise;
  22182. this.aRotation = source.aRotation;
  22183. return this;
  22184. }
  22185. toJSON() {
  22186. const data = super.toJSON();
  22187. data.aX = this.aX;
  22188. data.aY = this.aY;
  22189. data.xRadius = this.xRadius;
  22190. data.yRadius = this.yRadius;
  22191. data.aStartAngle = this.aStartAngle;
  22192. data.aEndAngle = this.aEndAngle;
  22193. data.aClockwise = this.aClockwise;
  22194. data.aRotation = this.aRotation;
  22195. return data;
  22196. }
  22197. fromJSON( json ) {
  22198. super.fromJSON( json );
  22199. this.aX = json.aX;
  22200. this.aY = json.aY;
  22201. this.xRadius = json.xRadius;
  22202. this.yRadius = json.yRadius;
  22203. this.aStartAngle = json.aStartAngle;
  22204. this.aEndAngle = json.aEndAngle;
  22205. this.aClockwise = json.aClockwise;
  22206. this.aRotation = json.aRotation;
  22207. return this;
  22208. }
  22209. }
  22210. /**
  22211. * A curve representing an arc.
  22212. *
  22213. * @augments EllipseCurve
  22214. */
  22215. class ArcCurve extends EllipseCurve {
  22216. /**
  22217. * Constructs a new arc curve.
  22218. *
  22219. * @param {number} [aX=0] - The X center of the ellipse.
  22220. * @param {number} [aY=0] - The Y center of the ellipse.
  22221. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  22222. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22223. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22224. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22225. */
  22226. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22227. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22228. /**
  22229. * This flag can be used for type testing.
  22230. *
  22231. * @type {boolean}
  22232. * @readonly
  22233. * @default true
  22234. */
  22235. this.isArcCurve = true;
  22236. this.type = 'ArcCurve';
  22237. }
  22238. }
  22239. function CubicPoly() {
  22240. /**
  22241. * Centripetal CatmullRom Curve - which is useful for avoiding
  22242. * cusps and self-intersections in non-uniform catmull rom curves.
  22243. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22244. *
  22245. * curve.type accepts centripetal(default), chordal and catmullrom
  22246. * curve.tension is used for catmullrom which defaults to 0.5
  22247. */
  22248. /*
  22249. Based on an optimized c++ solution in
  22250. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22251. - http://ideone.com/NoEbVM
  22252. This CubicPoly class could be used for reusing some variables and calculations,
  22253. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22254. which can be placed in CurveUtils.
  22255. */
  22256. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  22257. /*
  22258. * Compute coefficients for a cubic polynomial
  22259. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22260. * such that
  22261. * p(0) = x0, p(1) = x1
  22262. * and
  22263. * p'(0) = t0, p'(1) = t1.
  22264. */
  22265. function init( x0, x1, t0, t1 ) {
  22266. c0 = x0;
  22267. c1 = t0;
  22268. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  22269. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22270. }
  22271. return {
  22272. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  22273. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  22274. },
  22275. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  22276. // compute tangents when parameterized in [t1,t2]
  22277. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  22278. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  22279. // rescale tangents for parametrization in [0,1]
  22280. t1 *= dt1;
  22281. t2 *= dt1;
  22282. init( x1, x2, t1, t2 );
  22283. },
  22284. calc: function ( t ) {
  22285. const t2 = t * t;
  22286. const t3 = t2 * t;
  22287. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22288. }
  22289. };
  22290. }
  22291. //
  22292. const tmp = /*@__PURE__*/ new Vector3();
  22293. const px = /*@__PURE__*/ new CubicPoly();
  22294. const py = /*@__PURE__*/ new CubicPoly();
  22295. const pz = /*@__PURE__*/ new CubicPoly();
  22296. /**
  22297. * A curve representing a Catmull-Rom spline.
  22298. *
  22299. * ```js
  22300. * //Create a closed wavey loop
  22301. * const curve = new THREE.CatmullRomCurve3( [
  22302. * new THREE.Vector3( -10, 0, 10 ),
  22303. * new THREE.Vector3( -5, 5, 5 ),
  22304. * new THREE.Vector3( 0, 0, 0 ),
  22305. * new THREE.Vector3( 5, -5, 5 ),
  22306. * new THREE.Vector3( 10, 0, 10 )
  22307. * ] );
  22308. *
  22309. * const points = curve.getPoints( 50 );
  22310. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22311. *
  22312. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22313. *
  22314. * // Create the final object to add to the scene
  22315. * const curveObject = new THREE.Line( geometry, material );
  22316. * ```
  22317. *
  22318. * @augments Curve
  22319. */
  22320. class CatmullRomCurve3 extends Curve {
  22321. /**
  22322. * Constructs a new Catmull-Rom curve.
  22323. *
  22324. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  22325. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  22326. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  22327. * @param {number} [tension=0.5] - Tension of the curve.
  22328. */
  22329. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  22330. super();
  22331. /**
  22332. * This flag can be used for type testing.
  22333. *
  22334. * @type {boolean}
  22335. * @readonly
  22336. * @default true
  22337. */
  22338. this.isCatmullRomCurve3 = true;
  22339. this.type = 'CatmullRomCurve3';
  22340. /**
  22341. * An array of 3D points defining the curve.
  22342. *
  22343. * @type {Array<Vector3>}
  22344. */
  22345. this.points = points;
  22346. /**
  22347. * Whether the curve is closed or not.
  22348. *
  22349. * @type {boolean}
  22350. * @default false
  22351. */
  22352. this.closed = closed;
  22353. /**
  22354. * The curve type.
  22355. *
  22356. * @type {('centripetal'|'chordal'|'catmullrom')}
  22357. * @default 'centripetal'
  22358. */
  22359. this.curveType = curveType;
  22360. /**
  22361. * Tension of the curve.
  22362. *
  22363. * @type {number}
  22364. * @default 0.5
  22365. */
  22366. this.tension = tension;
  22367. }
  22368. /**
  22369. * Returns a point on the curve.
  22370. *
  22371. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22372. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  22373. * @return {Vector3} The position on the curve.
  22374. */
  22375. getPoint( t, optionalTarget = new Vector3() ) {
  22376. const point = optionalTarget;
  22377. const points = this.points;
  22378. const l = points.length;
  22379. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  22380. let intPoint = Math.floor( p );
  22381. let weight = p - intPoint;
  22382. if ( this.closed ) {
  22383. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  22384. } else if ( weight === 0 && intPoint === l - 1 ) {
  22385. intPoint = l - 2;
  22386. weight = 1;
  22387. }
  22388. let p0, p3; // 4 points (p1 & p2 defined below)
  22389. if ( this.closed || intPoint > 0 ) {
  22390. p0 = points[ ( intPoint - 1 ) % l ];
  22391. } else {
  22392. // extrapolate first point
  22393. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  22394. p0 = tmp;
  22395. }
  22396. const p1 = points[ intPoint % l ];
  22397. const p2 = points[ ( intPoint + 1 ) % l ];
  22398. if ( this.closed || intPoint + 2 < l ) {
  22399. p3 = points[ ( intPoint + 2 ) % l ];
  22400. } else {
  22401. // extrapolate last point
  22402. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  22403. p3 = tmp;
  22404. }
  22405. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  22406. // init Centripetal / Chordal Catmull-Rom
  22407. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22408. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  22409. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  22410. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  22411. // safety check for repeated points
  22412. if ( dt1 < 1e-4 ) dt1 = 1.0;
  22413. if ( dt0 < 1e-4 ) dt0 = dt1;
  22414. if ( dt2 < 1e-4 ) dt2 = dt1;
  22415. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  22416. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  22417. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  22418. } else if ( this.curveType === 'catmullrom' ) {
  22419. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  22420. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  22421. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  22422. }
  22423. point.set(
  22424. px.calc( weight ),
  22425. py.calc( weight ),
  22426. pz.calc( weight )
  22427. );
  22428. return point;
  22429. }
  22430. copy( source ) {
  22431. super.copy( source );
  22432. this.points = [];
  22433. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  22434. const point = source.points[ i ];
  22435. this.points.push( point.clone() );
  22436. }
  22437. this.closed = source.closed;
  22438. this.curveType = source.curveType;
  22439. this.tension = source.tension;
  22440. return this;
  22441. }
  22442. toJSON() {
  22443. const data = super.toJSON();
  22444. data.points = [];
  22445. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  22446. const point = this.points[ i ];
  22447. data.points.push( point.toArray() );
  22448. }
  22449. data.closed = this.closed;
  22450. data.curveType = this.curveType;
  22451. data.tension = this.tension;
  22452. return data;
  22453. }
  22454. fromJSON( json ) {
  22455. super.fromJSON( json );
  22456. this.points = [];
  22457. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  22458. const point = json.points[ i ];
  22459. this.points.push( new Vector3().fromArray( point ) );
  22460. }
  22461. this.closed = json.closed;
  22462. this.curveType = json.curveType;
  22463. this.tension = json.tension;
  22464. return this;
  22465. }
  22466. }
  22467. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  22468. /**
  22469. * Computes a point on a Catmull-Rom spline.
  22470. *
  22471. * @param {number} t - The interpolation factor.
  22472. * @param {number} p0 - The first control point.
  22473. * @param {number} p1 - The second control point.
  22474. * @param {number} p2 - The third control point.
  22475. * @param {number} p3 - The fourth control point.
  22476. * @return {number} The calculated point on a Catmull-Rom spline.
  22477. */
  22478. function CatmullRom( t, p0, p1, p2, p3 ) {
  22479. const v0 = ( p2 - p0 ) * 0.5;
  22480. const v1 = ( p3 - p1 ) * 0.5;
  22481. const t2 = t * t;
  22482. const t3 = t * t2;
  22483. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  22484. }
  22485. //
  22486. function QuadraticBezierP0( t, p ) {
  22487. const k = 1 - t;
  22488. return k * k * p;
  22489. }
  22490. function QuadraticBezierP1( t, p ) {
  22491. return 2 * ( 1 - t ) * t * p;
  22492. }
  22493. function QuadraticBezierP2( t, p ) {
  22494. return t * t * p;
  22495. }
  22496. /**
  22497. * Computes a point on a Quadratic Bezier curve.
  22498. *
  22499. * @param {number} t - The interpolation factor.
  22500. * @param {number} p0 - The first control point.
  22501. * @param {number} p1 - The second control point.
  22502. * @param {number} p2 - The third control point.
  22503. * @return {number} The calculated point on a Quadratic Bezier curve.
  22504. */
  22505. function QuadraticBezier( t, p0, p1, p2 ) {
  22506. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  22507. QuadraticBezierP2( t, p2 );
  22508. }
  22509. //
  22510. function CubicBezierP0( t, p ) {
  22511. const k = 1 - t;
  22512. return k * k * k * p;
  22513. }
  22514. function CubicBezierP1( t, p ) {
  22515. const k = 1 - t;
  22516. return 3 * k * k * t * p;
  22517. }
  22518. function CubicBezierP2( t, p ) {
  22519. return 3 * ( 1 - t ) * t * t * p;
  22520. }
  22521. function CubicBezierP3( t, p ) {
  22522. return t * t * t * p;
  22523. }
  22524. /**
  22525. * Computes a point on a Cubic Bezier curve.
  22526. *
  22527. * @param {number} t - The interpolation factor.
  22528. * @param {number} p0 - The first control point.
  22529. * @param {number} p1 - The second control point.
  22530. * @param {number} p2 - The third control point.
  22531. * @param {number} p3 - The fourth control point.
  22532. * @return {number} The calculated point on a Cubic Bezier curve.
  22533. */
  22534. function CubicBezier( t, p0, p1, p2, p3 ) {
  22535. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  22536. CubicBezierP3( t, p3 );
  22537. }
  22538. /**
  22539. * A curve representing a 2D Cubic Bezier curve.
  22540. *
  22541. * ```js
  22542. * const curve = new THREE.CubicBezierCurve(
  22543. * new THREE.Vector2( - 0, 0 ),
  22544. * new THREE.Vector2( - 5, 15 ),
  22545. * new THREE.Vector2( 20, 15 ),
  22546. * new THREE.Vector2( 10, 0 )
  22547. * );
  22548. *
  22549. * const points = curve.getPoints( 50 );
  22550. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22551. *
  22552. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22553. *
  22554. * // Create the final object to add to the scene
  22555. * const curveObject = new THREE.Line( geometry, material );
  22556. * ```
  22557. *
  22558. * @augments Curve
  22559. */
  22560. class CubicBezierCurve extends Curve {
  22561. /**
  22562. * Constructs a new Cubic Bezier curve.
  22563. *
  22564. * @param {Vector2} [v0] - The start point.
  22565. * @param {Vector2} [v1] - The first control point.
  22566. * @param {Vector2} [v2] - The second control point.
  22567. * @param {Vector2} [v3] - The end point.
  22568. */
  22569. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  22570. super();
  22571. /**
  22572. * This flag can be used for type testing.
  22573. *
  22574. * @type {boolean}
  22575. * @readonly
  22576. * @default true
  22577. */
  22578. this.isCubicBezierCurve = true;
  22579. this.type = 'CubicBezierCurve';
  22580. /**
  22581. * The start point.
  22582. *
  22583. * @type {Vector2}
  22584. */
  22585. this.v0 = v0;
  22586. /**
  22587. * The first control point.
  22588. *
  22589. * @type {Vector2}
  22590. */
  22591. this.v1 = v1;
  22592. /**
  22593. * The second control point.
  22594. *
  22595. * @type {Vector2}
  22596. */
  22597. this.v2 = v2;
  22598. /**
  22599. * The end point.
  22600. *
  22601. * @type {Vector2}
  22602. */
  22603. this.v3 = v3;
  22604. }
  22605. /**
  22606. * Returns a point on the curve.
  22607. *
  22608. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22609. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22610. * @return {Vector2} The position on the curve.
  22611. */
  22612. getPoint( t, optionalTarget = new Vector2() ) {
  22613. const point = optionalTarget;
  22614. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22615. point.set(
  22616. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22617. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  22618. );
  22619. return point;
  22620. }
  22621. copy( source ) {
  22622. super.copy( source );
  22623. this.v0.copy( source.v0 );
  22624. this.v1.copy( source.v1 );
  22625. this.v2.copy( source.v2 );
  22626. this.v3.copy( source.v3 );
  22627. return this;
  22628. }
  22629. toJSON() {
  22630. const data = super.toJSON();
  22631. data.v0 = this.v0.toArray();
  22632. data.v1 = this.v1.toArray();
  22633. data.v2 = this.v2.toArray();
  22634. data.v3 = this.v3.toArray();
  22635. return data;
  22636. }
  22637. fromJSON( json ) {
  22638. super.fromJSON( json );
  22639. this.v0.fromArray( json.v0 );
  22640. this.v1.fromArray( json.v1 );
  22641. this.v2.fromArray( json.v2 );
  22642. this.v3.fromArray( json.v3 );
  22643. return this;
  22644. }
  22645. }
  22646. /**
  22647. * A curve representing a 3D Cubic Bezier curve.
  22648. *
  22649. * @augments Curve
  22650. */
  22651. class CubicBezierCurve3 extends Curve {
  22652. /**
  22653. * Constructs a new Cubic Bezier curve.
  22654. *
  22655. * @param {Vector3} [v0] - The start point.
  22656. * @param {Vector3} [v1] - The first control point.
  22657. * @param {Vector3} [v2] - The second control point.
  22658. * @param {Vector3} [v3] - The end point.
  22659. */
  22660. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  22661. super();
  22662. /**
  22663. * This flag can be used for type testing.
  22664. *
  22665. * @type {boolean}
  22666. * @readonly
  22667. * @default true
  22668. */
  22669. this.isCubicBezierCurve3 = true;
  22670. this.type = 'CubicBezierCurve3';
  22671. /**
  22672. * The start point.
  22673. *
  22674. * @type {Vector3}
  22675. */
  22676. this.v0 = v0;
  22677. /**
  22678. * The first control point.
  22679. *
  22680. * @type {Vector3}
  22681. */
  22682. this.v1 = v1;
  22683. /**
  22684. * The second control point.
  22685. *
  22686. * @type {Vector3}
  22687. */
  22688. this.v2 = v2;
  22689. /**
  22690. * The end point.
  22691. *
  22692. * @type {Vector3}
  22693. */
  22694. this.v3 = v3;
  22695. }
  22696. /**
  22697. * Returns a point on the curve.
  22698. *
  22699. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22700. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  22701. * @return {Vector3} The position on the curve.
  22702. */
  22703. getPoint( t, optionalTarget = new Vector3() ) {
  22704. const point = optionalTarget;
  22705. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  22706. point.set(
  22707. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  22708. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  22709. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  22710. );
  22711. return point;
  22712. }
  22713. copy( source ) {
  22714. super.copy( source );
  22715. this.v0.copy( source.v0 );
  22716. this.v1.copy( source.v1 );
  22717. this.v2.copy( source.v2 );
  22718. this.v3.copy( source.v3 );
  22719. return this;
  22720. }
  22721. toJSON() {
  22722. const data = super.toJSON();
  22723. data.v0 = this.v0.toArray();
  22724. data.v1 = this.v1.toArray();
  22725. data.v2 = this.v2.toArray();
  22726. data.v3 = this.v3.toArray();
  22727. return data;
  22728. }
  22729. fromJSON( json ) {
  22730. super.fromJSON( json );
  22731. this.v0.fromArray( json.v0 );
  22732. this.v1.fromArray( json.v1 );
  22733. this.v2.fromArray( json.v2 );
  22734. this.v3.fromArray( json.v3 );
  22735. return this;
  22736. }
  22737. }
  22738. /**
  22739. * A curve representing a 2D line segment.
  22740. *
  22741. * @augments Curve
  22742. */
  22743. class LineCurve extends Curve {
  22744. /**
  22745. * Constructs a new line curve.
  22746. *
  22747. * @param {Vector2} [v1] - The start point.
  22748. * @param {Vector2} [v2] - The end point.
  22749. */
  22750. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  22751. super();
  22752. /**
  22753. * This flag can be used for type testing.
  22754. *
  22755. * @type {boolean}
  22756. * @readonly
  22757. * @default true
  22758. */
  22759. this.isLineCurve = true;
  22760. this.type = 'LineCurve';
  22761. /**
  22762. * The start point.
  22763. *
  22764. * @type {Vector2}
  22765. */
  22766. this.v1 = v1;
  22767. /**
  22768. * The end point.
  22769. *
  22770. * @type {Vector2}
  22771. */
  22772. this.v2 = v2;
  22773. }
  22774. /**
  22775. * Returns a point on the line.
  22776. *
  22777. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  22778. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22779. * @return {Vector2} The position on the line.
  22780. */
  22781. getPoint( t, optionalTarget = new Vector2() ) {
  22782. const point = optionalTarget;
  22783. if ( t === 1 ) {
  22784. point.copy( this.v2 );
  22785. } else {
  22786. point.copy( this.v2 ).sub( this.v1 );
  22787. point.multiplyScalar( t ).add( this.v1 );
  22788. }
  22789. return point;
  22790. }
  22791. // Line curve is linear, so we can overwrite default getPointAt
  22792. getPointAt( u, optionalTarget ) {
  22793. return this.getPoint( u, optionalTarget );
  22794. }
  22795. getTangent( t, optionalTarget = new Vector2() ) {
  22796. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  22797. }
  22798. getTangentAt( u, optionalTarget ) {
  22799. return this.getTangent( u, optionalTarget );
  22800. }
  22801. copy( source ) {
  22802. super.copy( source );
  22803. this.v1.copy( source.v1 );
  22804. this.v2.copy( source.v2 );
  22805. return this;
  22806. }
  22807. toJSON() {
  22808. const data = super.toJSON();
  22809. data.v1 = this.v1.toArray();
  22810. data.v2 = this.v2.toArray();
  22811. return data;
  22812. }
  22813. fromJSON( json ) {
  22814. super.fromJSON( json );
  22815. this.v1.fromArray( json.v1 );
  22816. this.v2.fromArray( json.v2 );
  22817. return this;
  22818. }
  22819. }
  22820. /**
  22821. * A curve representing a 3D line segment.
  22822. *
  22823. * @augments Curve
  22824. */
  22825. class LineCurve3 extends Curve {
  22826. /**
  22827. * Constructs a new line curve.
  22828. *
  22829. * @param {Vector3} [v1] - The start point.
  22830. * @param {Vector3} [v2] - The end point.
  22831. */
  22832. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  22833. super();
  22834. /**
  22835. * This flag can be used for type testing.
  22836. *
  22837. * @type {boolean}
  22838. * @readonly
  22839. * @default true
  22840. */
  22841. this.isLineCurve3 = true;
  22842. this.type = 'LineCurve3';
  22843. /**
  22844. * The start point.
  22845. *
  22846. * @type {Vector3}
  22847. */
  22848. this.v1 = v1;
  22849. /**
  22850. * The end point.
  22851. *
  22852. * @type {Vector2}
  22853. */
  22854. this.v2 = v2;
  22855. }
  22856. /**
  22857. * Returns a point on the line.
  22858. *
  22859. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  22860. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  22861. * @return {Vector3} The position on the line.
  22862. */
  22863. getPoint( t, optionalTarget = new Vector3() ) {
  22864. const point = optionalTarget;
  22865. if ( t === 1 ) {
  22866. point.copy( this.v2 );
  22867. } else {
  22868. point.copy( this.v2 ).sub( this.v1 );
  22869. point.multiplyScalar( t ).add( this.v1 );
  22870. }
  22871. return point;
  22872. }
  22873. // Line curve is linear, so we can overwrite default getPointAt
  22874. getPointAt( u, optionalTarget ) {
  22875. return this.getPoint( u, optionalTarget );
  22876. }
  22877. getTangent( t, optionalTarget = new Vector3() ) {
  22878. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  22879. }
  22880. getTangentAt( u, optionalTarget ) {
  22881. return this.getTangent( u, optionalTarget );
  22882. }
  22883. copy( source ) {
  22884. super.copy( source );
  22885. this.v1.copy( source.v1 );
  22886. this.v2.copy( source.v2 );
  22887. return this;
  22888. }
  22889. toJSON() {
  22890. const data = super.toJSON();
  22891. data.v1 = this.v1.toArray();
  22892. data.v2 = this.v2.toArray();
  22893. return data;
  22894. }
  22895. fromJSON( json ) {
  22896. super.fromJSON( json );
  22897. this.v1.fromArray( json.v1 );
  22898. this.v2.fromArray( json.v2 );
  22899. return this;
  22900. }
  22901. }
  22902. /**
  22903. * A curve representing a 2D Quadratic Bezier curve.
  22904. *
  22905. * ```js
  22906. * const curve = new THREE.QuadraticBezierCurve(
  22907. * new THREE.Vector2( - 10, 0 ),
  22908. * new THREE.Vector2( 20, 15 ),
  22909. * new THREE.Vector2( 10, 0 )
  22910. * )
  22911. *
  22912. * const points = curve.getPoints( 50 );
  22913. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22914. *
  22915. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22916. *
  22917. * // Create the final object to add to the scene
  22918. * const curveObject = new THREE.Line( geometry, material );
  22919. * ```
  22920. *
  22921. * @augments Curve
  22922. */
  22923. class QuadraticBezierCurve extends Curve {
  22924. /**
  22925. * Constructs a new Quadratic Bezier curve.
  22926. *
  22927. * @param {Vector2} [v0] - The start point.
  22928. * @param {Vector2} [v1] - The control point.
  22929. * @param {Vector2} [v2] - The end point.
  22930. */
  22931. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  22932. super();
  22933. /**
  22934. * This flag can be used for type testing.
  22935. *
  22936. * @type {boolean}
  22937. * @readonly
  22938. * @default true
  22939. */
  22940. this.isQuadraticBezierCurve = true;
  22941. this.type = 'QuadraticBezierCurve';
  22942. /**
  22943. * The start point.
  22944. *
  22945. * @type {Vector2}
  22946. */
  22947. this.v0 = v0;
  22948. /**
  22949. * The control point.
  22950. *
  22951. * @type {Vector2}
  22952. */
  22953. this.v1 = v1;
  22954. /**
  22955. * The end point.
  22956. *
  22957. * @type {Vector2}
  22958. */
  22959. this.v2 = v2;
  22960. }
  22961. /**
  22962. * Returns a point on the curve.
  22963. *
  22964. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22965. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22966. * @return {Vector2} The position on the curve.
  22967. */
  22968. getPoint( t, optionalTarget = new Vector2() ) {
  22969. const point = optionalTarget;
  22970. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  22971. point.set(
  22972. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  22973. QuadraticBezier( t, v0.y, v1.y, v2.y )
  22974. );
  22975. return point;
  22976. }
  22977. copy( source ) {
  22978. super.copy( source );
  22979. this.v0.copy( source.v0 );
  22980. this.v1.copy( source.v1 );
  22981. this.v2.copy( source.v2 );
  22982. return this;
  22983. }
  22984. toJSON() {
  22985. const data = super.toJSON();
  22986. data.v0 = this.v0.toArray();
  22987. data.v1 = this.v1.toArray();
  22988. data.v2 = this.v2.toArray();
  22989. return data;
  22990. }
  22991. fromJSON( json ) {
  22992. super.fromJSON( json );
  22993. this.v0.fromArray( json.v0 );
  22994. this.v1.fromArray( json.v1 );
  22995. this.v2.fromArray( json.v2 );
  22996. return this;
  22997. }
  22998. }
  22999. /**
  23000. * A curve representing a 3D Quadratic Bezier curve.
  23001. *
  23002. * @augments Curve
  23003. */
  23004. class QuadraticBezierCurve3 extends Curve {
  23005. /**
  23006. * Constructs a new Quadratic Bezier curve.
  23007. *
  23008. * @param {Vector3} [v0] - The start point.
  23009. * @param {Vector3} [v1] - The control point.
  23010. * @param {Vector3} [v2] - The end point.
  23011. */
  23012. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23013. super();
  23014. /**
  23015. * This flag can be used for type testing.
  23016. *
  23017. * @type {boolean}
  23018. * @readonly
  23019. * @default true
  23020. */
  23021. this.isQuadraticBezierCurve3 = true;
  23022. this.type = 'QuadraticBezierCurve3';
  23023. /**
  23024. * The start point.
  23025. *
  23026. * @type {Vector3}
  23027. */
  23028. this.v0 = v0;
  23029. /**
  23030. * The control point.
  23031. *
  23032. * @type {Vector3}
  23033. */
  23034. this.v1 = v1;
  23035. /**
  23036. * The end point.
  23037. *
  23038. * @type {Vector3}
  23039. */
  23040. this.v2 = v2;
  23041. }
  23042. /**
  23043. * Returns a point on the curve.
  23044. *
  23045. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23046. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23047. * @return {Vector3} The position on the curve.
  23048. */
  23049. getPoint( t, optionalTarget = new Vector3() ) {
  23050. const point = optionalTarget;
  23051. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23052. point.set(
  23053. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23054. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23055. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23056. );
  23057. return point;
  23058. }
  23059. copy( source ) {
  23060. super.copy( source );
  23061. this.v0.copy( source.v0 );
  23062. this.v1.copy( source.v1 );
  23063. this.v2.copy( source.v2 );
  23064. return this;
  23065. }
  23066. toJSON() {
  23067. const data = super.toJSON();
  23068. data.v0 = this.v0.toArray();
  23069. data.v1 = this.v1.toArray();
  23070. data.v2 = this.v2.toArray();
  23071. return data;
  23072. }
  23073. fromJSON( json ) {
  23074. super.fromJSON( json );
  23075. this.v0.fromArray( json.v0 );
  23076. this.v1.fromArray( json.v1 );
  23077. this.v2.fromArray( json.v2 );
  23078. return this;
  23079. }
  23080. }
  23081. /**
  23082. * A curve representing a 2D spline curve.
  23083. *
  23084. * ```js
  23085. * // Create a sine-like wave
  23086. * const curve = new THREE.SplineCurve( [
  23087. * new THREE.Vector2( -10, 0 ),
  23088. * new THREE.Vector2( -5, 5 ),
  23089. * new THREE.Vector2( 0, 0 ),
  23090. * new THREE.Vector2( 5, -5 ),
  23091. * new THREE.Vector2( 10, 0 )
  23092. * ] );
  23093. *
  23094. * const points = curve.getPoints( 50 );
  23095. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23096. *
  23097. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23098. *
  23099. * // Create the final object to add to the scene
  23100. * const splineObject = new THREE.Line( geometry, material );
  23101. * ```
  23102. *
  23103. * @augments Curve
  23104. */
  23105. class SplineCurve extends Curve {
  23106. /**
  23107. * Constructs a new 2D spline curve.
  23108. *
  23109. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  23110. */
  23111. constructor( points = [] ) {
  23112. super();
  23113. /**
  23114. * This flag can be used for type testing.
  23115. *
  23116. * @type {boolean}
  23117. * @readonly
  23118. * @default true
  23119. */
  23120. this.isSplineCurve = true;
  23121. this.type = 'SplineCurve';
  23122. /**
  23123. * An array of 2D points defining the curve.
  23124. *
  23125. * @type {Array<Vector2>}
  23126. */
  23127. this.points = points;
  23128. }
  23129. /**
  23130. * Returns a point on the curve.
  23131. *
  23132. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23133. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23134. * @return {Vector2} The position on the curve.
  23135. */
  23136. getPoint( t, optionalTarget = new Vector2() ) {
  23137. const point = optionalTarget;
  23138. const points = this.points;
  23139. const p = ( points.length - 1 ) * t;
  23140. const intPoint = Math.floor( p );
  23141. const weight = p - intPoint;
  23142. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23143. const p1 = points[ intPoint ];
  23144. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23145. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23146. point.set(
  23147. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23148. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23149. );
  23150. return point;
  23151. }
  23152. copy( source ) {
  23153. super.copy( source );
  23154. this.points = [];
  23155. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23156. const point = source.points[ i ];
  23157. this.points.push( point.clone() );
  23158. }
  23159. return this;
  23160. }
  23161. toJSON() {
  23162. const data = super.toJSON();
  23163. data.points = [];
  23164. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23165. const point = this.points[ i ];
  23166. data.points.push( point.toArray() );
  23167. }
  23168. return data;
  23169. }
  23170. fromJSON( json ) {
  23171. super.fromJSON( json );
  23172. this.points = [];
  23173. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23174. const point = json.points[ i ];
  23175. this.points.push( new Vector2().fromArray( point ) );
  23176. }
  23177. return this;
  23178. }
  23179. }
  23180. var Curves = /*#__PURE__*/Object.freeze({
  23181. __proto__: null,
  23182. ArcCurve: ArcCurve,
  23183. CatmullRomCurve3: CatmullRomCurve3,
  23184. CubicBezierCurve: CubicBezierCurve,
  23185. CubicBezierCurve3: CubicBezierCurve3,
  23186. EllipseCurve: EllipseCurve,
  23187. LineCurve: LineCurve,
  23188. LineCurve3: LineCurve3,
  23189. QuadraticBezierCurve: QuadraticBezierCurve,
  23190. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23191. SplineCurve: SplineCurve
  23192. });
  23193. /**
  23194. * A base class extending {@link Curve}. `CurvePath` is simply an
  23195. * array of connected curves, but retains the API of a curve.
  23196. *
  23197. * @augments Curve
  23198. */
  23199. class CurvePath extends Curve {
  23200. /**
  23201. * Constructs a new curve path.
  23202. */
  23203. constructor() {
  23204. super();
  23205. this.type = 'CurvePath';
  23206. /**
  23207. * An array of curves defining the
  23208. * path.
  23209. *
  23210. * @type {Array<Curve>}
  23211. */
  23212. this.curves = [];
  23213. /**
  23214. * Whether the path should automatically be closed
  23215. * by a line curve.
  23216. *
  23217. * @type {boolean}
  23218. * @default false
  23219. */
  23220. this.autoClose = false;
  23221. }
  23222. /**
  23223. * Adds a curve to this curve path.
  23224. *
  23225. * @param {Curve} curve - The curve to add.
  23226. */
  23227. add( curve ) {
  23228. this.curves.push( curve );
  23229. }
  23230. /**
  23231. * Adds a line curve to close the path.
  23232. *
  23233. * @return {CurvePath} A reference to this curve path.
  23234. */
  23235. closePath() {
  23236. // Add a line curve if start and end of lines are not connected
  23237. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23238. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23239. if ( ! startPoint.equals( endPoint ) ) {
  23240. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  23241. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  23242. }
  23243. return this;
  23244. }
  23245. /**
  23246. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  23247. * for the given interpolation factor.
  23248. *
  23249. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23250. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23251. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23252. */
  23253. getPoint( t, optionalTarget ) {
  23254. // To get accurate point with reference to
  23255. // entire path distance at time t,
  23256. // following has to be done:
  23257. // 1. Length of each sub path have to be known
  23258. // 2. Locate and identify type of curve
  23259. // 3. Get t for the curve
  23260. // 4. Return curve.getPointAt(t')
  23261. const d = t * this.getLength();
  23262. const curveLengths = this.getCurveLengths();
  23263. let i = 0;
  23264. // To think about boundaries points.
  23265. while ( i < curveLengths.length ) {
  23266. if ( curveLengths[ i ] >= d ) {
  23267. const diff = curveLengths[ i ] - d;
  23268. const curve = this.curves[ i ];
  23269. const segmentLength = curve.getLength();
  23270. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23271. return curve.getPointAt( u, optionalTarget );
  23272. }
  23273. i ++;
  23274. }
  23275. return null;
  23276. // loop where sum != 0, sum > d , sum+1 <d
  23277. }
  23278. getLength() {
  23279. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23280. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23281. // getPoint() depends on getLength
  23282. const lens = this.getCurveLengths();
  23283. return lens[ lens.length - 1 ];
  23284. }
  23285. updateArcLengths() {
  23286. // cacheLengths must be recalculated.
  23287. this.needsUpdate = true;
  23288. this.cacheLengths = null;
  23289. this.getCurveLengths();
  23290. }
  23291. /**
  23292. * Returns list of cumulative curve lengths of the defined curves.
  23293. *
  23294. * @return {Array<number>} The curve lengths.
  23295. */
  23296. getCurveLengths() {
  23297. // Compute lengths and cache them
  23298. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23299. // We use cache values if curves and cache array are same length
  23300. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23301. return this.cacheLengths;
  23302. }
  23303. // Get length of sub-curve
  23304. // Push sums into cached array
  23305. const lengths = [];
  23306. let sums = 0;
  23307. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23308. sums += this.curves[ i ].getLength();
  23309. lengths.push( sums );
  23310. }
  23311. this.cacheLengths = lengths;
  23312. return lengths;
  23313. }
  23314. getSpacedPoints( divisions = 40 ) {
  23315. const points = [];
  23316. for ( let i = 0; i <= divisions; i ++ ) {
  23317. points.push( this.getPoint( i / divisions ) );
  23318. }
  23319. if ( this.autoClose ) {
  23320. points.push( points[ 0 ] );
  23321. }
  23322. return points;
  23323. }
  23324. getPoints( divisions = 12 ) {
  23325. const points = [];
  23326. let last;
  23327. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23328. const curve = curves[ i ];
  23329. const resolution = curve.isEllipseCurve ? divisions * 2
  23330. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  23331. : curve.isSplineCurve ? divisions * curve.points.length
  23332. : divisions;
  23333. const pts = curve.getPoints( resolution );
  23334. for ( let j = 0; j < pts.length; j ++ ) {
  23335. const point = pts[ j ];
  23336. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23337. points.push( point );
  23338. last = point;
  23339. }
  23340. }
  23341. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23342. points.push( points[ 0 ] );
  23343. }
  23344. return points;
  23345. }
  23346. copy( source ) {
  23347. super.copy( source );
  23348. this.curves = [];
  23349. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23350. const curve = source.curves[ i ];
  23351. this.curves.push( curve.clone() );
  23352. }
  23353. this.autoClose = source.autoClose;
  23354. return this;
  23355. }
  23356. toJSON() {
  23357. const data = super.toJSON();
  23358. data.autoClose = this.autoClose;
  23359. data.curves = [];
  23360. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23361. const curve = this.curves[ i ];
  23362. data.curves.push( curve.toJSON() );
  23363. }
  23364. return data;
  23365. }
  23366. fromJSON( json ) {
  23367. super.fromJSON( json );
  23368. this.autoClose = json.autoClose;
  23369. this.curves = [];
  23370. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23371. const curve = json.curves[ i ];
  23372. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23373. }
  23374. return this;
  23375. }
  23376. }
  23377. /**
  23378. * A 2D path representation. The class provides methods for creating paths
  23379. * and contours of 2D shapes similar to the 2D Canvas API.
  23380. *
  23381. * ```js
  23382. * const path = new THREE.Path();
  23383. *
  23384. * path.lineTo( 0, 0.8 );
  23385. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  23386. * path.lineTo( 1, 1 );
  23387. *
  23388. * const points = path.getPoints();
  23389. *
  23390. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23391. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  23392. *
  23393. * const line = new THREE.Line( geometry, material );
  23394. * scene.add( line );
  23395. * ```
  23396. *
  23397. * @augments CurvePath
  23398. */
  23399. class Path extends CurvePath {
  23400. /**
  23401. * Constructs a new path.
  23402. *
  23403. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  23404. */
  23405. constructor( points ) {
  23406. super();
  23407. this.type = 'Path';
  23408. /**
  23409. * The current offset of the path. Any new curve added will start here.
  23410. *
  23411. * @type {Vector2}
  23412. */
  23413. this.currentPoint = new Vector2();
  23414. if ( points ) {
  23415. this.setFromPoints( points );
  23416. }
  23417. }
  23418. /**
  23419. * Creates a path from the given list of points. The points are added
  23420. * to the path as instances of {@link LineCurve}.
  23421. *
  23422. * @param {Array<Vector2>} points - An array of 2D points.
  23423. * @return {Path} A reference to this path.
  23424. */
  23425. setFromPoints( points ) {
  23426. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23427. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23428. this.lineTo( points[ i ].x, points[ i ].y );
  23429. }
  23430. return this;
  23431. }
  23432. /**
  23433. * Moves {@link Path#currentPoint} to the given point.
  23434. *
  23435. * @param {number} x - The x coordinate.
  23436. * @param {number} y - The y coordinate.
  23437. * @return {Path} A reference to this path.
  23438. */
  23439. moveTo( x, y ) {
  23440. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23441. return this;
  23442. }
  23443. /**
  23444. * Adds an instance of {@link LineCurve} to the path by connecting
  23445. * the current point with the given one.
  23446. *
  23447. * @param {number} x - The x coordinate of the end point.
  23448. * @param {number} y - The y coordinate of the end point.
  23449. * @return {Path} A reference to this path.
  23450. */
  23451. lineTo( x, y ) {
  23452. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  23453. this.curves.push( curve );
  23454. this.currentPoint.set( x, y );
  23455. return this;
  23456. }
  23457. /**
  23458. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  23459. * the current point with the given one.
  23460. *
  23461. * @param {number} aCPx - The x coordinate of the control point.
  23462. * @param {number} aCPy - The y coordinate of the control point.
  23463. * @param {number} aX - The x coordinate of the end point.
  23464. * @param {number} aY - The y coordinate of the end point.
  23465. * @return {Path} A reference to this path.
  23466. */
  23467. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  23468. const curve = new QuadraticBezierCurve(
  23469. this.currentPoint.clone(),
  23470. new Vector2( aCPx, aCPy ),
  23471. new Vector2( aX, aY )
  23472. );
  23473. this.curves.push( curve );
  23474. this.currentPoint.set( aX, aY );
  23475. return this;
  23476. }
  23477. /**
  23478. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  23479. * the current point with the given one.
  23480. *
  23481. * @param {number} aCP1x - The x coordinate of the first control point.
  23482. * @param {number} aCP1y - The y coordinate of the first control point.
  23483. * @param {number} aCP2x - The x coordinate of the second control point.
  23484. * @param {number} aCP2y - The y coordinate of the second control point.
  23485. * @param {number} aX - The x coordinate of the end point.
  23486. * @param {number} aY - The y coordinate of the end point.
  23487. * @return {Path} A reference to this path.
  23488. */
  23489. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23490. const curve = new CubicBezierCurve(
  23491. this.currentPoint.clone(),
  23492. new Vector2( aCP1x, aCP1y ),
  23493. new Vector2( aCP2x, aCP2y ),
  23494. new Vector2( aX, aY )
  23495. );
  23496. this.curves.push( curve );
  23497. this.currentPoint.set( aX, aY );
  23498. return this;
  23499. }
  23500. /**
  23501. * Adds an instance of {@link SplineCurve} to the path by connecting
  23502. * the current point with the given list of points.
  23503. *
  23504. * @param {Array<Vector2>} pts - An array of points in 2D space.
  23505. * @return {Path} A reference to this path.
  23506. */
  23507. splineThru( pts ) {
  23508. const npts = [ this.currentPoint.clone() ].concat( pts );
  23509. const curve = new SplineCurve( npts );
  23510. this.curves.push( curve );
  23511. this.currentPoint.copy( pts[ pts.length - 1 ] );
  23512. return this;
  23513. }
  23514. /**
  23515. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  23516. * to the current point.
  23517. *
  23518. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  23519. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  23520. * @param {number} aRadius - The radius of the arc.
  23521. * @param {number} aStartAngle - The start angle in radians.
  23522. * @param {number} aEndAngle - The end angle in radians.
  23523. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  23524. * @return {Path} A reference to this path.
  23525. */
  23526. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23527. const x0 = this.currentPoint.x;
  23528. const y0 = this.currentPoint.y;
  23529. this.absarc( aX + x0, aY + y0, aRadius,
  23530. aStartAngle, aEndAngle, aClockwise );
  23531. return this;
  23532. }
  23533. /**
  23534. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  23535. *
  23536. * @param {number} aX - The x coordinate of the center of the arc.
  23537. * @param {number} aY - The y coordinate of the center of the arc.
  23538. * @param {number} aRadius - The radius of the arc.
  23539. * @param {number} aStartAngle - The start angle in radians.
  23540. * @param {number} aEndAngle - The end angle in radians.
  23541. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  23542. * @return {Path} A reference to this path.
  23543. */
  23544. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23545. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23546. return this;
  23547. }
  23548. /**
  23549. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  23550. * to the current point
  23551. *
  23552. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  23553. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  23554. * @param {number} xRadius - The radius of the ellipse in the x axis.
  23555. * @param {number} yRadius - The radius of the ellipse in the y axis.
  23556. * @param {number} aStartAngle - The start angle in radians.
  23557. * @param {number} aEndAngle - The end angle in radians.
  23558. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  23559. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23560. * @return {Path} A reference to this path.
  23561. */
  23562. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23563. const x0 = this.currentPoint.x;
  23564. const y0 = this.currentPoint.y;
  23565. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23566. return this;
  23567. }
  23568. /**
  23569. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  23570. *
  23571. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  23572. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  23573. * @param {number} xRadius - The radius of the ellipse in the x axis.
  23574. * @param {number} yRadius - The radius of the ellipse in the y axis.
  23575. * @param {number} aStartAngle - The start angle in radians.
  23576. * @param {number} aEndAngle - The end angle in radians.
  23577. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  23578. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23579. * @return {Path} A reference to this path.
  23580. */
  23581. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23582. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  23583. if ( this.curves.length > 0 ) {
  23584. // if a previous curve is present, attempt to join
  23585. const firstPoint = curve.getPoint( 0 );
  23586. if ( ! firstPoint.equals( this.currentPoint ) ) {
  23587. this.lineTo( firstPoint.x, firstPoint.y );
  23588. }
  23589. }
  23590. this.curves.push( curve );
  23591. const lastPoint = curve.getPoint( 1 );
  23592. this.currentPoint.copy( lastPoint );
  23593. return this;
  23594. }
  23595. copy( source ) {
  23596. super.copy( source );
  23597. this.currentPoint.copy( source.currentPoint );
  23598. return this;
  23599. }
  23600. toJSON() {
  23601. const data = super.toJSON();
  23602. data.currentPoint = this.currentPoint.toArray();
  23603. return data;
  23604. }
  23605. fromJSON( json ) {
  23606. super.fromJSON( json );
  23607. this.currentPoint.fromArray( json.currentPoint );
  23608. return this;
  23609. }
  23610. }
  23611. /**
  23612. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  23613. *
  23614. * ```js
  23615. * const points = [];
  23616. * for ( let i = 0; i < 10; i ++ ) {
  23617. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  23618. * }
  23619. * const geometry = new THREE.LatheGeometry( points );
  23620. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23621. * const lathe = new THREE.Mesh( geometry, material );
  23622. * scene.add( lathe );
  23623. * ```
  23624. *
  23625. * @augments BufferGeometry
  23626. */
  23627. class LatheGeometry extends BufferGeometry {
  23628. /**
  23629. * Constructs a new lathe geometry.
  23630. *
  23631. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  23632. * must be greater than zero.
  23633. * @param {number} [segments=12] - The number of circumference segments to generate.
  23634. * @param {number} [phiStart=0] - The starting angle in radians.
  23635. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  23636. * closed lathe, less than 2PI is a portion.
  23637. */
  23638. 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 ) {
  23639. super();
  23640. this.type = 'LatheGeometry';
  23641. /**
  23642. * Holds the constructor parameters that have been
  23643. * used to generate the geometry. Any modification
  23644. * after instantiation does not change the geometry.
  23645. *
  23646. * @type {Object}
  23647. */
  23648. this.parameters = {
  23649. points: points,
  23650. segments: segments,
  23651. phiStart: phiStart,
  23652. phiLength: phiLength
  23653. };
  23654. segments = Math.floor( segments );
  23655. // clamp phiLength so it's in range of [ 0, 2PI ]
  23656. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  23657. // buffers
  23658. const indices = [];
  23659. const vertices = [];
  23660. const uvs = [];
  23661. const initNormals = [];
  23662. const normals = [];
  23663. // helper variables
  23664. const inverseSegments = 1.0 / segments;
  23665. const vertex = new Vector3();
  23666. const uv = new Vector2();
  23667. const normal = new Vector3();
  23668. const curNormal = new Vector3();
  23669. const prevNormal = new Vector3();
  23670. let dx = 0;
  23671. let dy = 0;
  23672. // pre-compute normals for initial "meridian"
  23673. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  23674. switch ( j ) {
  23675. case 0: // special handling for 1st vertex on path
  23676. dx = points[ j + 1 ].x - points[ j ].x;
  23677. dy = points[ j + 1 ].y - points[ j ].y;
  23678. normal.x = dy * 1.0;
  23679. normal.y = - dx;
  23680. normal.z = dy * 0.0;
  23681. prevNormal.copy( normal );
  23682. normal.normalize();
  23683. initNormals.push( normal.x, normal.y, normal.z );
  23684. break;
  23685. case ( points.length - 1 ): // special handling for last Vertex on path
  23686. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  23687. break;
  23688. default: // default handling for all vertices in between
  23689. dx = points[ j + 1 ].x - points[ j ].x;
  23690. dy = points[ j + 1 ].y - points[ j ].y;
  23691. normal.x = dy * 1.0;
  23692. normal.y = - dx;
  23693. normal.z = dy * 0.0;
  23694. curNormal.copy( normal );
  23695. normal.x += prevNormal.x;
  23696. normal.y += prevNormal.y;
  23697. normal.z += prevNormal.z;
  23698. normal.normalize();
  23699. initNormals.push( normal.x, normal.y, normal.z );
  23700. prevNormal.copy( curNormal );
  23701. }
  23702. }
  23703. // generate vertices, uvs and normals
  23704. for ( let i = 0; i <= segments; i ++ ) {
  23705. const phi = phiStart + i * inverseSegments * phiLength;
  23706. const sin = Math.sin( phi );
  23707. const cos = Math.cos( phi );
  23708. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  23709. // vertex
  23710. vertex.x = points[ j ].x * sin;
  23711. vertex.y = points[ j ].y;
  23712. vertex.z = points[ j ].x * cos;
  23713. vertices.push( vertex.x, vertex.y, vertex.z );
  23714. // uv
  23715. uv.x = i / segments;
  23716. uv.y = j / ( points.length - 1 );
  23717. uvs.push( uv.x, uv.y );
  23718. // normal
  23719. const x = initNormals[ 3 * j + 0 ] * sin;
  23720. const y = initNormals[ 3 * j + 1 ];
  23721. const z = initNormals[ 3 * j + 0 ] * cos;
  23722. normals.push( x, y, z );
  23723. }
  23724. }
  23725. // indices
  23726. for ( let i = 0; i < segments; i ++ ) {
  23727. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  23728. const base = j + i * points.length;
  23729. const a = base;
  23730. const b = base + points.length;
  23731. const c = base + points.length + 1;
  23732. const d = base + 1;
  23733. // faces
  23734. indices.push( a, b, d );
  23735. indices.push( c, d, b );
  23736. }
  23737. }
  23738. // build geometry
  23739. this.setIndex( indices );
  23740. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23741. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23742. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23743. }
  23744. copy( source ) {
  23745. super.copy( source );
  23746. this.parameters = Object.assign( {}, source.parameters );
  23747. return this;
  23748. }
  23749. /**
  23750. * Factory method for creating an instance of this class from the given
  23751. * JSON object.
  23752. *
  23753. * @param {Object} data - A JSON object representing the serialized geometry.
  23754. * @return {LatheGeometry} A new instance.
  23755. */
  23756. static fromJSON( data ) {
  23757. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  23758. }
  23759. }
  23760. /**
  23761. * A geometry class for a capsule with given radii and height. It is constructed using a lathe.
  23762. *
  23763. * ```js
  23764. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8 );
  23765. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  23766. * const capsule = new THREE.Mesh( geometry, material );
  23767. * scene.add( capsule );
  23768. * ```
  23769. *
  23770. * @augments LatheGeometry
  23771. */
  23772. class CapsuleGeometry extends LatheGeometry {
  23773. /**
  23774. * Constructs a new capsule geometry.
  23775. *
  23776. * @param {number} [radius=1] - Radius of the capsule.
  23777. * @param {number} [length=1] - Length of the middle section.
  23778. * @param {number} [capSegments=4] - Number of curve segments used to build the caps.
  23779. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule.
  23780. */
  23781. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  23782. const path = new Path();
  23783. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  23784. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  23785. super( path.getPoints( capSegments ), radialSegments );
  23786. this.type = 'CapsuleGeometry';
  23787. /**
  23788. * Holds the constructor parameters that have been
  23789. * used to generate the geometry. Any modification
  23790. * after instantiation does not change the geometry.
  23791. *
  23792. * @type {Object}
  23793. */
  23794. this.parameters = {
  23795. radius: radius,
  23796. length: length,
  23797. capSegments: capSegments,
  23798. radialSegments: radialSegments,
  23799. };
  23800. }
  23801. /**
  23802. * Factory method for creating an instance of this class from the given
  23803. * JSON object.
  23804. *
  23805. * @param {Object} data - A JSON object representing the serialized geometry.
  23806. * @return {CapsuleGeometry} A new instance.
  23807. */
  23808. static fromJSON( data ) {
  23809. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  23810. }
  23811. }
  23812. /**
  23813. * A simple shape of Euclidean geometry. It is constructed from a
  23814. * number of triangular segments that are oriented around a central point and
  23815. * extend as far out as a given radius. It is built counter-clockwise from a
  23816. * start angle and a given central angle. It can also be used to create
  23817. * regular polygons, where the number of segments determines the number of
  23818. * sides.
  23819. *
  23820. * ```js
  23821. * const geometry = new THREE.CircleGeometry( 5, 32 );
  23822. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23823. * const circle = new THREE.Mesh( geometry, material );
  23824. * scene.add( circle )
  23825. * ```
  23826. *
  23827. * @augments BufferGeometry
  23828. */
  23829. class CircleGeometry extends BufferGeometry {
  23830. /**
  23831. * Constructs a new circle geometry.
  23832. *
  23833. * @param {number} [radius=1] - Radius of the circle.
  23834. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  23835. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  23836. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  23837. * of the circular sector in radians. The default value results in a complete circle.
  23838. */
  23839. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23840. super();
  23841. this.type = 'CircleGeometry';
  23842. /**
  23843. * Holds the constructor parameters that have been
  23844. * used to generate the geometry. Any modification
  23845. * after instantiation does not change the geometry.
  23846. *
  23847. * @type {Object}
  23848. */
  23849. this.parameters = {
  23850. radius: radius,
  23851. segments: segments,
  23852. thetaStart: thetaStart,
  23853. thetaLength: thetaLength
  23854. };
  23855. segments = Math.max( 3, segments );
  23856. // buffers
  23857. const indices = [];
  23858. const vertices = [];
  23859. const normals = [];
  23860. const uvs = [];
  23861. // helper variables
  23862. const vertex = new Vector3();
  23863. const uv = new Vector2();
  23864. // center point
  23865. vertices.push( 0, 0, 0 );
  23866. normals.push( 0, 0, 1 );
  23867. uvs.push( 0.5, 0.5 );
  23868. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  23869. const segment = thetaStart + s / segments * thetaLength;
  23870. // vertex
  23871. vertex.x = radius * Math.cos( segment );
  23872. vertex.y = radius * Math.sin( segment );
  23873. vertices.push( vertex.x, vertex.y, vertex.z );
  23874. // normal
  23875. normals.push( 0, 0, 1 );
  23876. // uvs
  23877. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  23878. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  23879. uvs.push( uv.x, uv.y );
  23880. }
  23881. // indices
  23882. for ( let i = 1; i <= segments; i ++ ) {
  23883. indices.push( i, i + 1, 0 );
  23884. }
  23885. // build geometry
  23886. this.setIndex( indices );
  23887. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23888. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23889. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23890. }
  23891. copy( source ) {
  23892. super.copy( source );
  23893. this.parameters = Object.assign( {}, source.parameters );
  23894. return this;
  23895. }
  23896. /**
  23897. * Factory method for creating an instance of this class from the given
  23898. * JSON object.
  23899. *
  23900. * @param {Object} data - A JSON object representing the serialized geometry.
  23901. * @return {CircleGeometry} A new instance.
  23902. */
  23903. static fromJSON( data ) {
  23904. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  23905. }
  23906. }
  23907. /**
  23908. * A geometry class for representing a cylinder.
  23909. *
  23910. * ```js
  23911. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  23912. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23913. * const cylinder = new THREE.Mesh( geometry, material );
  23914. * scene.add( cylinder );
  23915. * ```
  23916. *
  23917. * @augments BufferGeometry
  23918. */
  23919. class CylinderGeometry extends BufferGeometry {
  23920. /**
  23921. * Constructs a new cylinder geometry.
  23922. *
  23923. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  23924. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  23925. * @param {number} [height=1] - Height of the cylinder.
  23926. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  23927. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  23928. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  23929. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  23930. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  23931. * The default value results in a complete cylinder.
  23932. */
  23933. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23934. super();
  23935. this.type = 'CylinderGeometry';
  23936. /**
  23937. * Holds the constructor parameters that have been
  23938. * used to generate the geometry. Any modification
  23939. * after instantiation does not change the geometry.
  23940. *
  23941. * @type {Object}
  23942. */
  23943. this.parameters = {
  23944. radiusTop: radiusTop,
  23945. radiusBottom: radiusBottom,
  23946. height: height,
  23947. radialSegments: radialSegments,
  23948. heightSegments: heightSegments,
  23949. openEnded: openEnded,
  23950. thetaStart: thetaStart,
  23951. thetaLength: thetaLength
  23952. };
  23953. const scope = this;
  23954. radialSegments = Math.floor( radialSegments );
  23955. heightSegments = Math.floor( heightSegments );
  23956. // buffers
  23957. const indices = [];
  23958. const vertices = [];
  23959. const normals = [];
  23960. const uvs = [];
  23961. // helper variables
  23962. let index = 0;
  23963. const indexArray = [];
  23964. const halfHeight = height / 2;
  23965. let groupStart = 0;
  23966. // generate geometry
  23967. generateTorso();
  23968. if ( openEnded === false ) {
  23969. if ( radiusTop > 0 ) generateCap( true );
  23970. if ( radiusBottom > 0 ) generateCap( false );
  23971. }
  23972. // build geometry
  23973. this.setIndex( indices );
  23974. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23975. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23976. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23977. function generateTorso() {
  23978. const normal = new Vector3();
  23979. const vertex = new Vector3();
  23980. let groupCount = 0;
  23981. // this will be used to calculate the normal
  23982. const slope = ( radiusBottom - radiusTop ) / height;
  23983. // generate vertices, normals and uvs
  23984. for ( let y = 0; y <= heightSegments; y ++ ) {
  23985. const indexRow = [];
  23986. const v = y / heightSegments;
  23987. // calculate the radius of the current row
  23988. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  23989. for ( let x = 0; x <= radialSegments; x ++ ) {
  23990. const u = x / radialSegments;
  23991. const theta = u * thetaLength + thetaStart;
  23992. const sinTheta = Math.sin( theta );
  23993. const cosTheta = Math.cos( theta );
  23994. // vertex
  23995. vertex.x = radius * sinTheta;
  23996. vertex.y = - v * height + halfHeight;
  23997. vertex.z = radius * cosTheta;
  23998. vertices.push( vertex.x, vertex.y, vertex.z );
  23999. // normal
  24000. normal.set( sinTheta, slope, cosTheta ).normalize();
  24001. normals.push( normal.x, normal.y, normal.z );
  24002. // uv
  24003. uvs.push( u, 1 - v );
  24004. // save index of vertex in respective row
  24005. indexRow.push( index ++ );
  24006. }
  24007. // now save vertices of the row in our index array
  24008. indexArray.push( indexRow );
  24009. }
  24010. // generate indices
  24011. for ( let x = 0; x < radialSegments; x ++ ) {
  24012. for ( let y = 0; y < heightSegments; y ++ ) {
  24013. // we use the index array to access the correct indices
  24014. const a = indexArray[ y ][ x ];
  24015. const b = indexArray[ y + 1 ][ x ];
  24016. const c = indexArray[ y + 1 ][ x + 1 ];
  24017. const d = indexArray[ y ][ x + 1 ];
  24018. // faces
  24019. if ( radiusTop > 0 || y !== 0 ) {
  24020. indices.push( a, b, d );
  24021. groupCount += 3;
  24022. }
  24023. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  24024. indices.push( b, c, d );
  24025. groupCount += 3;
  24026. }
  24027. }
  24028. }
  24029. // add a group to the geometry. this will ensure multi material support
  24030. scope.addGroup( groupStart, groupCount, 0 );
  24031. // calculate new start value for groups
  24032. groupStart += groupCount;
  24033. }
  24034. function generateCap( top ) {
  24035. // save the index of the first center vertex
  24036. const centerIndexStart = index;
  24037. const uv = new Vector2();
  24038. const vertex = new Vector3();
  24039. let groupCount = 0;
  24040. const radius = ( top === true ) ? radiusTop : radiusBottom;
  24041. const sign = ( top === true ) ? 1 : - 1;
  24042. // first we generate the center vertex data of the cap.
  24043. // because the geometry needs one set of uvs per face,
  24044. // we must generate a center vertex per face/segment
  24045. for ( let x = 1; x <= radialSegments; x ++ ) {
  24046. // vertex
  24047. vertices.push( 0, halfHeight * sign, 0 );
  24048. // normal
  24049. normals.push( 0, sign, 0 );
  24050. // uv
  24051. uvs.push( 0.5, 0.5 );
  24052. // increase index
  24053. index ++;
  24054. }
  24055. // save the index of the last center vertex
  24056. const centerIndexEnd = index;
  24057. // now we generate the surrounding vertices, normals and uvs
  24058. for ( let x = 0; x <= radialSegments; x ++ ) {
  24059. const u = x / radialSegments;
  24060. const theta = u * thetaLength + thetaStart;
  24061. const cosTheta = Math.cos( theta );
  24062. const sinTheta = Math.sin( theta );
  24063. // vertex
  24064. vertex.x = radius * sinTheta;
  24065. vertex.y = halfHeight * sign;
  24066. vertex.z = radius * cosTheta;
  24067. vertices.push( vertex.x, vertex.y, vertex.z );
  24068. // normal
  24069. normals.push( 0, sign, 0 );
  24070. // uv
  24071. uv.x = ( cosTheta * 0.5 ) + 0.5;
  24072. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  24073. uvs.push( uv.x, uv.y );
  24074. // increase index
  24075. index ++;
  24076. }
  24077. // generate indices
  24078. for ( let x = 0; x < radialSegments; x ++ ) {
  24079. const c = centerIndexStart + x;
  24080. const i = centerIndexEnd + x;
  24081. if ( top === true ) {
  24082. // face top
  24083. indices.push( i, i + 1, c );
  24084. } else {
  24085. // face bottom
  24086. indices.push( i + 1, i, c );
  24087. }
  24088. groupCount += 3;
  24089. }
  24090. // add a group to the geometry. this will ensure multi material support
  24091. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  24092. // calculate new start value for groups
  24093. groupStart += groupCount;
  24094. }
  24095. }
  24096. copy( source ) {
  24097. super.copy( source );
  24098. this.parameters = Object.assign( {}, source.parameters );
  24099. return this;
  24100. }
  24101. /**
  24102. * Factory method for creating an instance of this class from the given
  24103. * JSON object.
  24104. *
  24105. * @param {Object} data - A JSON object representing the serialized geometry.
  24106. * @return {CylinderGeometry} A new instance.
  24107. */
  24108. static fromJSON( data ) {
  24109. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  24110. }
  24111. }
  24112. /**
  24113. * A geometry class for representing a cone.
  24114. *
  24115. * ```js
  24116. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  24117. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  24118. * const cone = new THREE.Mesh(geometry, material );
  24119. * scene.add( cone );
  24120. * ```
  24121. *
  24122. * @augments CylinderGeometry
  24123. */
  24124. class ConeGeometry extends CylinderGeometry {
  24125. /**
  24126. * Constructs a new cone geometry.
  24127. *
  24128. * @param {number} [radius=1] - Radius of the cone base.
  24129. * @param {number} [height=1] - Height of the cone.
  24130. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  24131. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  24132. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  24133. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  24134. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  24135. * The default value results in a complete cone.
  24136. */
  24137. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  24138. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  24139. this.type = 'ConeGeometry';
  24140. /**
  24141. * Holds the constructor parameters that have been
  24142. * used to generate the geometry. Any modification
  24143. * after instantiation does not change the geometry.
  24144. *
  24145. * @type {Object}
  24146. */
  24147. this.parameters = {
  24148. radius: radius,
  24149. height: height,
  24150. radialSegments: radialSegments,
  24151. heightSegments: heightSegments,
  24152. openEnded: openEnded,
  24153. thetaStart: thetaStart,
  24154. thetaLength: thetaLength
  24155. };
  24156. }
  24157. /**
  24158. * Factory method for creating an instance of this class from the given
  24159. * JSON object.
  24160. *
  24161. * @param {Object} data - A JSON object representing the serialized geometry.
  24162. * @return {ConeGeometry} A new instance.
  24163. */
  24164. static fromJSON( data ) {
  24165. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  24166. }
  24167. }
  24168. /**
  24169. * A polyhedron is a solid in three dimensions with flat faces. This class
  24170. * will take an array of vertices, project them onto a sphere, and then
  24171. * divide them up to the desired level of detail.
  24172. *
  24173. * @augments BufferGeometry
  24174. */
  24175. class PolyhedronGeometry extends BufferGeometry {
  24176. /**
  24177. * Constructs a new polyhedron geometry.
  24178. *
  24179. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  24180. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  24181. * @param {number} [radius=1] - The radius of the shape.
  24182. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  24183. */
  24184. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  24185. super();
  24186. this.type = 'PolyhedronGeometry';
  24187. /**
  24188. * Holds the constructor parameters that have been
  24189. * used to generate the geometry. Any modification
  24190. * after instantiation does not change the geometry.
  24191. *
  24192. * @type {Object}
  24193. */
  24194. this.parameters = {
  24195. vertices: vertices,
  24196. indices: indices,
  24197. radius: radius,
  24198. detail: detail
  24199. };
  24200. // default buffer data
  24201. const vertexBuffer = [];
  24202. const uvBuffer = [];
  24203. // the subdivision creates the vertex buffer data
  24204. subdivide( detail );
  24205. // all vertices should lie on a conceptual sphere with a given radius
  24206. applyRadius( radius );
  24207. // finally, create the uv data
  24208. generateUVs();
  24209. // build non-indexed geometry
  24210. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  24211. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  24212. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  24213. if ( detail === 0 ) {
  24214. this.computeVertexNormals(); // flat normals
  24215. } else {
  24216. this.normalizeNormals(); // smooth normals
  24217. }
  24218. // helper functions
  24219. function subdivide( detail ) {
  24220. const a = new Vector3();
  24221. const b = new Vector3();
  24222. const c = new Vector3();
  24223. // iterate over all faces and apply a subdivision with the given detail value
  24224. for ( let i = 0; i < indices.length; i += 3 ) {
  24225. // get the vertices of the face
  24226. getVertexByIndex( indices[ i + 0 ], a );
  24227. getVertexByIndex( indices[ i + 1 ], b );
  24228. getVertexByIndex( indices[ i + 2 ], c );
  24229. // perform subdivision
  24230. subdivideFace( a, b, c, detail );
  24231. }
  24232. }
  24233. function subdivideFace( a, b, c, detail ) {
  24234. const cols = detail + 1;
  24235. // we use this multidimensional array as a data structure for creating the subdivision
  24236. const v = [];
  24237. // construct all of the vertices for this subdivision
  24238. for ( let i = 0; i <= cols; i ++ ) {
  24239. v[ i ] = [];
  24240. const aj = a.clone().lerp( c, i / cols );
  24241. const bj = b.clone().lerp( c, i / cols );
  24242. const rows = cols - i;
  24243. for ( let j = 0; j <= rows; j ++ ) {
  24244. if ( j === 0 && i === cols ) {
  24245. v[ i ][ j ] = aj;
  24246. } else {
  24247. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  24248. }
  24249. }
  24250. }
  24251. // construct all of the faces
  24252. for ( let i = 0; i < cols; i ++ ) {
  24253. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  24254. const k = Math.floor( j / 2 );
  24255. if ( j % 2 === 0 ) {
  24256. pushVertex( v[ i ][ k + 1 ] );
  24257. pushVertex( v[ i + 1 ][ k ] );
  24258. pushVertex( v[ i ][ k ] );
  24259. } else {
  24260. pushVertex( v[ i ][ k + 1 ] );
  24261. pushVertex( v[ i + 1 ][ k + 1 ] );
  24262. pushVertex( v[ i + 1 ][ k ] );
  24263. }
  24264. }
  24265. }
  24266. }
  24267. function applyRadius( radius ) {
  24268. const vertex = new Vector3();
  24269. // iterate over the entire buffer and apply the radius to each vertex
  24270. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  24271. vertex.x = vertexBuffer[ i + 0 ];
  24272. vertex.y = vertexBuffer[ i + 1 ];
  24273. vertex.z = vertexBuffer[ i + 2 ];
  24274. vertex.normalize().multiplyScalar( radius );
  24275. vertexBuffer[ i + 0 ] = vertex.x;
  24276. vertexBuffer[ i + 1 ] = vertex.y;
  24277. vertexBuffer[ i + 2 ] = vertex.z;
  24278. }
  24279. }
  24280. function generateUVs() {
  24281. const vertex = new Vector3();
  24282. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  24283. vertex.x = vertexBuffer[ i + 0 ];
  24284. vertex.y = vertexBuffer[ i + 1 ];
  24285. vertex.z = vertexBuffer[ i + 2 ];
  24286. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  24287. const v = inclination( vertex ) / Math.PI + 0.5;
  24288. uvBuffer.push( u, 1 - v );
  24289. }
  24290. correctUVs();
  24291. correctSeam();
  24292. }
  24293. function correctSeam() {
  24294. // handle case when face straddles the seam, see #3269
  24295. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  24296. // uv data of a single face
  24297. const x0 = uvBuffer[ i + 0 ];
  24298. const x1 = uvBuffer[ i + 2 ];
  24299. const x2 = uvBuffer[ i + 4 ];
  24300. const max = Math.max( x0, x1, x2 );
  24301. const min = Math.min( x0, x1, x2 );
  24302. // 0.9 is somewhat arbitrary
  24303. if ( max > 0.9 && min < 0.1 ) {
  24304. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  24305. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  24306. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  24307. }
  24308. }
  24309. }
  24310. function pushVertex( vertex ) {
  24311. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  24312. }
  24313. function getVertexByIndex( index, vertex ) {
  24314. const stride = index * 3;
  24315. vertex.x = vertices[ stride + 0 ];
  24316. vertex.y = vertices[ stride + 1 ];
  24317. vertex.z = vertices[ stride + 2 ];
  24318. }
  24319. function correctUVs() {
  24320. const a = new Vector3();
  24321. const b = new Vector3();
  24322. const c = new Vector3();
  24323. const centroid = new Vector3();
  24324. const uvA = new Vector2();
  24325. const uvB = new Vector2();
  24326. const uvC = new Vector2();
  24327. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  24328. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  24329. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  24330. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  24331. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  24332. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  24333. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  24334. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  24335. const azi = azimuth( centroid );
  24336. correctUV( uvA, j + 0, a, azi );
  24337. correctUV( uvB, j + 2, b, azi );
  24338. correctUV( uvC, j + 4, c, azi );
  24339. }
  24340. }
  24341. function correctUV( uv, stride, vector, azimuth ) {
  24342. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  24343. uvBuffer[ stride ] = uv.x - 1;
  24344. }
  24345. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  24346. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  24347. }
  24348. }
  24349. // Angle around the Y axis, counter-clockwise when looking from above.
  24350. function azimuth( vector ) {
  24351. return Math.atan2( vector.z, - vector.x );
  24352. }
  24353. // Angle above the XZ plane.
  24354. function inclination( vector ) {
  24355. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  24356. }
  24357. }
  24358. copy( source ) {
  24359. super.copy( source );
  24360. this.parameters = Object.assign( {}, source.parameters );
  24361. return this;
  24362. }
  24363. /**
  24364. * Factory method for creating an instance of this class from the given
  24365. * JSON object.
  24366. *
  24367. * @param {Object} data - A JSON object representing the serialized geometry.
  24368. * @return {PolyhedronGeometry} A new instance.
  24369. */
  24370. static fromJSON( data ) {
  24371. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  24372. }
  24373. }
  24374. /**
  24375. * A geometry class for representing a dodecahedron.
  24376. *
  24377. * ```js
  24378. * const geometry = new THREE.DodecahedronGeometry();
  24379. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  24380. * const dodecahedron = new THREE.Mesh( geometry, material );
  24381. * scene.add( dodecahedron );
  24382. * ```
  24383. *
  24384. * @augments PolyhedronGeometry
  24385. */
  24386. class DodecahedronGeometry extends PolyhedronGeometry {
  24387. /**
  24388. * Constructs a new dodecahedron geometry.
  24389. *
  24390. * @param {number} [radius=1] - Radius of the dodecahedron.
  24391. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  24392. */
  24393. constructor( radius = 1, detail = 0 ) {
  24394. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  24395. const r = 1 / t;
  24396. const vertices = [
  24397. // (±1, ±1, ±1)
  24398. - 1, - 1, - 1, - 1, - 1, 1,
  24399. - 1, 1, - 1, - 1, 1, 1,
  24400. 1, - 1, - 1, 1, - 1, 1,
  24401. 1, 1, - 1, 1, 1, 1,
  24402. // (0, ±1/φ, ±φ)
  24403. 0, - r, - t, 0, - r, t,
  24404. 0, r, - t, 0, r, t,
  24405. // (±1/φ, ±φ, 0)
  24406. - r, - t, 0, - r, t, 0,
  24407. r, - t, 0, r, t, 0,
  24408. // (±φ, 0, ±1/φ)
  24409. - t, 0, - r, t, 0, - r,
  24410. - t, 0, r, t, 0, r
  24411. ];
  24412. const indices = [
  24413. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  24414. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  24415. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  24416. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  24417. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  24418. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  24419. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  24420. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  24421. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  24422. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  24423. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  24424. 1, 12, 14, 1, 14, 5, 1, 5, 9
  24425. ];
  24426. super( vertices, indices, radius, detail );
  24427. this.type = 'DodecahedronGeometry';
  24428. /**
  24429. * Holds the constructor parameters that have been
  24430. * used to generate the geometry. Any modification
  24431. * after instantiation does not change the geometry.
  24432. *
  24433. * @type {Object}
  24434. */
  24435. this.parameters = {
  24436. radius: radius,
  24437. detail: detail
  24438. };
  24439. }
  24440. /**
  24441. * Factory method for creating an instance of this class from the given
  24442. * JSON object.
  24443. *
  24444. * @param {Object} data - A JSON object representing the serialized geometry.
  24445. * @return {DodecahedronGeometry} A new instance.
  24446. */
  24447. static fromJSON( data ) {
  24448. return new DodecahedronGeometry( data.radius, data.detail );
  24449. }
  24450. }
  24451. const _v0$1 = /*@__PURE__*/ new Vector3();
  24452. const _v1$1 = /*@__PURE__*/ new Vector3();
  24453. const _normal = /*@__PURE__*/ new Vector3();
  24454. const _triangle = /*@__PURE__*/ new Triangle();
  24455. /**
  24456. * Can be used as a helper object to view the edges of a geometry.
  24457. *
  24458. * ```js
  24459. * const geometry = new THREE.BoxGeometry();
  24460. * const edges = new THREE.EdgesGeometry( geometry );
  24461. * const line = new THREE.LineSegments( edges );
  24462. * scene.add( line );
  24463. * ```
  24464. *
  24465. * Note: It is not yet possible to serialize/deserialize instances of this class.
  24466. *
  24467. * @augments BufferGeometry
  24468. */
  24469. class EdgesGeometry extends BufferGeometry {
  24470. /**
  24471. * Constructs a new edges geometry.
  24472. *
  24473. * @param {?BufferGeometry} [geometry=null] - The geometry.
  24474. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  24475. * between the face normals of the adjoining faces exceeds this value.
  24476. */
  24477. constructor( geometry = null, thresholdAngle = 1 ) {
  24478. super();
  24479. this.type = 'EdgesGeometry';
  24480. /**
  24481. * Holds the constructor parameters that have been
  24482. * used to generate the geometry. Any modification
  24483. * after instantiation does not change the geometry.
  24484. *
  24485. * @type {Object}
  24486. */
  24487. this.parameters = {
  24488. geometry: geometry,
  24489. thresholdAngle: thresholdAngle
  24490. };
  24491. if ( geometry !== null ) {
  24492. const precisionPoints = 4;
  24493. const precision = Math.pow( 10, precisionPoints );
  24494. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  24495. const indexAttr = geometry.getIndex();
  24496. const positionAttr = geometry.getAttribute( 'position' );
  24497. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  24498. const indexArr = [ 0, 0, 0 ];
  24499. const vertKeys = [ 'a', 'b', 'c' ];
  24500. const hashes = new Array( 3 );
  24501. const edgeData = {};
  24502. const vertices = [];
  24503. for ( let i = 0; i < indexCount; i += 3 ) {
  24504. if ( indexAttr ) {
  24505. indexArr[ 0 ] = indexAttr.getX( i );
  24506. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  24507. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  24508. } else {
  24509. indexArr[ 0 ] = i;
  24510. indexArr[ 1 ] = i + 1;
  24511. indexArr[ 2 ] = i + 2;
  24512. }
  24513. const { a, b, c } = _triangle;
  24514. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  24515. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  24516. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  24517. _triangle.getNormal( _normal );
  24518. // create hashes for the edge from the vertices
  24519. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  24520. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  24521. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  24522. // skip degenerate triangles
  24523. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  24524. continue;
  24525. }
  24526. // iterate over every edge
  24527. for ( let j = 0; j < 3; j ++ ) {
  24528. // get the first and next vertex making up the edge
  24529. const jNext = ( j + 1 ) % 3;
  24530. const vecHash0 = hashes[ j ];
  24531. const vecHash1 = hashes[ jNext ];
  24532. const v0 = _triangle[ vertKeys[ j ] ];
  24533. const v1 = _triangle[ vertKeys[ jNext ] ];
  24534. const hash = `${ vecHash0 }_${ vecHash1 }`;
  24535. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  24536. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  24537. // if we found a sibling edge add it into the vertex array if
  24538. // it meets the angle threshold and delete the edge from the map.
  24539. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  24540. vertices.push( v0.x, v0.y, v0.z );
  24541. vertices.push( v1.x, v1.y, v1.z );
  24542. }
  24543. edgeData[ reverseHash ] = null;
  24544. } else if ( ! ( hash in edgeData ) ) {
  24545. // if we've already got an edge here then skip adding a new one
  24546. edgeData[ hash ] = {
  24547. index0: indexArr[ j ],
  24548. index1: indexArr[ jNext ],
  24549. normal: _normal.clone(),
  24550. };
  24551. }
  24552. }
  24553. }
  24554. // iterate over all remaining, unmatched edges and add them to the vertex array
  24555. for ( const key in edgeData ) {
  24556. if ( edgeData[ key ] ) {
  24557. const { index0, index1 } = edgeData[ key ];
  24558. _v0$1.fromBufferAttribute( positionAttr, index0 );
  24559. _v1$1.fromBufferAttribute( positionAttr, index1 );
  24560. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  24561. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  24562. }
  24563. }
  24564. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24565. }
  24566. }
  24567. copy( source ) {
  24568. super.copy( source );
  24569. this.parameters = Object.assign( {}, source.parameters );
  24570. return this;
  24571. }
  24572. }
  24573. /**
  24574. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24575. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24576. * points, or to get triangulated faces.
  24577. *
  24578. * ```js
  24579. * const heartShape = new THREE.Shape();
  24580. *
  24581. * heartShape.moveTo( 25, 25 );
  24582. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24583. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24584. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24585. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24586. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24587. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24588. *
  24589. * const extrudeSettings = {
  24590. * depth: 8,
  24591. * bevelEnabled: true,
  24592. * bevelSegments: 2,
  24593. * steps: 2,
  24594. * bevelSize: 1,
  24595. * bevelThickness: 1
  24596. * };
  24597. *
  24598. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24599. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24600. * ```
  24601. *
  24602. * @augments Path
  24603. */
  24604. class Shape extends Path {
  24605. /**
  24606. * Constructs a new shape.
  24607. *
  24608. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24609. */
  24610. constructor( points ) {
  24611. super( points );
  24612. /**
  24613. * The UUID of the shape.
  24614. *
  24615. * @type {string}
  24616. * @readonly
  24617. */
  24618. this.uuid = generateUUID();
  24619. this.type = 'Shape';
  24620. /**
  24621. * Defines the holes in the shape. Hole definitions must use the
  24622. * opposite winding order (CW/CCW) than the outer shape.
  24623. *
  24624. * @type {Array<Path>}
  24625. * @readonly
  24626. */
  24627. this.holes = [];
  24628. }
  24629. /**
  24630. * Returns an array representing each contour of the holes
  24631. * as a list of 2D points.
  24632. *
  24633. * @param {number} divisions - The fineness of the result.
  24634. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24635. */
  24636. getPointsHoles( divisions ) {
  24637. const holesPts = [];
  24638. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24639. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24640. }
  24641. return holesPts;
  24642. }
  24643. // get points of shape and holes (keypoints based on segments parameter)
  24644. /**
  24645. * Returns an object that holds contour data for the shape and its holes as
  24646. * arrays of 2D points.
  24647. *
  24648. * @param {number} divisions - The fineness of the result.
  24649. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24650. */
  24651. extractPoints( divisions ) {
  24652. return {
  24653. shape: this.getPoints( divisions ),
  24654. holes: this.getPointsHoles( divisions )
  24655. };
  24656. }
  24657. copy( source ) {
  24658. super.copy( source );
  24659. this.holes = [];
  24660. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24661. const hole = source.holes[ i ];
  24662. this.holes.push( hole.clone() );
  24663. }
  24664. return this;
  24665. }
  24666. toJSON() {
  24667. const data = super.toJSON();
  24668. data.uuid = this.uuid;
  24669. data.holes = [];
  24670. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24671. const hole = this.holes[ i ];
  24672. data.holes.push( hole.toJSON() );
  24673. }
  24674. return data;
  24675. }
  24676. fromJSON( json ) {
  24677. super.fromJSON( json );
  24678. this.uuid = json.uuid;
  24679. this.holes = [];
  24680. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24681. const hole = json.holes[ i ];
  24682. this.holes.push( new Path().fromJSON( hole ) );
  24683. }
  24684. return this;
  24685. }
  24686. }
  24687. /* eslint-disable */
  24688. // copy of mapbox/earcut version 3.0.1
  24689. // https://github.com/mapbox/earcut/tree/v3.0.1
  24690. function earcut(data, holeIndices, dim = 2) {
  24691. const hasHoles = holeIndices && holeIndices.length;
  24692. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24693. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24694. const triangles = [];
  24695. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24696. let minX, minY, invSize;
  24697. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24698. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24699. if (data.length > 80 * dim) {
  24700. minX = Infinity;
  24701. minY = Infinity;
  24702. let maxX = -Infinity;
  24703. let maxY = -Infinity;
  24704. for (let i = dim; i < outerLen; i += dim) {
  24705. const x = data[i];
  24706. const y = data[i + 1];
  24707. if (x < minX) minX = x;
  24708. if (y < minY) minY = y;
  24709. if (x > maxX) maxX = x;
  24710. if (y > maxY) maxY = y;
  24711. }
  24712. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24713. invSize = Math.max(maxX - minX, maxY - minY);
  24714. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24715. }
  24716. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24717. return triangles;
  24718. }
  24719. // create a circular doubly linked list from polygon points in the specified winding order
  24720. function linkedList(data, start, end, dim, clockwise) {
  24721. let last;
  24722. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24723. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24724. } else {
  24725. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24726. }
  24727. if (last && equals(last, last.next)) {
  24728. removeNode(last);
  24729. last = last.next;
  24730. }
  24731. return last;
  24732. }
  24733. // eliminate colinear or duplicate points
  24734. function filterPoints(start, end) {
  24735. if (!start) return start;
  24736. if (!end) end = start;
  24737. let p = start,
  24738. again;
  24739. do {
  24740. again = false;
  24741. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24742. removeNode(p);
  24743. p = end = p.prev;
  24744. if (p === p.next) break;
  24745. again = true;
  24746. } else {
  24747. p = p.next;
  24748. }
  24749. } while (again || p !== end);
  24750. return end;
  24751. }
  24752. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24753. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24754. if (!ear) return;
  24755. // interlink polygon nodes in z-order
  24756. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24757. let stop = ear;
  24758. // iterate through ears, slicing them one by one
  24759. while (ear.prev !== ear.next) {
  24760. const prev = ear.prev;
  24761. const next = ear.next;
  24762. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24763. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24764. removeNode(ear);
  24765. // skipping the next vertex leads to less sliver triangles
  24766. ear = next.next;
  24767. stop = next.next;
  24768. continue;
  24769. }
  24770. ear = next;
  24771. // if we looped through the whole remaining polygon and can't find any more ears
  24772. if (ear === stop) {
  24773. // try filtering points and slicing again
  24774. if (!pass) {
  24775. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24776. // if this didn't work, try curing all small self-intersections locally
  24777. } else if (pass === 1) {
  24778. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24779. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24780. // as a last resort, try splitting the remaining polygon into two
  24781. } else if (pass === 2) {
  24782. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24783. }
  24784. break;
  24785. }
  24786. }
  24787. }
  24788. // check whether a polygon node forms a valid ear with adjacent nodes
  24789. function isEar(ear) {
  24790. const a = ear.prev,
  24791. b = ear,
  24792. c = ear.next;
  24793. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24794. // now make sure we don't have other points inside the potential ear
  24795. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24796. // triangle bbox
  24797. const x0 = Math.min(ax, bx, cx),
  24798. y0 = Math.min(ay, by, cy),
  24799. x1 = Math.max(ax, bx, cx),
  24800. y1 = Math.max(ay, by, cy);
  24801. let p = c.next;
  24802. while (p !== a) {
  24803. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24804. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24805. area(p.prev, p, p.next) >= 0) return false;
  24806. p = p.next;
  24807. }
  24808. return true;
  24809. }
  24810. function isEarHashed(ear, minX, minY, invSize) {
  24811. const a = ear.prev,
  24812. b = ear,
  24813. c = ear.next;
  24814. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24815. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24816. // triangle bbox
  24817. const x0 = Math.min(ax, bx, cx),
  24818. y0 = Math.min(ay, by, cy),
  24819. x1 = Math.max(ax, bx, cx),
  24820. y1 = Math.max(ay, by, cy);
  24821. // z-order range for the current triangle bbox;
  24822. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24823. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24824. let p = ear.prevZ,
  24825. n = ear.nextZ;
  24826. // look for points inside the triangle in both directions
  24827. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24828. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24829. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24830. p = p.prevZ;
  24831. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24832. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24833. n = n.nextZ;
  24834. }
  24835. // look for remaining points in decreasing z-order
  24836. while (p && p.z >= minZ) {
  24837. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24838. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24839. p = p.prevZ;
  24840. }
  24841. // look for remaining points in increasing z-order
  24842. while (n && n.z <= maxZ) {
  24843. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24844. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24845. n = n.nextZ;
  24846. }
  24847. return true;
  24848. }
  24849. // go through all polygon nodes and cure small local self-intersections
  24850. function cureLocalIntersections(start, triangles) {
  24851. let p = start;
  24852. do {
  24853. const a = p.prev,
  24854. b = p.next.next;
  24855. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24856. triangles.push(a.i, p.i, b.i);
  24857. // remove two nodes involved
  24858. removeNode(p);
  24859. removeNode(p.next);
  24860. p = start = b;
  24861. }
  24862. p = p.next;
  24863. } while (p !== start);
  24864. return filterPoints(p);
  24865. }
  24866. // try splitting polygon into two and triangulate them independently
  24867. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  24868. // look for a valid diagonal that divides the polygon into two
  24869. let a = start;
  24870. do {
  24871. let b = a.next.next;
  24872. while (b !== a.prev) {
  24873. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24874. // split the polygon in two by the diagonal
  24875. let c = splitPolygon(a, b);
  24876. // filter colinear points around the cuts
  24877. a = filterPoints(a, a.next);
  24878. c = filterPoints(c, c.next);
  24879. // run earcut on each half
  24880. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  24881. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  24882. return;
  24883. }
  24884. b = b.next;
  24885. }
  24886. a = a.next;
  24887. } while (a !== start);
  24888. }
  24889. // link every hole into the outer loop, producing a single-ring polygon without holes
  24890. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24891. const queue = [];
  24892. for (let i = 0, len = holeIndices.length; i < len; i++) {
  24893. const start = holeIndices[i] * dim;
  24894. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24895. const list = linkedList(data, start, end, dim, false);
  24896. if (list === list.next) list.steiner = true;
  24897. queue.push(getLeftmost(list));
  24898. }
  24899. queue.sort(compareXYSlope);
  24900. // process holes from left to right
  24901. for (let i = 0; i < queue.length; i++) {
  24902. outerNode = eliminateHole(queue[i], outerNode);
  24903. }
  24904. return outerNode;
  24905. }
  24906. function compareXYSlope(a, b) {
  24907. let result = a.x - b.x;
  24908. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  24909. // the bridge to the outer shell is always the point that they meet at.
  24910. if (result === 0) {
  24911. result = a.y - b.y;
  24912. if (result === 0) {
  24913. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  24914. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  24915. result = aSlope - bSlope;
  24916. }
  24917. }
  24918. return result;
  24919. }
  24920. // find a bridge between vertices that connects hole with an outer ring and and link it
  24921. function eliminateHole(hole, outerNode) {
  24922. const bridge = findHoleBridge(hole, outerNode);
  24923. if (!bridge) {
  24924. return outerNode;
  24925. }
  24926. const bridgeReverse = splitPolygon(bridge, hole);
  24927. // filter collinear points around the cuts
  24928. filterPoints(bridgeReverse, bridgeReverse.next);
  24929. return filterPoints(bridge, bridge.next);
  24930. }
  24931. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24932. function findHoleBridge(hole, outerNode) {
  24933. let p = outerNode;
  24934. const hx = hole.x;
  24935. const hy = hole.y;
  24936. let qx = -Infinity;
  24937. let m;
  24938. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24939. // segment's endpoint with lesser x will be potential connection point
  24940. // unless they intersect at a vertex, then choose the vertex
  24941. if (equals(hole, p)) return p;
  24942. do {
  24943. if (equals(hole, p.next)) return p.next;
  24944. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  24945. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24946. if (x <= hx && x > qx) {
  24947. qx = x;
  24948. m = p.x < p.next.x ? p : p.next;
  24949. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  24950. }
  24951. }
  24952. p = p.next;
  24953. } while (p !== outerNode);
  24954. if (!m) return null;
  24955. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24956. // if there are no points found, we have a valid connection;
  24957. // otherwise choose the point of the minimum angle with the ray as connection point
  24958. const stop = m;
  24959. const mx = m.x;
  24960. const my = m.y;
  24961. let tanMin = Infinity;
  24962. p = m;
  24963. do {
  24964. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  24965. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24966. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24967. if (locallyInside(p, hole) &&
  24968. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  24969. m = p;
  24970. tanMin = tan;
  24971. }
  24972. }
  24973. p = p.next;
  24974. } while (p !== stop);
  24975. return m;
  24976. }
  24977. // whether sector in vertex m contains sector in vertex p in the same coordinates
  24978. function sectorContainsSector(m, p) {
  24979. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  24980. }
  24981. // interlink polygon nodes in z-order
  24982. function indexCurve(start, minX, minY, invSize) {
  24983. let p = start;
  24984. do {
  24985. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  24986. p.prevZ = p.prev;
  24987. p.nextZ = p.next;
  24988. p = p.next;
  24989. } while (p !== start);
  24990. p.prevZ.nextZ = null;
  24991. p.prevZ = null;
  24992. sortLinked(p);
  24993. }
  24994. // Simon Tatham's linked list merge sort algorithm
  24995. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24996. function sortLinked(list) {
  24997. let numMerges;
  24998. let inSize = 1;
  24999. do {
  25000. let p = list;
  25001. let e;
  25002. list = null;
  25003. let tail = null;
  25004. numMerges = 0;
  25005. while (p) {
  25006. numMerges++;
  25007. let q = p;
  25008. let pSize = 0;
  25009. for (let i = 0; i < inSize; i++) {
  25010. pSize++;
  25011. q = q.nextZ;
  25012. if (!q) break;
  25013. }
  25014. let qSize = inSize;
  25015. while (pSize > 0 || (qSize > 0 && q)) {
  25016. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25017. e = p;
  25018. p = p.nextZ;
  25019. pSize--;
  25020. } else {
  25021. e = q;
  25022. q = q.nextZ;
  25023. qSize--;
  25024. }
  25025. if (tail) tail.nextZ = e;
  25026. else list = e;
  25027. e.prevZ = tail;
  25028. tail = e;
  25029. }
  25030. p = q;
  25031. }
  25032. tail.nextZ = null;
  25033. inSize *= 2;
  25034. } while (numMerges > 1);
  25035. return list;
  25036. }
  25037. // z-order of a point given coords and inverse of the longer side of data bbox
  25038. function zOrder(x, y, minX, minY, invSize) {
  25039. // coords are transformed into non-negative 15-bit integer range
  25040. x = (x - minX) * invSize | 0;
  25041. y = (y - minY) * invSize | 0;
  25042. x = (x | (x << 8)) & 0x00FF00FF;
  25043. x = (x | (x << 4)) & 0x0F0F0F0F;
  25044. x = (x | (x << 2)) & 0x33333333;
  25045. x = (x | (x << 1)) & 0x55555555;
  25046. y = (y | (y << 8)) & 0x00FF00FF;
  25047. y = (y | (y << 4)) & 0x0F0F0F0F;
  25048. y = (y | (y << 2)) & 0x33333333;
  25049. y = (y | (y << 1)) & 0x55555555;
  25050. return x | (y << 1);
  25051. }
  25052. // find the leftmost node of a polygon ring
  25053. function getLeftmost(start) {
  25054. let p = start,
  25055. leftmost = start;
  25056. do {
  25057. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25058. p = p.next;
  25059. } while (p !== start);
  25060. return leftmost;
  25061. }
  25062. // check if a point lies within a convex triangle
  25063. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25064. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25065. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25066. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25067. }
  25068. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25069. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25070. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25071. }
  25072. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25073. function isValidDiagonal(a, b) {
  25074. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25075. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25076. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25077. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25078. }
  25079. // signed area of a triangle
  25080. function area(p, q, r) {
  25081. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25082. }
  25083. // check if two points are equal
  25084. function equals(p1, p2) {
  25085. return p1.x === p2.x && p1.y === p2.y;
  25086. }
  25087. // check if two segments intersect
  25088. function intersects(p1, q1, p2, q2) {
  25089. const o1 = sign(area(p1, q1, p2));
  25090. const o2 = sign(area(p1, q1, q2));
  25091. const o3 = sign(area(p2, q2, p1));
  25092. const o4 = sign(area(p2, q2, q1));
  25093. if (o1 !== o2 && o3 !== o4) return true; // general case
  25094. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25095. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25096. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25097. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25098. return false;
  25099. }
  25100. // for collinear points p, q, r, check if point q lies on segment pr
  25101. function onSegment(p, q, r) {
  25102. 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);
  25103. }
  25104. function sign(num) {
  25105. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25106. }
  25107. // check if a polygon diagonal intersects any polygon segments
  25108. function intersectsPolygon(a, b) {
  25109. let p = a;
  25110. do {
  25111. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25112. intersects(p, p.next, a, b)) return true;
  25113. p = p.next;
  25114. } while (p !== a);
  25115. return false;
  25116. }
  25117. // check if a polygon diagonal is locally inside the polygon
  25118. function locallyInside(a, b) {
  25119. return area(a.prev, a, a.next) < 0 ?
  25120. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25121. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25122. }
  25123. // check if the middle point of a polygon diagonal is inside the polygon
  25124. function middleInside(a, b) {
  25125. let p = a;
  25126. let inside = false;
  25127. const px = (a.x + b.x) / 2;
  25128. const py = (a.y + b.y) / 2;
  25129. do {
  25130. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25131. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25132. inside = !inside;
  25133. p = p.next;
  25134. } while (p !== a);
  25135. return inside;
  25136. }
  25137. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25138. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25139. function splitPolygon(a, b) {
  25140. const a2 = createNode(a.i, a.x, a.y),
  25141. b2 = createNode(b.i, b.x, b.y),
  25142. an = a.next,
  25143. bp = b.prev;
  25144. a.next = b;
  25145. b.prev = a;
  25146. a2.next = an;
  25147. an.prev = a2;
  25148. b2.next = a2;
  25149. a2.prev = b2;
  25150. bp.next = b2;
  25151. b2.prev = bp;
  25152. return b2;
  25153. }
  25154. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25155. function insertNode(i, x, y, last) {
  25156. const p = createNode(i, x, y);
  25157. if (!last) {
  25158. p.prev = p;
  25159. p.next = p;
  25160. } else {
  25161. p.next = last.next;
  25162. p.prev = last;
  25163. last.next.prev = p;
  25164. last.next = p;
  25165. }
  25166. return p;
  25167. }
  25168. function removeNode(p) {
  25169. p.next.prev = p.prev;
  25170. p.prev.next = p.next;
  25171. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25172. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25173. }
  25174. function createNode(i, x, y) {
  25175. return {
  25176. i, // vertex index in coordinates array
  25177. x, y, // vertex coordinates
  25178. prev: null, // previous and next vertex nodes in a polygon ring
  25179. next: null,
  25180. z: 0, // z-order curve value
  25181. prevZ: null, // previous and next nodes in z-order
  25182. nextZ: null,
  25183. steiner: false // indicates whether this is a steiner point
  25184. };
  25185. }
  25186. function signedArea(data, start, end, dim) {
  25187. let sum = 0;
  25188. for (let i = start, j = end - dim; i < end; i += dim) {
  25189. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25190. j = i;
  25191. }
  25192. return sum;
  25193. }
  25194. class Earcut {
  25195. /**
  25196. * Triangulates the given shape definition by returning an array of triangles.
  25197. *
  25198. * @param {Array<number>} data - An array with 2D points.
  25199. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25200. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25201. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25202. * representing vertex indices.
  25203. */
  25204. static triangulate( data, holeIndices, dim = 2 ) {
  25205. return earcut( data, holeIndices, dim );
  25206. }
  25207. }
  25208. /**
  25209. * A class containing utility functions for shapes.
  25210. *
  25211. * @hideconstructor
  25212. */
  25213. class ShapeUtils {
  25214. /**
  25215. * Calculate area of a ( 2D ) contour polygon.
  25216. *
  25217. * @param {Array<Vector2>} contour - An array of 2D points.
  25218. * @return {number} The area.
  25219. */
  25220. static area( contour ) {
  25221. const n = contour.length;
  25222. let a = 0.0;
  25223. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25224. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25225. }
  25226. return a * 0.5;
  25227. }
  25228. /**
  25229. * Returns `true` if the given contour uses a clockwise winding order.
  25230. *
  25231. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25232. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25233. */
  25234. static isClockWise( pts ) {
  25235. return ShapeUtils.area( pts ) < 0;
  25236. }
  25237. /**
  25238. * Triangulates the given shape definition.
  25239. *
  25240. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25241. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25242. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25243. */
  25244. static triangulateShape( contour, holes ) {
  25245. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25246. const holeIndices = []; // array of hole indices
  25247. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25248. removeDupEndPts( contour );
  25249. addContour( vertices, contour );
  25250. //
  25251. let holeIndex = contour.length;
  25252. holes.forEach( removeDupEndPts );
  25253. for ( let i = 0; i < holes.length; i ++ ) {
  25254. holeIndices.push( holeIndex );
  25255. holeIndex += holes[ i ].length;
  25256. addContour( vertices, holes[ i ] );
  25257. }
  25258. //
  25259. const triangles = Earcut.triangulate( vertices, holeIndices );
  25260. //
  25261. for ( let i = 0; i < triangles.length; i += 3 ) {
  25262. faces.push( triangles.slice( i, i + 3 ) );
  25263. }
  25264. return faces;
  25265. }
  25266. }
  25267. function removeDupEndPts( points ) {
  25268. const l = points.length;
  25269. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25270. points.pop();
  25271. }
  25272. }
  25273. function addContour( vertices, contour ) {
  25274. for ( let i = 0; i < contour.length; i ++ ) {
  25275. vertices.push( contour[ i ].x );
  25276. vertices.push( contour[ i ].y );
  25277. }
  25278. }
  25279. /**
  25280. * Creates extruded geometry from a path shape.
  25281. *
  25282. * ```js
  25283. * const length = 12, width = 8;
  25284. *
  25285. * const shape = new THREE.Shape();
  25286. * shape.moveTo( 0,0 );
  25287. * shape.lineTo( 0, width );
  25288. * shape.lineTo( length, width );
  25289. * shape.lineTo( length, 0 );
  25290. * shape.lineTo( 0, 0 );
  25291. *
  25292. * const geometry = new THREE.ExtrudeGeometry( shape );
  25293. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25294. * const mesh = new THREE.Mesh( geometry, material ) ;
  25295. * scene.add( mesh );
  25296. * ```
  25297. *
  25298. * @augments BufferGeometry
  25299. */
  25300. class ExtrudeGeometry extends BufferGeometry {
  25301. /**
  25302. * Constructs a new extrude geometry.
  25303. *
  25304. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25305. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25306. */
  25307. 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 = {} ) {
  25308. super();
  25309. this.type = 'ExtrudeGeometry';
  25310. /**
  25311. * Holds the constructor parameters that have been
  25312. * used to generate the geometry. Any modification
  25313. * after instantiation does not change the geometry.
  25314. *
  25315. * @type {Object}
  25316. */
  25317. this.parameters = {
  25318. shapes: shapes,
  25319. options: options
  25320. };
  25321. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25322. const scope = this;
  25323. const verticesArray = [];
  25324. const uvArray = [];
  25325. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25326. const shape = shapes[ i ];
  25327. addShape( shape );
  25328. }
  25329. // build geometry
  25330. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25331. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25332. this.computeVertexNormals();
  25333. // functions
  25334. function addShape( shape ) {
  25335. const placeholder = [];
  25336. // options
  25337. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25338. const steps = options.steps !== undefined ? options.steps : 1;
  25339. const depth = options.depth !== undefined ? options.depth : 1;
  25340. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25341. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25342. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25343. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25344. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25345. const extrudePath = options.extrudePath;
  25346. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25347. //
  25348. let extrudePts, extrudeByPath = false;
  25349. let splineTube, binormal, normal, position2;
  25350. if ( extrudePath ) {
  25351. extrudePts = extrudePath.getSpacedPoints( steps );
  25352. extrudeByPath = true;
  25353. bevelEnabled = false; // bevels not supported for path extrusion
  25354. // SETUP TNB variables
  25355. // TODO1 - have a .isClosed in spline?
  25356. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25357. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25358. binormal = new Vector3();
  25359. normal = new Vector3();
  25360. position2 = new Vector3();
  25361. }
  25362. // Safeguards if bevels are not enabled
  25363. if ( ! bevelEnabled ) {
  25364. bevelSegments = 0;
  25365. bevelThickness = 0;
  25366. bevelSize = 0;
  25367. bevelOffset = 0;
  25368. }
  25369. // Variables initialization
  25370. const shapePoints = shape.extractPoints( curveSegments );
  25371. let vertices = shapePoints.shape;
  25372. const holes = shapePoints.holes;
  25373. const reverse = ! ShapeUtils.isClockWise( vertices );
  25374. if ( reverse ) {
  25375. vertices = vertices.reverse();
  25376. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25377. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25378. const ahole = holes[ h ];
  25379. if ( ShapeUtils.isClockWise( ahole ) ) {
  25380. holes[ h ] = ahole.reverse();
  25381. }
  25382. }
  25383. }
  25384. const faces = ShapeUtils.triangulateShape( vertices, holes );
  25385. /* Vertices */
  25386. const contour = vertices; // vertices has all points but contour has only points of circumference
  25387. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25388. const ahole = holes[ h ];
  25389. vertices = vertices.concat( ahole );
  25390. }
  25391. function scalePt2( pt, vec, size ) {
  25392. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25393. return pt.clone().addScaledVector( vec, size );
  25394. }
  25395. const vlen = vertices.length, flen = faces.length;
  25396. // Find directions for point movement
  25397. function getBevelVec( inPt, inPrev, inNext ) {
  25398. // computes for inPt the corresponding point inPt' on a new contour
  25399. // shifted by 1 unit (length of normalized vector) to the left
  25400. // if we walk along contour clockwise, this new contour is outside the old one
  25401. //
  25402. // inPt' is the intersection of the two lines parallel to the two
  25403. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25404. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25405. // good reading for geometry algorithms (here: line-line intersection)
  25406. // http://geomalgorithms.com/a05-_intersect-1.html
  25407. const v_prev_x = inPt.x - inPrev.x,
  25408. v_prev_y = inPt.y - inPrev.y;
  25409. const v_next_x = inNext.x - inPt.x,
  25410. v_next_y = inNext.y - inPt.y;
  25411. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25412. // check for collinear edges
  25413. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25414. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25415. // not collinear
  25416. // length of vectors for normalizing
  25417. const v_prev_len = Math.sqrt( v_prev_lensq );
  25418. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25419. // shift adjacent points by unit vectors to the left
  25420. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25421. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25422. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25423. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25424. // scaling factor for v_prev to intersection point
  25425. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25426. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25427. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25428. // vector from inPt to intersection point
  25429. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25430. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25431. // Don't normalize!, otherwise sharp corners become ugly
  25432. // but prevent crazy spikes
  25433. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25434. if ( v_trans_lensq <= 2 ) {
  25435. return new Vector2( v_trans_x, v_trans_y );
  25436. } else {
  25437. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25438. }
  25439. } else {
  25440. // handle special case of collinear edges
  25441. let direction_eq = false; // assumes: opposite
  25442. if ( v_prev_x > Number.EPSILON ) {
  25443. if ( v_next_x > Number.EPSILON ) {
  25444. direction_eq = true;
  25445. }
  25446. } else {
  25447. if ( v_prev_x < - Number.EPSILON ) {
  25448. if ( v_next_x < - Number.EPSILON ) {
  25449. direction_eq = true;
  25450. }
  25451. } else {
  25452. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25453. direction_eq = true;
  25454. }
  25455. }
  25456. }
  25457. if ( direction_eq ) {
  25458. // console.log("Warning: lines are a straight sequence");
  25459. v_trans_x = - v_prev_y;
  25460. v_trans_y = v_prev_x;
  25461. shrink_by = Math.sqrt( v_prev_lensq );
  25462. } else {
  25463. // console.log("Warning: lines are a straight spike");
  25464. v_trans_x = v_prev_x;
  25465. v_trans_y = v_prev_y;
  25466. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25467. }
  25468. }
  25469. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25470. }
  25471. const contourMovements = [];
  25472. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25473. if ( j === il ) j = 0;
  25474. if ( k === il ) k = 0;
  25475. // (j)---(i)---(k)
  25476. // console.log('i,j,k', i, j , k)
  25477. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25478. }
  25479. const holesMovements = [];
  25480. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25481. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25482. const ahole = holes[ h ];
  25483. oneHoleMovements = [];
  25484. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25485. if ( j === il ) j = 0;
  25486. if ( k === il ) k = 0;
  25487. // (j)---(i)---(k)
  25488. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25489. }
  25490. holesMovements.push( oneHoleMovements );
  25491. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25492. }
  25493. // Loop bevelSegments, 1 for the front, 1 for the back
  25494. for ( let b = 0; b < bevelSegments; b ++ ) {
  25495. //for ( b = bevelSegments; b > 0; b -- ) {
  25496. const t = b / bevelSegments;
  25497. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25498. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25499. // contract shape
  25500. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25501. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25502. v( vert.x, vert.y, - z );
  25503. }
  25504. // expand holes
  25505. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25506. const ahole = holes[ h ];
  25507. oneHoleMovements = holesMovements[ h ];
  25508. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25509. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25510. v( vert.x, vert.y, - z );
  25511. }
  25512. }
  25513. }
  25514. const bs = bevelSize + bevelOffset;
  25515. // Back facing vertices
  25516. for ( let i = 0; i < vlen; i ++ ) {
  25517. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25518. if ( ! extrudeByPath ) {
  25519. v( vert.x, vert.y, 0 );
  25520. } else {
  25521. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25522. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25523. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25524. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25525. v( position2.x, position2.y, position2.z );
  25526. }
  25527. }
  25528. // Add stepped vertices...
  25529. // Including front facing vertices
  25530. for ( let s = 1; s <= steps; s ++ ) {
  25531. for ( let i = 0; i < vlen; i ++ ) {
  25532. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25533. if ( ! extrudeByPath ) {
  25534. v( vert.x, vert.y, depth / steps * s );
  25535. } else {
  25536. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25537. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25538. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25539. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25540. v( position2.x, position2.y, position2.z );
  25541. }
  25542. }
  25543. }
  25544. // Add bevel segments planes
  25545. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25546. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25547. const t = b / bevelSegments;
  25548. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25549. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25550. // contract shape
  25551. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25552. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25553. v( vert.x, vert.y, depth + z );
  25554. }
  25555. // expand holes
  25556. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25557. const ahole = holes[ h ];
  25558. oneHoleMovements = holesMovements[ h ];
  25559. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25560. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25561. if ( ! extrudeByPath ) {
  25562. v( vert.x, vert.y, depth + z );
  25563. } else {
  25564. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25565. }
  25566. }
  25567. }
  25568. }
  25569. /* Faces */
  25570. // Top and bottom faces
  25571. buildLidFaces();
  25572. // Sides faces
  25573. buildSideFaces();
  25574. ///// Internal functions
  25575. function buildLidFaces() {
  25576. const start = verticesArray.length / 3;
  25577. if ( bevelEnabled ) {
  25578. let layer = 0; // steps + 1
  25579. let offset = vlen * layer;
  25580. // Bottom faces
  25581. for ( let i = 0; i < flen; i ++ ) {
  25582. const face = faces[ i ];
  25583. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25584. }
  25585. layer = steps + bevelSegments * 2;
  25586. offset = vlen * layer;
  25587. // Top faces
  25588. for ( let i = 0; i < flen; i ++ ) {
  25589. const face = faces[ i ];
  25590. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25591. }
  25592. } else {
  25593. // Bottom faces
  25594. for ( let i = 0; i < flen; i ++ ) {
  25595. const face = faces[ i ];
  25596. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25597. }
  25598. // Top faces
  25599. for ( let i = 0; i < flen; i ++ ) {
  25600. const face = faces[ i ];
  25601. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25602. }
  25603. }
  25604. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25605. }
  25606. // Create faces for the z-sides of the shape
  25607. function buildSideFaces() {
  25608. const start = verticesArray.length / 3;
  25609. let layeroffset = 0;
  25610. sidewalls( contour, layeroffset );
  25611. layeroffset += contour.length;
  25612. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25613. const ahole = holes[ h ];
  25614. sidewalls( ahole, layeroffset );
  25615. //, true
  25616. layeroffset += ahole.length;
  25617. }
  25618. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25619. }
  25620. function sidewalls( contour, layeroffset ) {
  25621. let i = contour.length;
  25622. while ( -- i >= 0 ) {
  25623. const j = i;
  25624. let k = i - 1;
  25625. if ( k < 0 ) k = contour.length - 1;
  25626. //console.log('b', i,j, i-1, k,vertices.length);
  25627. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25628. const slen1 = vlen * s;
  25629. const slen2 = vlen * ( s + 1 );
  25630. const a = layeroffset + j + slen1,
  25631. b = layeroffset + k + slen1,
  25632. c = layeroffset + k + slen2,
  25633. d = layeroffset + j + slen2;
  25634. f4( a, b, c, d );
  25635. }
  25636. }
  25637. }
  25638. function v( x, y, z ) {
  25639. placeholder.push( x );
  25640. placeholder.push( y );
  25641. placeholder.push( z );
  25642. }
  25643. function f3( a, b, c ) {
  25644. addVertex( a );
  25645. addVertex( b );
  25646. addVertex( c );
  25647. const nextIndex = verticesArray.length / 3;
  25648. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25649. addUV( uvs[ 0 ] );
  25650. addUV( uvs[ 1 ] );
  25651. addUV( uvs[ 2 ] );
  25652. }
  25653. function f4( a, b, c, d ) {
  25654. addVertex( a );
  25655. addVertex( b );
  25656. addVertex( d );
  25657. addVertex( b );
  25658. addVertex( c );
  25659. addVertex( d );
  25660. const nextIndex = verticesArray.length / 3;
  25661. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25662. addUV( uvs[ 0 ] );
  25663. addUV( uvs[ 1 ] );
  25664. addUV( uvs[ 3 ] );
  25665. addUV( uvs[ 1 ] );
  25666. addUV( uvs[ 2 ] );
  25667. addUV( uvs[ 3 ] );
  25668. }
  25669. function addVertex( index ) {
  25670. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25671. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25672. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25673. }
  25674. function addUV( vector2 ) {
  25675. uvArray.push( vector2.x );
  25676. uvArray.push( vector2.y );
  25677. }
  25678. }
  25679. }
  25680. copy( source ) {
  25681. super.copy( source );
  25682. this.parameters = Object.assign( {}, source.parameters );
  25683. return this;
  25684. }
  25685. toJSON() {
  25686. const data = super.toJSON();
  25687. const shapes = this.parameters.shapes;
  25688. const options = this.parameters.options;
  25689. return toJSON$1( shapes, options, data );
  25690. }
  25691. /**
  25692. * Factory method for creating an instance of this class from the given
  25693. * JSON object.
  25694. *
  25695. * @param {Object} data - A JSON object representing the serialized geometry.
  25696. * @param {Array<Shape>} shapes - An array of shapes.
  25697. * @return {ExtrudeGeometry} A new instance.
  25698. */
  25699. static fromJSON( data, shapes ) {
  25700. const geometryShapes = [];
  25701. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25702. const shape = shapes[ data.shapes[ j ] ];
  25703. geometryShapes.push( shape );
  25704. }
  25705. const extrudePath = data.options.extrudePath;
  25706. if ( extrudePath !== undefined ) {
  25707. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25708. }
  25709. return new ExtrudeGeometry( geometryShapes, data.options );
  25710. }
  25711. }
  25712. const WorldUVGenerator = {
  25713. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25714. const a_x = vertices[ indexA * 3 ];
  25715. const a_y = vertices[ indexA * 3 + 1 ];
  25716. const b_x = vertices[ indexB * 3 ];
  25717. const b_y = vertices[ indexB * 3 + 1 ];
  25718. const c_x = vertices[ indexC * 3 ];
  25719. const c_y = vertices[ indexC * 3 + 1 ];
  25720. return [
  25721. new Vector2( a_x, a_y ),
  25722. new Vector2( b_x, b_y ),
  25723. new Vector2( c_x, c_y )
  25724. ];
  25725. },
  25726. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25727. const a_x = vertices[ indexA * 3 ];
  25728. const a_y = vertices[ indexA * 3 + 1 ];
  25729. const a_z = vertices[ indexA * 3 + 2 ];
  25730. const b_x = vertices[ indexB * 3 ];
  25731. const b_y = vertices[ indexB * 3 + 1 ];
  25732. const b_z = vertices[ indexB * 3 + 2 ];
  25733. const c_x = vertices[ indexC * 3 ];
  25734. const c_y = vertices[ indexC * 3 + 1 ];
  25735. const c_z = vertices[ indexC * 3 + 2 ];
  25736. const d_x = vertices[ indexD * 3 ];
  25737. const d_y = vertices[ indexD * 3 + 1 ];
  25738. const d_z = vertices[ indexD * 3 + 2 ];
  25739. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25740. return [
  25741. new Vector2( a_x, 1 - a_z ),
  25742. new Vector2( b_x, 1 - b_z ),
  25743. new Vector2( c_x, 1 - c_z ),
  25744. new Vector2( d_x, 1 - d_z )
  25745. ];
  25746. } else {
  25747. return [
  25748. new Vector2( a_y, 1 - a_z ),
  25749. new Vector2( b_y, 1 - b_z ),
  25750. new Vector2( c_y, 1 - c_z ),
  25751. new Vector2( d_y, 1 - d_z )
  25752. ];
  25753. }
  25754. }
  25755. };
  25756. function toJSON$1( shapes, options, data ) {
  25757. data.shapes = [];
  25758. if ( Array.isArray( shapes ) ) {
  25759. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25760. const shape = shapes[ i ];
  25761. data.shapes.push( shape.uuid );
  25762. }
  25763. } else {
  25764. data.shapes.push( shapes.uuid );
  25765. }
  25766. data.options = Object.assign( {}, options );
  25767. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25768. return data;
  25769. }
  25770. /**
  25771. * A geometry class for representing an icosahedron.
  25772. *
  25773. * ```js
  25774. * const geometry = new THREE.IcosahedronGeometry();
  25775. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25776. * const icosahedron = new THREE.Mesh( geometry, material );
  25777. * scene.add( icosahedron );
  25778. * ```
  25779. *
  25780. * @augments PolyhedronGeometry
  25781. */
  25782. class IcosahedronGeometry extends PolyhedronGeometry {
  25783. /**
  25784. * Constructs a new icosahedron geometry.
  25785. *
  25786. * @param {number} [radius=1] - Radius of the icosahedron.
  25787. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25788. */
  25789. constructor( radius = 1, detail = 0 ) {
  25790. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25791. const vertices = [
  25792. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  25793. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  25794. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  25795. ];
  25796. const indices = [
  25797. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25798. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25799. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25800. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25801. ];
  25802. super( vertices, indices, radius, detail );
  25803. this.type = 'IcosahedronGeometry';
  25804. /**
  25805. * Holds the constructor parameters that have been
  25806. * used to generate the geometry. Any modification
  25807. * after instantiation does not change the geometry.
  25808. *
  25809. * @type {Object}
  25810. */
  25811. this.parameters = {
  25812. radius: radius,
  25813. detail: detail
  25814. };
  25815. }
  25816. /**
  25817. * Factory method for creating an instance of this class from the given
  25818. * JSON object.
  25819. *
  25820. * @param {Object} data - A JSON object representing the serialized geometry.
  25821. * @return {IcosahedronGeometry} A new instance.
  25822. */
  25823. static fromJSON( data ) {
  25824. return new IcosahedronGeometry( data.radius, data.detail );
  25825. }
  25826. }
  25827. /**
  25828. * A geometry class for representing an octahedron.
  25829. *
  25830. * ```js
  25831. * const geometry = new THREE.OctahedronGeometry();
  25832. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25833. * const octahedron = new THREE.Mesh( geometry, material );
  25834. * scene.add( octahedron );
  25835. * ```
  25836. *
  25837. * @augments PolyhedronGeometry
  25838. */
  25839. class OctahedronGeometry extends PolyhedronGeometry {
  25840. /**
  25841. * Constructs a new octahedron geometry.
  25842. *
  25843. * @param {number} [radius=1] - Radius of the octahedron.
  25844. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  25845. */
  25846. constructor( radius = 1, detail = 0 ) {
  25847. const vertices = [
  25848. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  25849. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  25850. ];
  25851. const indices = [
  25852. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  25853. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  25854. 1, 3, 4, 1, 4, 2
  25855. ];
  25856. super( vertices, indices, radius, detail );
  25857. this.type = 'OctahedronGeometry';
  25858. /**
  25859. * Holds the constructor parameters that have been
  25860. * used to generate the geometry. Any modification
  25861. * after instantiation does not change the geometry.
  25862. *
  25863. * @type {Object}
  25864. */
  25865. this.parameters = {
  25866. radius: radius,
  25867. detail: detail
  25868. };
  25869. }
  25870. /**
  25871. * Factory method for creating an instance of this class from the given
  25872. * JSON object.
  25873. *
  25874. * @param {Object} data - A JSON object representing the serialized geometry.
  25875. * @return {OctahedronGeometry} A new instance.
  25876. */
  25877. static fromJSON( data ) {
  25878. return new OctahedronGeometry( data.radius, data.detail );
  25879. }
  25880. }
  25881. /**
  25882. * A geometry class for representing a plane.
  25883. *
  25884. * ```js
  25885. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  25886. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25887. * const plane = new THREE.Mesh( geometry, material );
  25888. * scene.add( plane );
  25889. * ```
  25890. *
  25891. * @augments BufferGeometry
  25892. */
  25893. class PlaneGeometry extends BufferGeometry {
  25894. /**
  25895. * Constructs a new plane geometry.
  25896. *
  25897. * @param {number} [width=1] - The width along the X axis.
  25898. * @param {number} [height=1] - The height along the Y axis
  25899. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  25900. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  25901. */
  25902. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  25903. super();
  25904. this.type = 'PlaneGeometry';
  25905. /**
  25906. * Holds the constructor parameters that have been
  25907. * used to generate the geometry. Any modification
  25908. * after instantiation does not change the geometry.
  25909. *
  25910. * @type {Object}
  25911. */
  25912. this.parameters = {
  25913. width: width,
  25914. height: height,
  25915. widthSegments: widthSegments,
  25916. heightSegments: heightSegments
  25917. };
  25918. const width_half = width / 2;
  25919. const height_half = height / 2;
  25920. const gridX = Math.floor( widthSegments );
  25921. const gridY = Math.floor( heightSegments );
  25922. const gridX1 = gridX + 1;
  25923. const gridY1 = gridY + 1;
  25924. const segment_width = width / gridX;
  25925. const segment_height = height / gridY;
  25926. //
  25927. const indices = [];
  25928. const vertices = [];
  25929. const normals = [];
  25930. const uvs = [];
  25931. for ( let iy = 0; iy < gridY1; iy ++ ) {
  25932. const y = iy * segment_height - height_half;
  25933. for ( let ix = 0; ix < gridX1; ix ++ ) {
  25934. const x = ix * segment_width - width_half;
  25935. vertices.push( x, - y, 0 );
  25936. normals.push( 0, 0, 1 );
  25937. uvs.push( ix / gridX );
  25938. uvs.push( 1 - ( iy / gridY ) );
  25939. }
  25940. }
  25941. for ( let iy = 0; iy < gridY; iy ++ ) {
  25942. for ( let ix = 0; ix < gridX; ix ++ ) {
  25943. const a = ix + gridX1 * iy;
  25944. const b = ix + gridX1 * ( iy + 1 );
  25945. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  25946. const d = ( ix + 1 ) + gridX1 * iy;
  25947. indices.push( a, b, d );
  25948. indices.push( b, c, d );
  25949. }
  25950. }
  25951. this.setIndex( indices );
  25952. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25953. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25954. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25955. }
  25956. copy( source ) {
  25957. super.copy( source );
  25958. this.parameters = Object.assign( {}, source.parameters );
  25959. return this;
  25960. }
  25961. /**
  25962. * Factory method for creating an instance of this class from the given
  25963. * JSON object.
  25964. *
  25965. * @param {Object} data - A JSON object representing the serialized geometry.
  25966. * @return {PlaneGeometry} A new instance.
  25967. */
  25968. static fromJSON( data ) {
  25969. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  25970. }
  25971. }
  25972. /**
  25973. * A class for generating a two-dimensional ring geometry.
  25974. *
  25975. * ```js
  25976. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  25977. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25978. * const mesh = new THREE.Mesh( geometry, material );
  25979. * scene.add( mesh );
  25980. * ```
  25981. *
  25982. * @augments BufferGeometry
  25983. */
  25984. class RingGeometry extends BufferGeometry {
  25985. /**
  25986. * Constructs a new ring geometry.
  25987. *
  25988. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  25989. * @param {number} [outerRadius=1] - The outer radius of the ring.
  25990. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  25991. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  25992. * @param {number} [thetaStart=0] - Starting angle in radians.
  25993. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  25994. */
  25995. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  25996. super();
  25997. this.type = 'RingGeometry';
  25998. /**
  25999. * Holds the constructor parameters that have been
  26000. * used to generate the geometry. Any modification
  26001. * after instantiation does not change the geometry.
  26002. *
  26003. * @type {Object}
  26004. */
  26005. this.parameters = {
  26006. innerRadius: innerRadius,
  26007. outerRadius: outerRadius,
  26008. thetaSegments: thetaSegments,
  26009. phiSegments: phiSegments,
  26010. thetaStart: thetaStart,
  26011. thetaLength: thetaLength
  26012. };
  26013. thetaSegments = Math.max( 3, thetaSegments );
  26014. phiSegments = Math.max( 1, phiSegments );
  26015. // buffers
  26016. const indices = [];
  26017. const vertices = [];
  26018. const normals = [];
  26019. const uvs = [];
  26020. // some helper variables
  26021. let radius = innerRadius;
  26022. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26023. const vertex = new Vector3();
  26024. const uv = new Vector2();
  26025. // generate vertices, normals and uvs
  26026. for ( let j = 0; j <= phiSegments; j ++ ) {
  26027. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26028. // values are generate from the inside of the ring to the outside
  26029. const segment = thetaStart + i / thetaSegments * thetaLength;
  26030. // vertex
  26031. vertex.x = radius * Math.cos( segment );
  26032. vertex.y = radius * Math.sin( segment );
  26033. vertices.push( vertex.x, vertex.y, vertex.z );
  26034. // normal
  26035. normals.push( 0, 0, 1 );
  26036. // uv
  26037. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26038. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26039. uvs.push( uv.x, uv.y );
  26040. }
  26041. // increase the radius for next row of vertices
  26042. radius += radiusStep;
  26043. }
  26044. // indices
  26045. for ( let j = 0; j < phiSegments; j ++ ) {
  26046. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26047. for ( let i = 0; i < thetaSegments; i ++ ) {
  26048. const segment = i + thetaSegmentLevel;
  26049. const a = segment;
  26050. const b = segment + thetaSegments + 1;
  26051. const c = segment + thetaSegments + 2;
  26052. const d = segment + 1;
  26053. // faces
  26054. indices.push( a, b, d );
  26055. indices.push( b, c, d );
  26056. }
  26057. }
  26058. // build geometry
  26059. this.setIndex( indices );
  26060. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26061. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26062. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26063. }
  26064. copy( source ) {
  26065. super.copy( source );
  26066. this.parameters = Object.assign( {}, source.parameters );
  26067. return this;
  26068. }
  26069. /**
  26070. * Factory method for creating an instance of this class from the given
  26071. * JSON object.
  26072. *
  26073. * @param {Object} data - A JSON object representing the serialized geometry.
  26074. * @return {RingGeometry} A new instance.
  26075. */
  26076. static fromJSON( data ) {
  26077. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26078. }
  26079. }
  26080. /**
  26081. * Creates an one-sided polygonal geometry from one or more path shapes.
  26082. *
  26083. * ```js
  26084. * const arcShape = new THREE.Shape()
  26085. * .moveTo( 5, 1 )
  26086. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26087. *
  26088. * const geometry = new THREE.ShapeGeometry( arcShape );
  26089. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26090. * const mesh = new THREE.Mesh( geometry, material ) ;
  26091. * scene.add( mesh );
  26092. * ```
  26093. *
  26094. * @augments BufferGeometry
  26095. */
  26096. class ShapeGeometry extends BufferGeometry {
  26097. /**
  26098. * Constructs a new shape geometry.
  26099. *
  26100. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26101. * @param {number} [curveSegments=12] - Number of segments per shape.
  26102. */
  26103. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  26104. super();
  26105. this.type = 'ShapeGeometry';
  26106. /**
  26107. * Holds the constructor parameters that have been
  26108. * used to generate the geometry. Any modification
  26109. * after instantiation does not change the geometry.
  26110. *
  26111. * @type {Object}
  26112. */
  26113. this.parameters = {
  26114. shapes: shapes,
  26115. curveSegments: curveSegments
  26116. };
  26117. // buffers
  26118. const indices = [];
  26119. const vertices = [];
  26120. const normals = [];
  26121. const uvs = [];
  26122. // helper variables
  26123. let groupStart = 0;
  26124. let groupCount = 0;
  26125. // allow single and array values for "shapes" parameter
  26126. if ( Array.isArray( shapes ) === false ) {
  26127. addShape( shapes );
  26128. } else {
  26129. for ( let i = 0; i < shapes.length; i ++ ) {
  26130. addShape( shapes[ i ] );
  26131. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26132. groupStart += groupCount;
  26133. groupCount = 0;
  26134. }
  26135. }
  26136. // build geometry
  26137. this.setIndex( indices );
  26138. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26139. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26140. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26141. // helper functions
  26142. function addShape( shape ) {
  26143. const indexOffset = vertices.length / 3;
  26144. const points = shape.extractPoints( curveSegments );
  26145. let shapeVertices = points.shape;
  26146. const shapeHoles = points.holes;
  26147. // check direction of vertices
  26148. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26149. shapeVertices = shapeVertices.reverse();
  26150. }
  26151. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26152. const shapeHole = shapeHoles[ i ];
  26153. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26154. shapeHoles[ i ] = shapeHole.reverse();
  26155. }
  26156. }
  26157. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26158. // join vertices of inner and outer paths to a single array
  26159. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26160. const shapeHole = shapeHoles[ i ];
  26161. shapeVertices = shapeVertices.concat( shapeHole );
  26162. }
  26163. // vertices, normals, uvs
  26164. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26165. const vertex = shapeVertices[ i ];
  26166. vertices.push( vertex.x, vertex.y, 0 );
  26167. normals.push( 0, 0, 1 );
  26168. uvs.push( vertex.x, vertex.y ); // world uvs
  26169. }
  26170. // indices
  26171. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26172. const face = faces[ i ];
  26173. const a = face[ 0 ] + indexOffset;
  26174. const b = face[ 1 ] + indexOffset;
  26175. const c = face[ 2 ] + indexOffset;
  26176. indices.push( a, b, c );
  26177. groupCount += 3;
  26178. }
  26179. }
  26180. }
  26181. copy( source ) {
  26182. super.copy( source );
  26183. this.parameters = Object.assign( {}, source.parameters );
  26184. return this;
  26185. }
  26186. toJSON() {
  26187. const data = super.toJSON();
  26188. const shapes = this.parameters.shapes;
  26189. return toJSON( shapes, data );
  26190. }
  26191. /**
  26192. * Factory method for creating an instance of this class from the given
  26193. * JSON object.
  26194. *
  26195. * @param {Object} data - A JSON object representing the serialized geometry.
  26196. * @param {Array<Shape>} shapes - An array of shapes.
  26197. * @return {ShapeGeometry} A new instance.
  26198. */
  26199. static fromJSON( data, shapes ) {
  26200. const geometryShapes = [];
  26201. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26202. const shape = shapes[ data.shapes[ j ] ];
  26203. geometryShapes.push( shape );
  26204. }
  26205. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26206. }
  26207. }
  26208. function toJSON( shapes, data ) {
  26209. data.shapes = [];
  26210. if ( Array.isArray( shapes ) ) {
  26211. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26212. const shape = shapes[ i ];
  26213. data.shapes.push( shape.uuid );
  26214. }
  26215. } else {
  26216. data.shapes.push( shapes.uuid );
  26217. }
  26218. return data;
  26219. }
  26220. /**
  26221. * A class for generating a sphere geometry.
  26222. *
  26223. * ```js
  26224. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26225. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26226. * const sphere = new THREE.Mesh( geometry, material );
  26227. * scene.add( sphere );
  26228. * ```
  26229. *
  26230. * @augments BufferGeometry
  26231. */
  26232. class SphereGeometry extends BufferGeometry {
  26233. /**
  26234. * Constructs a new sphere geometry.
  26235. *
  26236. * @param {number} [radius=1] - The sphere radius.
  26237. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26238. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26239. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26240. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26241. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26242. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26243. */
  26244. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26245. super();
  26246. this.type = 'SphereGeometry';
  26247. /**
  26248. * Holds the constructor parameters that have been
  26249. * used to generate the geometry. Any modification
  26250. * after instantiation does not change the geometry.
  26251. *
  26252. * @type {Object}
  26253. */
  26254. this.parameters = {
  26255. radius: radius,
  26256. widthSegments: widthSegments,
  26257. heightSegments: heightSegments,
  26258. phiStart: phiStart,
  26259. phiLength: phiLength,
  26260. thetaStart: thetaStart,
  26261. thetaLength: thetaLength
  26262. };
  26263. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26264. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26265. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26266. let index = 0;
  26267. const grid = [];
  26268. const vertex = new Vector3();
  26269. const normal = new Vector3();
  26270. // buffers
  26271. const indices = [];
  26272. const vertices = [];
  26273. const normals = [];
  26274. const uvs = [];
  26275. // generate vertices, normals and uvs
  26276. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26277. const verticesRow = [];
  26278. const v = iy / heightSegments;
  26279. // special case for the poles
  26280. let uOffset = 0;
  26281. if ( iy === 0 && thetaStart === 0 ) {
  26282. uOffset = 0.5 / widthSegments;
  26283. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26284. uOffset = - 0.5 / widthSegments;
  26285. }
  26286. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26287. const u = ix / widthSegments;
  26288. // vertex
  26289. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26290. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26291. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26292. vertices.push( vertex.x, vertex.y, vertex.z );
  26293. // normal
  26294. normal.copy( vertex ).normalize();
  26295. normals.push( normal.x, normal.y, normal.z );
  26296. // uv
  26297. uvs.push( u + uOffset, 1 - v );
  26298. verticesRow.push( index ++ );
  26299. }
  26300. grid.push( verticesRow );
  26301. }
  26302. // indices
  26303. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26304. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26305. const a = grid[ iy ][ ix + 1 ];
  26306. const b = grid[ iy ][ ix ];
  26307. const c = grid[ iy + 1 ][ ix ];
  26308. const d = grid[ iy + 1 ][ ix + 1 ];
  26309. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26310. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26311. }
  26312. }
  26313. // build geometry
  26314. this.setIndex( indices );
  26315. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26316. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26317. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26318. }
  26319. copy( source ) {
  26320. super.copy( source );
  26321. this.parameters = Object.assign( {}, source.parameters );
  26322. return this;
  26323. }
  26324. /**
  26325. * Factory method for creating an instance of this class from the given
  26326. * JSON object.
  26327. *
  26328. * @param {Object} data - A JSON object representing the serialized geometry.
  26329. * @return {SphereGeometry} A new instance.
  26330. */
  26331. static fromJSON( data ) {
  26332. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26333. }
  26334. }
  26335. /**
  26336. * A geometry class for representing an tetrahedron.
  26337. *
  26338. * ```js
  26339. * const geometry = new THREE.TetrahedronGeometry();
  26340. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26341. * const tetrahedron = new THREE.Mesh( geometry, material );
  26342. * scene.add( tetrahedron );
  26343. * ```
  26344. *
  26345. * @augments PolyhedronGeometry
  26346. */
  26347. class TetrahedronGeometry extends PolyhedronGeometry {
  26348. /**
  26349. * Constructs a new tetrahedron geometry.
  26350. *
  26351. * @param {number} [radius=1] - Radius of the tetrahedron.
  26352. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26353. */
  26354. constructor( radius = 1, detail = 0 ) {
  26355. const vertices = [
  26356. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  26357. ];
  26358. const indices = [
  26359. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26360. ];
  26361. super( vertices, indices, radius, detail );
  26362. this.type = 'TetrahedronGeometry';
  26363. /**
  26364. * Holds the constructor parameters that have been
  26365. * used to generate the geometry. Any modification
  26366. * after instantiation does not change the geometry.
  26367. *
  26368. * @type {Object}
  26369. */
  26370. this.parameters = {
  26371. radius: radius,
  26372. detail: detail
  26373. };
  26374. }
  26375. /**
  26376. * Factory method for creating an instance of this class from the given
  26377. * JSON object.
  26378. *
  26379. * @param {Object} data - A JSON object representing the serialized geometry.
  26380. * @return {TetrahedronGeometry} A new instance.
  26381. */
  26382. static fromJSON( data ) {
  26383. return new TetrahedronGeometry( data.radius, data.detail );
  26384. }
  26385. }
  26386. /**
  26387. * A geometry class for representing an torus.
  26388. *
  26389. * ```js
  26390. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26391. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26392. * const torus = new THREE.Mesh( geometry, material );
  26393. * scene.add( torus );
  26394. * ```
  26395. *
  26396. * @augments BufferGeometry
  26397. */
  26398. class TorusGeometry extends BufferGeometry {
  26399. /**
  26400. * Constructs a new torus geometry.
  26401. *
  26402. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26403. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26404. * @param {number} [radialSegments=12] - The number of radial segments.
  26405. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26406. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26407. */
  26408. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26409. super();
  26410. this.type = 'TorusGeometry';
  26411. /**
  26412. * Holds the constructor parameters that have been
  26413. * used to generate the geometry. Any modification
  26414. * after instantiation does not change the geometry.
  26415. *
  26416. * @type {Object}
  26417. */
  26418. this.parameters = {
  26419. radius: radius,
  26420. tube: tube,
  26421. radialSegments: radialSegments,
  26422. tubularSegments: tubularSegments,
  26423. arc: arc
  26424. };
  26425. radialSegments = Math.floor( radialSegments );
  26426. tubularSegments = Math.floor( tubularSegments );
  26427. // buffers
  26428. const indices = [];
  26429. const vertices = [];
  26430. const normals = [];
  26431. const uvs = [];
  26432. // helper variables
  26433. const center = new Vector3();
  26434. const vertex = new Vector3();
  26435. const normal = new Vector3();
  26436. // generate vertices, normals and uvs
  26437. for ( let j = 0; j <= radialSegments; j ++ ) {
  26438. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26439. const u = i / tubularSegments * arc;
  26440. const v = j / radialSegments * Math.PI * 2;
  26441. // vertex
  26442. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26443. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26444. vertex.z = tube * Math.sin( v );
  26445. vertices.push( vertex.x, vertex.y, vertex.z );
  26446. // normal
  26447. center.x = radius * Math.cos( u );
  26448. center.y = radius * Math.sin( u );
  26449. normal.subVectors( vertex, center ).normalize();
  26450. normals.push( normal.x, normal.y, normal.z );
  26451. // uv
  26452. uvs.push( i / tubularSegments );
  26453. uvs.push( j / radialSegments );
  26454. }
  26455. }
  26456. // generate indices
  26457. for ( let j = 1; j <= radialSegments; j ++ ) {
  26458. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26459. // indices
  26460. const a = ( tubularSegments + 1 ) * j + i - 1;
  26461. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26462. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26463. const d = ( tubularSegments + 1 ) * j + i;
  26464. // faces
  26465. indices.push( a, b, d );
  26466. indices.push( b, c, d );
  26467. }
  26468. }
  26469. // build geometry
  26470. this.setIndex( indices );
  26471. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26472. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26473. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26474. }
  26475. copy( source ) {
  26476. super.copy( source );
  26477. this.parameters = Object.assign( {}, source.parameters );
  26478. return this;
  26479. }
  26480. /**
  26481. * Factory method for creating an instance of this class from the given
  26482. * JSON object.
  26483. *
  26484. * @param {Object} data - A JSON object representing the serialized geometry.
  26485. * @return {TorusGeometry} A new instance.
  26486. */
  26487. static fromJSON( data ) {
  26488. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26489. }
  26490. }
  26491. /**
  26492. * Creates a torus knot, the particular shape of which is defined by a pair
  26493. * of coprime integers, p and q. If p and q are not coprime, the result will
  26494. * be a torus link.
  26495. *
  26496. * ```js
  26497. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26498. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26499. * const torusKnot = new THREE.Mesh( geometry, material );
  26500. * scene.add( torusKnot );
  26501. * ```
  26502. *
  26503. * @augments BufferGeometry
  26504. */
  26505. class TorusKnotGeometry extends BufferGeometry {
  26506. /**
  26507. * Constructs a new torus knot geometry.
  26508. *
  26509. * @param {number} [radius=1] - Radius of the torus knot.
  26510. * @param {number} [tube=0.4] - Radius of the tube.
  26511. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26512. * @param {number} [radialSegments=8] - The number of radial segments.
  26513. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26514. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26515. */
  26516. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26517. super();
  26518. this.type = 'TorusKnotGeometry';
  26519. /**
  26520. * Holds the constructor parameters that have been
  26521. * used to generate the geometry. Any modification
  26522. * after instantiation does not change the geometry.
  26523. *
  26524. * @type {Object}
  26525. */
  26526. this.parameters = {
  26527. radius: radius,
  26528. tube: tube,
  26529. tubularSegments: tubularSegments,
  26530. radialSegments: radialSegments,
  26531. p: p,
  26532. q: q
  26533. };
  26534. tubularSegments = Math.floor( tubularSegments );
  26535. radialSegments = Math.floor( radialSegments );
  26536. // buffers
  26537. const indices = [];
  26538. const vertices = [];
  26539. const normals = [];
  26540. const uvs = [];
  26541. // helper variables
  26542. const vertex = new Vector3();
  26543. const normal = new Vector3();
  26544. const P1 = new Vector3();
  26545. const P2 = new Vector3();
  26546. const B = new Vector3();
  26547. const T = new Vector3();
  26548. const N = new Vector3();
  26549. // generate vertices, normals and uvs
  26550. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26551. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26552. const u = i / tubularSegments * p * Math.PI * 2;
  26553. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26554. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26555. calculatePositionOnCurve( u, p, q, radius, P1 );
  26556. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26557. // calculate orthonormal basis
  26558. T.subVectors( P2, P1 );
  26559. N.addVectors( P2, P1 );
  26560. B.crossVectors( T, N );
  26561. N.crossVectors( B, T );
  26562. // normalize B, N. T can be ignored, we don't use it
  26563. B.normalize();
  26564. N.normalize();
  26565. for ( let j = 0; j <= radialSegments; ++ j ) {
  26566. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26567. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26568. const v = j / radialSegments * Math.PI * 2;
  26569. const cx = - tube * Math.cos( v );
  26570. const cy = tube * Math.sin( v );
  26571. // now calculate the final vertex position.
  26572. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26573. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26574. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26575. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26576. vertices.push( vertex.x, vertex.y, vertex.z );
  26577. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26578. normal.subVectors( vertex, P1 ).normalize();
  26579. normals.push( normal.x, normal.y, normal.z );
  26580. // uv
  26581. uvs.push( i / tubularSegments );
  26582. uvs.push( j / radialSegments );
  26583. }
  26584. }
  26585. // generate indices
  26586. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26587. for ( let i = 1; i <= radialSegments; i ++ ) {
  26588. // indices
  26589. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26590. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26591. const c = ( radialSegments + 1 ) * j + i;
  26592. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26593. // faces
  26594. indices.push( a, b, d );
  26595. indices.push( b, c, d );
  26596. }
  26597. }
  26598. // build geometry
  26599. this.setIndex( indices );
  26600. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26601. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26602. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26603. // this function calculates the current position on the torus curve
  26604. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26605. const cu = Math.cos( u );
  26606. const su = Math.sin( u );
  26607. const quOverP = q / p * u;
  26608. const cs = Math.cos( quOverP );
  26609. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26610. position.y = radius * ( 2 + cs ) * su * 0.5;
  26611. position.z = radius * Math.sin( quOverP ) * 0.5;
  26612. }
  26613. }
  26614. copy( source ) {
  26615. super.copy( source );
  26616. this.parameters = Object.assign( {}, source.parameters );
  26617. return this;
  26618. }
  26619. /**
  26620. * Factory method for creating an instance of this class from the given
  26621. * JSON object.
  26622. *
  26623. * @param {Object} data - A JSON object representing the serialized geometry.
  26624. * @return {TorusKnotGeometry} A new instance.
  26625. */
  26626. static fromJSON( data ) {
  26627. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26628. }
  26629. }
  26630. /**
  26631. * Creates a tube that extrudes along a 3D curve.
  26632. *
  26633. * ```js
  26634. * class CustomSinCurve extends THREE.Curve {
  26635. *
  26636. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26637. *
  26638. * const tx = t * 3 - 1.5;
  26639. * const ty = Math.sin( 2 * Math.PI * t );
  26640. * const tz = 0;
  26641. *
  26642. * return optionalTarget.set( tx, ty, tz );
  26643. * }
  26644. *
  26645. * }
  26646. *
  26647. * const path = new CustomSinCurve( 10 );
  26648. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  26649. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26650. * const mesh = new THREE.Mesh( geometry, material );
  26651. * scene.add( mesh );
  26652. * ```
  26653. *
  26654. * @augments BufferGeometry
  26655. */
  26656. class TubeGeometry extends BufferGeometry {
  26657. /**
  26658. * Constructs a new tube geometry.
  26659. *
  26660. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  26661. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  26662. * @param {number} [radius=1] -The radius of the tube.
  26663. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  26664. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  26665. */
  26666. 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 ) {
  26667. super();
  26668. this.type = 'TubeGeometry';
  26669. /**
  26670. * Holds the constructor parameters that have been
  26671. * used to generate the geometry. Any modification
  26672. * after instantiation does not change the geometry.
  26673. *
  26674. * @type {Object}
  26675. */
  26676. this.parameters = {
  26677. path: path,
  26678. tubularSegments: tubularSegments,
  26679. radius: radius,
  26680. radialSegments: radialSegments,
  26681. closed: closed
  26682. };
  26683. const frames = path.computeFrenetFrames( tubularSegments, closed );
  26684. // expose internals
  26685. this.tangents = frames.tangents;
  26686. this.normals = frames.normals;
  26687. this.binormals = frames.binormals;
  26688. // helper variables
  26689. const vertex = new Vector3();
  26690. const normal = new Vector3();
  26691. const uv = new Vector2();
  26692. let P = new Vector3();
  26693. // buffer
  26694. const vertices = [];
  26695. const normals = [];
  26696. const uvs = [];
  26697. const indices = [];
  26698. // create buffer data
  26699. generateBufferData();
  26700. // build geometry
  26701. this.setIndex( indices );
  26702. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26703. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26704. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26705. // functions
  26706. function generateBufferData() {
  26707. for ( let i = 0; i < tubularSegments; i ++ ) {
  26708. generateSegment( i );
  26709. }
  26710. // if the geometry is not closed, generate the last row of vertices and normals
  26711. // at the regular position on the given path
  26712. //
  26713. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26714. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  26715. // uvs are generated in a separate function.
  26716. // this makes it easy compute correct values for closed geometries
  26717. generateUVs();
  26718. // finally create faces
  26719. generateIndices();
  26720. }
  26721. function generateSegment( i ) {
  26722. // we use getPointAt to sample evenly distributed points from the given path
  26723. P = path.getPointAt( i / tubularSegments, P );
  26724. // retrieve corresponding normal and binormal
  26725. const N = frames.normals[ i ];
  26726. const B = frames.binormals[ i ];
  26727. // generate normals and vertices for the current segment
  26728. for ( let j = 0; j <= radialSegments; j ++ ) {
  26729. const v = j / radialSegments * Math.PI * 2;
  26730. const sin = Math.sin( v );
  26731. const cos = - Math.cos( v );
  26732. // normal
  26733. normal.x = ( cos * N.x + sin * B.x );
  26734. normal.y = ( cos * N.y + sin * B.y );
  26735. normal.z = ( cos * N.z + sin * B.z );
  26736. normal.normalize();
  26737. normals.push( normal.x, normal.y, normal.z );
  26738. // vertex
  26739. vertex.x = P.x + radius * normal.x;
  26740. vertex.y = P.y + radius * normal.y;
  26741. vertex.z = P.z + radius * normal.z;
  26742. vertices.push( vertex.x, vertex.y, vertex.z );
  26743. }
  26744. }
  26745. function generateIndices() {
  26746. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26747. for ( let i = 1; i <= radialSegments; i ++ ) {
  26748. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26749. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26750. const c = ( radialSegments + 1 ) * j + i;
  26751. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26752. // faces
  26753. indices.push( a, b, d );
  26754. indices.push( b, c, d );
  26755. }
  26756. }
  26757. }
  26758. function generateUVs() {
  26759. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26760. for ( let j = 0; j <= radialSegments; j ++ ) {
  26761. uv.x = i / tubularSegments;
  26762. uv.y = j / radialSegments;
  26763. uvs.push( uv.x, uv.y );
  26764. }
  26765. }
  26766. }
  26767. }
  26768. copy( source ) {
  26769. super.copy( source );
  26770. this.parameters = Object.assign( {}, source.parameters );
  26771. return this;
  26772. }
  26773. toJSON() {
  26774. const data = super.toJSON();
  26775. data.path = this.parameters.path.toJSON();
  26776. return data;
  26777. }
  26778. /**
  26779. * Factory method for creating an instance of this class from the given
  26780. * JSON object.
  26781. *
  26782. * @param {Object} data - A JSON object representing the serialized geometry.
  26783. * @return {TubeGeometry} A new instance.
  26784. */
  26785. static fromJSON( data ) {
  26786. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26787. // User defined curves or instances of CurvePath will not be deserialized.
  26788. return new TubeGeometry(
  26789. new Curves[ data.path.type ]().fromJSON( data.path ),
  26790. data.tubularSegments,
  26791. data.radius,
  26792. data.radialSegments,
  26793. data.closed
  26794. );
  26795. }
  26796. }
  26797. /**
  26798. * Can be used as a helper object to visualize a geometry as a wireframe.
  26799. *
  26800. * ```js
  26801. * const geometry = new THREE.SphereGeometry();
  26802. *
  26803. * const wireframe = new THREE.WireframeGeometry( geometry );
  26804. *
  26805. * const line = new THREE.LineSegments( wireframe );
  26806. * line.material.depthWrite = false;
  26807. * line.material.opacity = 0.25;
  26808. * line.material.transparent = true;
  26809. *
  26810. * scene.add( line );
  26811. * ```
  26812. *
  26813. * Note: It is not yet possible to serialize/deserialize instances of this class.
  26814. *
  26815. * @augments BufferGeometry
  26816. */
  26817. class WireframeGeometry extends BufferGeometry {
  26818. /**
  26819. * Constructs a new wireframe geometry.
  26820. *
  26821. * @param {?BufferGeometry} [geometry=null] - The geometry.
  26822. */
  26823. constructor( geometry = null ) {
  26824. super();
  26825. this.type = 'WireframeGeometry';
  26826. /**
  26827. * Holds the constructor parameters that have been
  26828. * used to generate the geometry. Any modification
  26829. * after instantiation does not change the geometry.
  26830. *
  26831. * @type {Object}
  26832. */
  26833. this.parameters = {
  26834. geometry: geometry
  26835. };
  26836. if ( geometry !== null ) {
  26837. // buffer
  26838. const vertices = [];
  26839. const edges = new Set();
  26840. // helper variables
  26841. const start = new Vector3();
  26842. const end = new Vector3();
  26843. if ( geometry.index !== null ) {
  26844. // indexed BufferGeometry
  26845. const position = geometry.attributes.position;
  26846. const indices = geometry.index;
  26847. let groups = geometry.groups;
  26848. if ( groups.length === 0 ) {
  26849. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  26850. }
  26851. // create a data structure that contains all edges without duplicates
  26852. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  26853. const group = groups[ o ];
  26854. const groupStart = group.start;
  26855. const groupCount = group.count;
  26856. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  26857. for ( let j = 0; j < 3; j ++ ) {
  26858. const index1 = indices.getX( i + j );
  26859. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  26860. start.fromBufferAttribute( position, index1 );
  26861. end.fromBufferAttribute( position, index2 );
  26862. if ( isUniqueEdge( start, end, edges ) === true ) {
  26863. vertices.push( start.x, start.y, start.z );
  26864. vertices.push( end.x, end.y, end.z );
  26865. }
  26866. }
  26867. }
  26868. }
  26869. } else {
  26870. // non-indexed BufferGeometry
  26871. const position = geometry.attributes.position;
  26872. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  26873. for ( let j = 0; j < 3; j ++ ) {
  26874. // three edges per triangle, an edge is represented as (index1, index2)
  26875. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26876. const index1 = 3 * i + j;
  26877. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  26878. start.fromBufferAttribute( position, index1 );
  26879. end.fromBufferAttribute( position, index2 );
  26880. if ( isUniqueEdge( start, end, edges ) === true ) {
  26881. vertices.push( start.x, start.y, start.z );
  26882. vertices.push( end.x, end.y, end.z );
  26883. }
  26884. }
  26885. }
  26886. }
  26887. // build geometry
  26888. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26889. }
  26890. }
  26891. copy( source ) {
  26892. super.copy( source );
  26893. this.parameters = Object.assign( {}, source.parameters );
  26894. return this;
  26895. }
  26896. }
  26897. function isUniqueEdge( start, end, edges ) {
  26898. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  26899. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  26900. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  26901. return false;
  26902. } else {
  26903. edges.add( hash1 );
  26904. edges.add( hash2 );
  26905. return true;
  26906. }
  26907. }
  26908. var Geometries = /*#__PURE__*/Object.freeze({
  26909. __proto__: null,
  26910. BoxGeometry: BoxGeometry,
  26911. CapsuleGeometry: CapsuleGeometry,
  26912. CircleGeometry: CircleGeometry,
  26913. ConeGeometry: ConeGeometry,
  26914. CylinderGeometry: CylinderGeometry,
  26915. DodecahedronGeometry: DodecahedronGeometry,
  26916. EdgesGeometry: EdgesGeometry,
  26917. ExtrudeGeometry: ExtrudeGeometry,
  26918. IcosahedronGeometry: IcosahedronGeometry,
  26919. LatheGeometry: LatheGeometry,
  26920. OctahedronGeometry: OctahedronGeometry,
  26921. PlaneGeometry: PlaneGeometry,
  26922. PolyhedronGeometry: PolyhedronGeometry,
  26923. RingGeometry: RingGeometry,
  26924. ShapeGeometry: ShapeGeometry,
  26925. SphereGeometry: SphereGeometry,
  26926. TetrahedronGeometry: TetrahedronGeometry,
  26927. TorusGeometry: TorusGeometry,
  26928. TorusKnotGeometry: TorusKnotGeometry,
  26929. TubeGeometry: TubeGeometry,
  26930. WireframeGeometry: WireframeGeometry
  26931. });
  26932. /**
  26933. * This material can receive shadows, but otherwise is completely transparent.
  26934. *
  26935. * ```js
  26936. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  26937. * geometry.rotateX( - Math.PI / 2 );
  26938. *
  26939. * const material = new THREE.ShadowMaterial();
  26940. * material.opacity = 0.2;
  26941. *
  26942. * const plane = new THREE.Mesh( geometry, material );
  26943. * plane.position.y = -200;
  26944. * plane.receiveShadow = true;
  26945. * scene.add( plane );
  26946. * ```
  26947. *
  26948. * @augments Material
  26949. */
  26950. class ShadowMaterial extends Material {
  26951. /**
  26952. * Constructs a new shadow material.
  26953. *
  26954. * @param {Object} [parameters] - An object with one or more properties
  26955. * defining the material's appearance. Any property of the material
  26956. * (including any property from inherited materials) can be passed
  26957. * in here. Color values can be passed any type of value accepted
  26958. * by {@link Color#set}.
  26959. */
  26960. constructor( parameters ) {
  26961. super();
  26962. /**
  26963. * This flag can be used for type testing.
  26964. *
  26965. * @type {boolean}
  26966. * @readonly
  26967. * @default true
  26968. */
  26969. this.isShadowMaterial = true;
  26970. this.type = 'ShadowMaterial';
  26971. /**
  26972. * Color of the material.
  26973. *
  26974. * @type {Color}
  26975. * @default (0,0,0)
  26976. */
  26977. this.color = new Color( 0x000000 );
  26978. /**
  26979. * Overwritten since shadow materials are transparent
  26980. * by default.
  26981. *
  26982. * @type {boolean}
  26983. * @default true
  26984. */
  26985. this.transparent = true;
  26986. /**
  26987. * Whether the material is affected by fog or not.
  26988. *
  26989. * @type {boolean}
  26990. * @default true
  26991. */
  26992. this.fog = true;
  26993. this.setValues( parameters );
  26994. }
  26995. copy( source ) {
  26996. super.copy( source );
  26997. this.color.copy( source.color );
  26998. this.fog = source.fog;
  26999. return this;
  27000. }
  27001. }
  27002. /**
  27003. * This class works just like {@link ShaderMaterial}, except that definitions
  27004. * of built-in uniforms and attributes are not automatically prepended to the
  27005. * GLSL shader code.
  27006. *
  27007. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27008. *
  27009. * @augments ShaderMaterial
  27010. */
  27011. class RawShaderMaterial extends ShaderMaterial {
  27012. /**
  27013. * Constructs a new raw shader material.
  27014. *
  27015. * @param {Object} [parameters] - An object with one or more properties
  27016. * defining the material's appearance. Any property of the material
  27017. * (including any property from inherited materials) can be passed
  27018. * in here. Color values can be passed any type of value accepted
  27019. * by {@link Color#set}.
  27020. */
  27021. constructor( parameters ) {
  27022. super( parameters );
  27023. /**
  27024. * This flag can be used for type testing.
  27025. *
  27026. * @type {boolean}
  27027. * @readonly
  27028. * @default true
  27029. */
  27030. this.isRawShaderMaterial = true;
  27031. this.type = 'RawShaderMaterial';
  27032. }
  27033. }
  27034. /**
  27035. * A standard physically based material, using Metallic-Roughness workflow.
  27036. *
  27037. * Physically based rendering (PBR) has recently become the standard in many
  27038. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27039. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27040. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27041. *
  27042. * This approach differs from older approaches in that instead of using
  27043. * approximations for the way in which light interacts with a surface, a
  27044. * physically correct model is used. The idea is that, instead of tweaking
  27045. * materials to look good under specific lighting, a material can be created
  27046. * that will react 'correctly' under all lighting scenarios.
  27047. *
  27048. * In practice this gives a more accurate and realistic looking result than
  27049. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27050. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27051. * shading.
  27052. *
  27053. * Note that for best results you should always specify an environment map when using this material.
  27054. *
  27055. * For a non-technical introduction to the concept of PBR and how to set up a
  27056. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27057. *
  27058. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27059. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27060. *
  27061. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27062. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27063. * (pdf), by Brent Burley.
  27064. *
  27065. * @augments Material
  27066. */
  27067. class MeshStandardMaterial extends Material {
  27068. /**
  27069. * Constructs a new mesh standard material.
  27070. *
  27071. * @param {Object} [parameters] - An object with one or more properties
  27072. * defining the material's appearance. Any property of the material
  27073. * (including any property from inherited materials) can be passed
  27074. * in here. Color values can be passed any type of value accepted
  27075. * by {@link Color#set}.
  27076. */
  27077. constructor( parameters ) {
  27078. super();
  27079. /**
  27080. * This flag can be used for type testing.
  27081. *
  27082. * @type {boolean}
  27083. * @readonly
  27084. * @default true
  27085. */
  27086. this.isMeshStandardMaterial = true;
  27087. this.type = 'MeshStandardMaterial';
  27088. this.defines = { 'STANDARD': '' };
  27089. /**
  27090. * Color of the material.
  27091. *
  27092. * @type {Color}
  27093. * @default (1,1,1)
  27094. */
  27095. this.color = new Color( 0xffffff ); // diffuse
  27096. /**
  27097. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27098. * means fully diffuse. If `roughnessMap` is also provided,
  27099. * both values are multiplied.
  27100. *
  27101. * @type {number}
  27102. * @default 1
  27103. */
  27104. this.roughness = 1.0;
  27105. /**
  27106. * How much the material is like a metal. Non-metallic materials such as wood
  27107. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27108. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27109. * If `metalnessMap` is also provided, both values are multiplied.
  27110. *
  27111. * @type {number}
  27112. * @default 0
  27113. */
  27114. this.metalness = 0.0;
  27115. /**
  27116. * The color map. May optionally include an alpha channel, typically combined
  27117. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27118. * color is modulated by the diffuse `color`.
  27119. *
  27120. * @type {?Texture}
  27121. * @default null
  27122. */
  27123. this.map = null;
  27124. /**
  27125. * The light map. Requires a second set of UVs.
  27126. *
  27127. * @type {?Texture}
  27128. * @default null
  27129. */
  27130. this.lightMap = null;
  27131. /**
  27132. * Intensity of the baked light.
  27133. *
  27134. * @type {number}
  27135. * @default 1
  27136. */
  27137. this.lightMapIntensity = 1.0;
  27138. /**
  27139. * The red channel of this texture is used as the ambient occlusion map.
  27140. * Requires a second set of UVs.
  27141. *
  27142. * @type {?Texture}
  27143. * @default null
  27144. */
  27145. this.aoMap = null;
  27146. /**
  27147. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27148. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27149. * red channel is also `1`, ambient light is fully occluded on a surface.
  27150. *
  27151. * @type {number}
  27152. * @default 1
  27153. */
  27154. this.aoMapIntensity = 1.0;
  27155. /**
  27156. * Emissive (light) color of the material, essentially a solid color
  27157. * unaffected by other lighting.
  27158. *
  27159. * @type {Color}
  27160. * @default (0,0,0)
  27161. */
  27162. this.emissive = new Color( 0x000000 );
  27163. /**
  27164. * Intensity of the emissive light. Modulates the emissive color.
  27165. *
  27166. * @type {number}
  27167. * @default 1
  27168. */
  27169. this.emissiveIntensity = 1.0;
  27170. /**
  27171. * Set emissive (glow) map. The emissive map color is modulated by the
  27172. * emissive color and the emissive intensity. If you have an emissive map,
  27173. * be sure to set the emissive color to something other than black.
  27174. *
  27175. * @type {?Texture}
  27176. * @default null
  27177. */
  27178. this.emissiveMap = null;
  27179. /**
  27180. * The texture to create a bump map. The black and white values map to the
  27181. * perceived depth in relation to the lights. Bump doesn't actually affect
  27182. * the geometry of the object, only the lighting. If a normal map is defined
  27183. * this will be ignored.
  27184. *
  27185. * @type {?Texture}
  27186. * @default null
  27187. */
  27188. this.bumpMap = null;
  27189. /**
  27190. * How much the bump map affects the material. Typical range is `[0,1]`.
  27191. *
  27192. * @type {number}
  27193. * @default 1
  27194. */
  27195. this.bumpScale = 1;
  27196. /**
  27197. * The texture to create a normal map. The RGB values affect the surface
  27198. * normal for each pixel fragment and change the way the color is lit. Normal
  27199. * maps do not change the actual shape of the surface, only the lighting. In
  27200. * case the material has a normal map authored using the left handed
  27201. * convention, the `y` component of `normalScale` should be negated to compensate
  27202. * for the different handedness.
  27203. *
  27204. * @type {?Texture}
  27205. * @default null
  27206. */
  27207. this.normalMap = null;
  27208. /**
  27209. * The type of normal map.
  27210. *
  27211. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27212. * @default TangentSpaceNormalMap
  27213. */
  27214. this.normalMapType = TangentSpaceNormalMap;
  27215. /**
  27216. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27217. *
  27218. * @type {Vector2}
  27219. * @default (1,1)
  27220. */
  27221. this.normalScale = new Vector2( 1, 1 );
  27222. /**
  27223. * The displacement map affects the position of the mesh's vertices. Unlike
  27224. * other maps which only affect the light and shade of the material the
  27225. * displaced vertices can cast shadows, block other objects, and otherwise
  27226. * act as real geometry. The displacement texture is an image where the value
  27227. * of each pixel (white being the highest) is mapped against, and
  27228. * repositions, the vertices of the mesh.
  27229. *
  27230. * @type {?Texture}
  27231. * @default null
  27232. */
  27233. this.displacementMap = null;
  27234. /**
  27235. * How much the displacement map affects the mesh (where black is no
  27236. * displacement, and white is maximum displacement). Without a displacement
  27237. * map set, this value is not applied.
  27238. *
  27239. * @type {number}
  27240. * @default 0
  27241. */
  27242. this.displacementScale = 1;
  27243. /**
  27244. * The offset of the displacement map's values on the mesh's vertices.
  27245. * The bias is added to the scaled sample of the displacement map.
  27246. * Without a displacement map set, this value is not applied.
  27247. *
  27248. * @type {number}
  27249. * @default 0
  27250. */
  27251. this.displacementBias = 0;
  27252. /**
  27253. * The green channel of this texture is used to alter the roughness of the
  27254. * material.
  27255. *
  27256. * @type {?Texture}
  27257. * @default null
  27258. */
  27259. this.roughnessMap = null;
  27260. /**
  27261. * The blue channel of this texture is used to alter the metalness of the
  27262. * material.
  27263. *
  27264. * @type {?Texture}
  27265. * @default null
  27266. */
  27267. this.metalnessMap = null;
  27268. /**
  27269. * The alpha map is a grayscale texture that controls the opacity across the
  27270. * surface (black: fully transparent; white: fully opaque).
  27271. *
  27272. * Only the color of the texture is used, ignoring the alpha channel if one
  27273. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27274. * when sampling this texture due to the extra bit of precision provided for
  27275. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27276. * luminance/alpha textures will also still work as expected.
  27277. *
  27278. * @type {?Texture}
  27279. * @default null
  27280. */
  27281. this.alphaMap = null;
  27282. /**
  27283. * The environment map. To ensure a physically correct rendering, environment maps
  27284. * are internally pre-processed with {@link PMREMGenerator}.
  27285. *
  27286. * @type {?Texture}
  27287. * @default null
  27288. */
  27289. this.envMap = null;
  27290. /**
  27291. * The rotation of the environment map in radians.
  27292. *
  27293. * @type {Euler}
  27294. * @default (0,0,0)
  27295. */
  27296. this.envMapRotation = new Euler();
  27297. /**
  27298. * Scales the effect of the environment map by multiplying its color.
  27299. *
  27300. * @type {number}
  27301. * @default 1
  27302. */
  27303. this.envMapIntensity = 1.0;
  27304. /**
  27305. * Renders the geometry as a wireframe.
  27306. *
  27307. * @type {boolean}
  27308. * @default false
  27309. */
  27310. this.wireframe = false;
  27311. /**
  27312. * Controls the thickness of the wireframe.
  27313. *
  27314. * Can only be used with {@link SVGRenderer}.
  27315. *
  27316. * @type {number}
  27317. * @default 1
  27318. */
  27319. this.wireframeLinewidth = 1;
  27320. /**
  27321. * Defines appearance of wireframe ends.
  27322. *
  27323. * Can only be used with {@link SVGRenderer}.
  27324. *
  27325. * @type {('round'|'bevel'|'miter')}
  27326. * @default 'round'
  27327. */
  27328. this.wireframeLinecap = 'round';
  27329. /**
  27330. * Defines appearance of wireframe joints.
  27331. *
  27332. * Can only be used with {@link SVGRenderer}.
  27333. *
  27334. * @type {('round'|'bevel'|'miter')}
  27335. * @default 'round'
  27336. */
  27337. this.wireframeLinejoin = 'round';
  27338. /**
  27339. * Whether the material is rendered with flat shading or not.
  27340. *
  27341. * @type {boolean}
  27342. * @default false
  27343. */
  27344. this.flatShading = false;
  27345. /**
  27346. * Whether the material is affected by fog or not.
  27347. *
  27348. * @type {boolean}
  27349. * @default true
  27350. */
  27351. this.fog = true;
  27352. this.setValues( parameters );
  27353. }
  27354. copy( source ) {
  27355. super.copy( source );
  27356. this.defines = { 'STANDARD': '' };
  27357. this.color.copy( source.color );
  27358. this.roughness = source.roughness;
  27359. this.metalness = source.metalness;
  27360. this.map = source.map;
  27361. this.lightMap = source.lightMap;
  27362. this.lightMapIntensity = source.lightMapIntensity;
  27363. this.aoMap = source.aoMap;
  27364. this.aoMapIntensity = source.aoMapIntensity;
  27365. this.emissive.copy( source.emissive );
  27366. this.emissiveMap = source.emissiveMap;
  27367. this.emissiveIntensity = source.emissiveIntensity;
  27368. this.bumpMap = source.bumpMap;
  27369. this.bumpScale = source.bumpScale;
  27370. this.normalMap = source.normalMap;
  27371. this.normalMapType = source.normalMapType;
  27372. this.normalScale.copy( source.normalScale );
  27373. this.displacementMap = source.displacementMap;
  27374. this.displacementScale = source.displacementScale;
  27375. this.displacementBias = source.displacementBias;
  27376. this.roughnessMap = source.roughnessMap;
  27377. this.metalnessMap = source.metalnessMap;
  27378. this.alphaMap = source.alphaMap;
  27379. this.envMap = source.envMap;
  27380. this.envMapRotation.copy( source.envMapRotation );
  27381. this.envMapIntensity = source.envMapIntensity;
  27382. this.wireframe = source.wireframe;
  27383. this.wireframeLinewidth = source.wireframeLinewidth;
  27384. this.wireframeLinecap = source.wireframeLinecap;
  27385. this.wireframeLinejoin = source.wireframeLinejoin;
  27386. this.flatShading = source.flatShading;
  27387. this.fog = source.fog;
  27388. return this;
  27389. }
  27390. }
  27391. /**
  27392. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27393. * physically-based rendering properties:
  27394. *
  27395. * - Anisotropy: Ability to represent the anisotropic property of materials
  27396. * as observable with brushed metals.
  27397. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27398. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27399. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27400. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27401. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27402. * wings of many insects.
  27403. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27404. * transparent materials are less reflective. Physically-based transmission provides a more
  27405. * realistic option for thin, transparent surfaces like glass.
  27406. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27407. * - Sheen: Can be used for representing cloth and fabric materials.
  27408. *
  27409. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27410. * higher performance cost, per pixel, than other three.js materials. Most
  27411. * effects are disabled by default, and add cost as they are enabled. For
  27412. * best results, always specify an environment map when using this material.
  27413. *
  27414. * @augments MeshStandardMaterial
  27415. */
  27416. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27417. /**
  27418. * Constructs a new mesh physical material.
  27419. *
  27420. * @param {Object} [parameters] - An object with one or more properties
  27421. * defining the material's appearance. Any property of the material
  27422. * (including any property from inherited materials) can be passed
  27423. * in here. Color values can be passed any type of value accepted
  27424. * by {@link Color#set}.
  27425. */
  27426. constructor( parameters ) {
  27427. super();
  27428. /**
  27429. * This flag can be used for type testing.
  27430. *
  27431. * @type {boolean}
  27432. * @readonly
  27433. * @default true
  27434. */
  27435. this.isMeshPhysicalMaterial = true;
  27436. this.defines = {
  27437. 'STANDARD': '',
  27438. 'PHYSICAL': ''
  27439. };
  27440. this.type = 'MeshPhysicalMaterial';
  27441. /**
  27442. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27443. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27444. * property provides additional rotation to the vectors in the texture.
  27445. *
  27446. * @type {number}
  27447. * @default 1
  27448. */
  27449. this.anisotropyRotation = 0;
  27450. /**
  27451. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27452. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27453. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27454. *
  27455. * @type {?Texture}
  27456. * @default null
  27457. */
  27458. this.anisotropyMap = null;
  27459. /**
  27460. * The red channel of this texture is multiplied against `clearcoat`,
  27461. * for per-pixel control over a coating's intensity.
  27462. *
  27463. * @type {?Texture}
  27464. * @default null
  27465. */
  27466. this.clearcoatMap = null;
  27467. /**
  27468. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27469. *
  27470. * @type {number}
  27471. * @default 0
  27472. */
  27473. this.clearcoatRoughness = 0.0;
  27474. /**
  27475. * The green channel of this texture is multiplied against
  27476. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27477. *
  27478. * @type {?Texture}
  27479. * @default null
  27480. */
  27481. this.clearcoatRoughnessMap = null;
  27482. /**
  27483. * How much `clearcoatNormalMap` affects the clear coat layer, from
  27484. * `(0,0)` to `(1,1)`.
  27485. *
  27486. * @type {Vector2}
  27487. * @default (1,1)
  27488. */
  27489. this.clearcoatNormalScale = new Vector2( 1, 1 );
  27490. /**
  27491. * Can be used to enable independent normals for the clear coat layer.
  27492. *
  27493. * @type {?Texture}
  27494. * @default null
  27495. */
  27496. this.clearcoatNormalMap = null;
  27497. /**
  27498. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  27499. *
  27500. * @type {number}
  27501. * @default 1.5
  27502. */
  27503. this.ior = 1.5;
  27504. /**
  27505. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  27506. * corresponds to an index-of-refraction of `1.5`.
  27507. *
  27508. * This models the reflectivity of non-metallic materials. It has no effect
  27509. * when `metalness` is `1.0`
  27510. *
  27511. * @name MeshPhysicalMaterial#reflectivity
  27512. * @type {number}
  27513. * @default 0.5
  27514. */
  27515. Object.defineProperty( this, 'reflectivity', {
  27516. get: function () {
  27517. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  27518. },
  27519. set: function ( reflectivity ) {
  27520. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  27521. }
  27522. } );
  27523. /**
  27524. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  27525. * control over iridescence.
  27526. *
  27527. * @type {?Texture}
  27528. * @default null
  27529. */
  27530. this.iridescenceMap = null;
  27531. /**
  27532. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  27533. * Between `1.0` to `2.333`.
  27534. *
  27535. * @type {number}
  27536. * @default 1.3
  27537. */
  27538. this.iridescenceIOR = 1.3;
  27539. /**
  27540. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  27541. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  27542. *
  27543. * @type {Array<number,number>}
  27544. * @default [100,400]
  27545. */
  27546. this.iridescenceThicknessRange = [ 100, 400 ];
  27547. /**
  27548. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  27549. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  27550. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  27551. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  27552. * - Values in-between will linearly interpolate between the elements of the array.
  27553. *
  27554. * @type {?Texture}
  27555. * @default null
  27556. */
  27557. this.iridescenceThicknessMap = null;
  27558. /**
  27559. * The sheen tint.
  27560. *
  27561. * @type {Color}
  27562. * @default (0,0,0)
  27563. */
  27564. this.sheenColor = new Color( 0x000000 );
  27565. /**
  27566. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  27567. * over sheen tint.
  27568. *
  27569. * @type {?Texture}
  27570. * @default null
  27571. */
  27572. this.sheenColorMap = null;
  27573. /**
  27574. * Roughness of the sheen layer, from `0.0` to `1.0`.
  27575. *
  27576. * @type {number}
  27577. * @default 1
  27578. */
  27579. this.sheenRoughness = 1.0;
  27580. /**
  27581. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  27582. * over sheen roughness.
  27583. *
  27584. * @type {?Texture}
  27585. * @default null
  27586. */
  27587. this.sheenRoughnessMap = null;
  27588. /**
  27589. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  27590. * optical transparency.
  27591. *
  27592. * @type {?Texture}
  27593. * @default null
  27594. */
  27595. this.transmissionMap = null;
  27596. /**
  27597. * The thickness of the volume beneath the surface. The value is given in the
  27598. * coordinate space of the mesh. If the value is `0` the material is
  27599. * thin-walled. Otherwise the material is a volume boundary.
  27600. *
  27601. * @type {number}
  27602. * @default 0
  27603. */
  27604. this.thickness = 0;
  27605. /**
  27606. * A texture that defines the thickness, stored in the green channel. This will
  27607. * be multiplied by `thickness`.
  27608. *
  27609. * @type {?Texture}
  27610. * @default null
  27611. */
  27612. this.thicknessMap = null;
  27613. /**
  27614. * Density of the medium given as the average distance that light travels in
  27615. * the medium before interacting with a particle. The value is given in world
  27616. * space units, and must be greater than zero.
  27617. *
  27618. * @type {number}
  27619. * @default Infinity
  27620. */
  27621. this.attenuationDistance = Infinity;
  27622. /**
  27623. * The color that white light turns into due to absorption when reaching the
  27624. * attenuation distance.
  27625. *
  27626. * @type {Color}
  27627. * @default (1,1,1)
  27628. */
  27629. this.attenuationColor = new Color( 1, 1, 1 );
  27630. /**
  27631. * A float that scales the amount of specular reflection for non-metals only.
  27632. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  27633. *
  27634. * @type {number}
  27635. * @default 1
  27636. */
  27637. this.specularIntensity = 1.0;
  27638. /**
  27639. * The alpha channel of this texture is multiplied against `specularIntensity`,
  27640. * for per-pixel control over specular intensity.
  27641. *
  27642. * @type {?Texture}
  27643. * @default null
  27644. */
  27645. this.specularIntensityMap = null;
  27646. /**
  27647. * Tints the specular reflection at normal incidence for non-metals only.
  27648. *
  27649. * @type {Color}
  27650. * @default (1,1,1)
  27651. */
  27652. this.specularColor = new Color( 1, 1, 1 );
  27653. /**
  27654. * The RGB channels of this texture are multiplied against `specularColor`,
  27655. * for per-pixel control over specular color.
  27656. *
  27657. * @type {?Texture}
  27658. * @default null
  27659. */
  27660. this.specularColorMap = null;
  27661. this._anisotropy = 0;
  27662. this._clearcoat = 0;
  27663. this._dispersion = 0;
  27664. this._iridescence = 0;
  27665. this._sheen = 0.0;
  27666. this._transmission = 0;
  27667. this.setValues( parameters );
  27668. }
  27669. /**
  27670. * The anisotropy strength.
  27671. *
  27672. * @type {number}
  27673. * @default 0
  27674. */
  27675. get anisotropy() {
  27676. return this._anisotropy;
  27677. }
  27678. set anisotropy( value ) {
  27679. if ( this._anisotropy > 0 !== value > 0 ) {
  27680. this.version ++;
  27681. }
  27682. this._anisotropy = value;
  27683. }
  27684. /**
  27685. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  27686. * clear coat related properties to enable multilayer materials that have a
  27687. * thin translucent layer over the base layer.
  27688. *
  27689. * @type {number}
  27690. * @default 0
  27691. */
  27692. get clearcoat() {
  27693. return this._clearcoat;
  27694. }
  27695. set clearcoat( value ) {
  27696. if ( this._clearcoat > 0 !== value > 0 ) {
  27697. this.version ++;
  27698. }
  27699. this._clearcoat = value;
  27700. }
  27701. /**
  27702. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  27703. * the surface and the viewer, from `0.0` to `1.0`.
  27704. *
  27705. * @type {number}
  27706. * @default 0
  27707. */
  27708. get iridescence() {
  27709. return this._iridescence;
  27710. }
  27711. set iridescence( value ) {
  27712. if ( this._iridescence > 0 !== value > 0 ) {
  27713. this.version ++;
  27714. }
  27715. this._iridescence = value;
  27716. }
  27717. /**
  27718. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  27719. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  27720. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  27721. *
  27722. * @type {number}
  27723. * @default 0
  27724. */
  27725. get dispersion() {
  27726. return this._dispersion;
  27727. }
  27728. set dispersion( value ) {
  27729. if ( this._dispersion > 0 !== value > 0 ) {
  27730. this.version ++;
  27731. }
  27732. this._dispersion = value;
  27733. }
  27734. /**
  27735. * The intensity of the sheen layer, from `0.0` to `1.0`.
  27736. *
  27737. * @type {number}
  27738. * @default 0
  27739. */
  27740. get sheen() {
  27741. return this._sheen;
  27742. }
  27743. set sheen( value ) {
  27744. if ( this._sheen > 0 !== value > 0 ) {
  27745. this.version ++;
  27746. }
  27747. this._sheen = value;
  27748. }
  27749. /**
  27750. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  27751. *
  27752. * Thin, transparent or semitransparent, plastic or glass materials remain
  27753. * largely reflective even if they are fully transmissive. The transmission
  27754. * property can be used to model these materials.
  27755. *
  27756. * When transmission is non-zero, `opacity` should be set to `1`.
  27757. *
  27758. * @type {number}
  27759. * @default 0
  27760. */
  27761. get transmission() {
  27762. return this._transmission;
  27763. }
  27764. set transmission( value ) {
  27765. if ( this._transmission > 0 !== value > 0 ) {
  27766. this.version ++;
  27767. }
  27768. this._transmission = value;
  27769. }
  27770. copy( source ) {
  27771. super.copy( source );
  27772. this.defines = {
  27773. 'STANDARD': '',
  27774. 'PHYSICAL': ''
  27775. };
  27776. this.anisotropy = source.anisotropy;
  27777. this.anisotropyRotation = source.anisotropyRotation;
  27778. this.anisotropyMap = source.anisotropyMap;
  27779. this.clearcoat = source.clearcoat;
  27780. this.clearcoatMap = source.clearcoatMap;
  27781. this.clearcoatRoughness = source.clearcoatRoughness;
  27782. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  27783. this.clearcoatNormalMap = source.clearcoatNormalMap;
  27784. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  27785. this.dispersion = source.dispersion;
  27786. this.ior = source.ior;
  27787. this.iridescence = source.iridescence;
  27788. this.iridescenceMap = source.iridescenceMap;
  27789. this.iridescenceIOR = source.iridescenceIOR;
  27790. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  27791. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  27792. this.sheen = source.sheen;
  27793. this.sheenColor.copy( source.sheenColor );
  27794. this.sheenColorMap = source.sheenColorMap;
  27795. this.sheenRoughness = source.sheenRoughness;
  27796. this.sheenRoughnessMap = source.sheenRoughnessMap;
  27797. this.transmission = source.transmission;
  27798. this.transmissionMap = source.transmissionMap;
  27799. this.thickness = source.thickness;
  27800. this.thicknessMap = source.thicknessMap;
  27801. this.attenuationDistance = source.attenuationDistance;
  27802. this.attenuationColor.copy( source.attenuationColor );
  27803. this.specularIntensity = source.specularIntensity;
  27804. this.specularIntensityMap = source.specularIntensityMap;
  27805. this.specularColor.copy( source.specularColor );
  27806. this.specularColorMap = source.specularColorMap;
  27807. return this;
  27808. }
  27809. }
  27810. /**
  27811. * A material for shiny surfaces with specular highlights.
  27812. *
  27813. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  27814. * model for calculating reflectance. Unlike the Lambertian model used in the
  27815. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  27816. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  27817. *
  27818. * Performance will generally be greater when using this material over the
  27819. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  27820. * some graphical accuracy.
  27821. *
  27822. * @augments Material
  27823. */
  27824. class MeshPhongMaterial extends Material {
  27825. /**
  27826. * Constructs a new mesh phong material.
  27827. *
  27828. * @param {Object} [parameters] - An object with one or more properties
  27829. * defining the material's appearance. Any property of the material
  27830. * (including any property from inherited materials) can be passed
  27831. * in here. Color values can be passed any type of value accepted
  27832. * by {@link Color#set}.
  27833. */
  27834. constructor( parameters ) {
  27835. super();
  27836. /**
  27837. * This flag can be used for type testing.
  27838. *
  27839. * @type {boolean}
  27840. * @readonly
  27841. * @default true
  27842. */
  27843. this.isMeshPhongMaterial = true;
  27844. this.type = 'MeshPhongMaterial';
  27845. /**
  27846. * Color of the material.
  27847. *
  27848. * @type {Color}
  27849. * @default (1,1,1)
  27850. */
  27851. this.color = new Color( 0xffffff ); // diffuse
  27852. /**
  27853. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  27854. *
  27855. * This defines how shiny the material is and the color of its shine.
  27856. *
  27857. * @type {Color}
  27858. */
  27859. this.specular = new Color( 0x111111 );
  27860. /**
  27861. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  27862. *
  27863. * @type {number}
  27864. * @default 30
  27865. */
  27866. this.shininess = 30;
  27867. /**
  27868. * The color map. May optionally include an alpha channel, typically combined
  27869. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27870. * color is modulated by the diffuse `color`.
  27871. *
  27872. * @type {?Texture}
  27873. * @default null
  27874. */
  27875. this.map = null;
  27876. /**
  27877. * The light map. Requires a second set of UVs.
  27878. *
  27879. * @type {?Texture}
  27880. * @default null
  27881. */
  27882. this.lightMap = null;
  27883. /**
  27884. * Intensity of the baked light.
  27885. *
  27886. * @type {number}
  27887. * @default 1
  27888. */
  27889. this.lightMapIntensity = 1.0;
  27890. /**
  27891. * The red channel of this texture is used as the ambient occlusion map.
  27892. * Requires a second set of UVs.
  27893. *
  27894. * @type {?Texture}
  27895. * @default null
  27896. */
  27897. this.aoMap = null;
  27898. /**
  27899. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27900. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27901. * red channel is also `1`, ambient light is fully occluded on a surface.
  27902. *
  27903. * @type {number}
  27904. * @default 1
  27905. */
  27906. this.aoMapIntensity = 1.0;
  27907. /**
  27908. * Emissive (light) color of the material, essentially a solid color
  27909. * unaffected by other lighting.
  27910. *
  27911. * @type {Color}
  27912. * @default (0,0,0)
  27913. */
  27914. this.emissive = new Color( 0x000000 );
  27915. /**
  27916. * Intensity of the emissive light. Modulates the emissive color.
  27917. *
  27918. * @type {number}
  27919. * @default 1
  27920. */
  27921. this.emissiveIntensity = 1.0;
  27922. /**
  27923. * Set emissive (glow) map. The emissive map color is modulated by the
  27924. * emissive color and the emissive intensity. If you have an emissive map,
  27925. * be sure to set the emissive color to something other than black.
  27926. *
  27927. * @type {?Texture}
  27928. * @default null
  27929. */
  27930. this.emissiveMap = null;
  27931. /**
  27932. * The texture to create a bump map. The black and white values map to the
  27933. * perceived depth in relation to the lights. Bump doesn't actually affect
  27934. * the geometry of the object, only the lighting. If a normal map is defined
  27935. * this will be ignored.
  27936. *
  27937. * @type {?Texture}
  27938. * @default null
  27939. */
  27940. this.bumpMap = null;
  27941. /**
  27942. * How much the bump map affects the material. Typical range is `[0,1]`.
  27943. *
  27944. * @type {number}
  27945. * @default 1
  27946. */
  27947. this.bumpScale = 1;
  27948. /**
  27949. * The texture to create a normal map. The RGB values affect the surface
  27950. * normal for each pixel fragment and change the way the color is lit. Normal
  27951. * maps do not change the actual shape of the surface, only the lighting. In
  27952. * case the material has a normal map authored using the left handed
  27953. * convention, the `y` component of `normalScale` should be negated to compensate
  27954. * for the different handedness.
  27955. *
  27956. * @type {?Texture}
  27957. * @default null
  27958. */
  27959. this.normalMap = null;
  27960. /**
  27961. * The type of normal map.
  27962. *
  27963. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27964. * @default TangentSpaceNormalMap
  27965. */
  27966. this.normalMapType = TangentSpaceNormalMap;
  27967. /**
  27968. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27969. *
  27970. * @type {Vector2}
  27971. * @default (1,1)
  27972. */
  27973. this.normalScale = new Vector2( 1, 1 );
  27974. /**
  27975. * The displacement map affects the position of the mesh's vertices. Unlike
  27976. * other maps which only affect the light and shade of the material the
  27977. * displaced vertices can cast shadows, block other objects, and otherwise
  27978. * act as real geometry. The displacement texture is an image where the value
  27979. * of each pixel (white being the highest) is mapped against, and
  27980. * repositions, the vertices of the mesh.
  27981. *
  27982. * @type {?Texture}
  27983. * @default null
  27984. */
  27985. this.displacementMap = null;
  27986. /**
  27987. * How much the displacement map affects the mesh (where black is no
  27988. * displacement, and white is maximum displacement). Without a displacement
  27989. * map set, this value is not applied.
  27990. *
  27991. * @type {number}
  27992. * @default 0
  27993. */
  27994. this.displacementScale = 1;
  27995. /**
  27996. * The offset of the displacement map's values on the mesh's vertices.
  27997. * The bias is added to the scaled sample of the displacement map.
  27998. * Without a displacement map set, this value is not applied.
  27999. *
  28000. * @type {number}
  28001. * @default 0
  28002. */
  28003. this.displacementBias = 0;
  28004. /**
  28005. * The specular map value affects both how much the specular surface
  28006. * highlight contributes and how much of the environment map affects the
  28007. * surface.
  28008. *
  28009. * @type {?Texture}
  28010. * @default null
  28011. */
  28012. this.specularMap = null;
  28013. /**
  28014. * The alpha map is a grayscale texture that controls the opacity across the
  28015. * surface (black: fully transparent; white: fully opaque).
  28016. *
  28017. * Only the color of the texture is used, ignoring the alpha channel if one
  28018. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28019. * when sampling this texture due to the extra bit of precision provided for
  28020. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28021. * luminance/alpha textures will also still work as expected.
  28022. *
  28023. * @type {?Texture}
  28024. * @default null
  28025. */
  28026. this.alphaMap = null;
  28027. /**
  28028. * The environment map.
  28029. *
  28030. * @type {?Texture}
  28031. * @default null
  28032. */
  28033. this.envMap = null;
  28034. /**
  28035. * The rotation of the environment map in radians.
  28036. *
  28037. * @type {Euler}
  28038. * @default (0,0,0)
  28039. */
  28040. this.envMapRotation = new Euler();
  28041. /**
  28042. * How to combine the result of the surface's color with the environment map, if any.
  28043. *
  28044. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28045. * blend between the two colors.
  28046. *
  28047. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28048. * @default MultiplyOperation
  28049. */
  28050. this.combine = MultiplyOperation;
  28051. /**
  28052. * How much the environment map affects the surface.
  28053. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28054. *
  28055. * @type {number}
  28056. * @default 1
  28057. */
  28058. this.reflectivity = 1;
  28059. /**
  28060. * The index of refraction (IOR) of air (approximately 1) divided by the
  28061. * index of refraction of the material. It is used with environment mapping
  28062. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28063. * The refraction ratio should not exceed `1`.
  28064. *
  28065. * @type {number}
  28066. * @default 0.98
  28067. */
  28068. this.refractionRatio = 0.98;
  28069. /**
  28070. * Renders the geometry as a wireframe.
  28071. *
  28072. * @type {boolean}
  28073. * @default false
  28074. */
  28075. this.wireframe = false;
  28076. /**
  28077. * Controls the thickness of the wireframe.
  28078. *
  28079. * Can only be used with {@link SVGRenderer}.
  28080. *
  28081. * @type {number}
  28082. * @default 1
  28083. */
  28084. this.wireframeLinewidth = 1;
  28085. /**
  28086. * Defines appearance of wireframe ends.
  28087. *
  28088. * Can only be used with {@link SVGRenderer}.
  28089. *
  28090. * @type {('round'|'bevel'|'miter')}
  28091. * @default 'round'
  28092. */
  28093. this.wireframeLinecap = 'round';
  28094. /**
  28095. * Defines appearance of wireframe joints.
  28096. *
  28097. * Can only be used with {@link SVGRenderer}.
  28098. *
  28099. * @type {('round'|'bevel'|'miter')}
  28100. * @default 'round'
  28101. */
  28102. this.wireframeLinejoin = 'round';
  28103. /**
  28104. * Whether the material is rendered with flat shading or not.
  28105. *
  28106. * @type {boolean}
  28107. * @default false
  28108. */
  28109. this.flatShading = false;
  28110. /**
  28111. * Whether the material is affected by fog or not.
  28112. *
  28113. * @type {boolean}
  28114. * @default true
  28115. */
  28116. this.fog = true;
  28117. this.setValues( parameters );
  28118. }
  28119. copy( source ) {
  28120. super.copy( source );
  28121. this.color.copy( source.color );
  28122. this.specular.copy( source.specular );
  28123. this.shininess = source.shininess;
  28124. this.map = source.map;
  28125. this.lightMap = source.lightMap;
  28126. this.lightMapIntensity = source.lightMapIntensity;
  28127. this.aoMap = source.aoMap;
  28128. this.aoMapIntensity = source.aoMapIntensity;
  28129. this.emissive.copy( source.emissive );
  28130. this.emissiveMap = source.emissiveMap;
  28131. this.emissiveIntensity = source.emissiveIntensity;
  28132. this.bumpMap = source.bumpMap;
  28133. this.bumpScale = source.bumpScale;
  28134. this.normalMap = source.normalMap;
  28135. this.normalMapType = source.normalMapType;
  28136. this.normalScale.copy( source.normalScale );
  28137. this.displacementMap = source.displacementMap;
  28138. this.displacementScale = source.displacementScale;
  28139. this.displacementBias = source.displacementBias;
  28140. this.specularMap = source.specularMap;
  28141. this.alphaMap = source.alphaMap;
  28142. this.envMap = source.envMap;
  28143. this.envMapRotation.copy( source.envMapRotation );
  28144. this.combine = source.combine;
  28145. this.reflectivity = source.reflectivity;
  28146. this.refractionRatio = source.refractionRatio;
  28147. this.wireframe = source.wireframe;
  28148. this.wireframeLinewidth = source.wireframeLinewidth;
  28149. this.wireframeLinecap = source.wireframeLinecap;
  28150. this.wireframeLinejoin = source.wireframeLinejoin;
  28151. this.flatShading = source.flatShading;
  28152. this.fog = source.fog;
  28153. return this;
  28154. }
  28155. }
  28156. /**
  28157. * A material implementing toon shading.
  28158. *
  28159. * @augments Material
  28160. */
  28161. class MeshToonMaterial extends Material {
  28162. /**
  28163. * Constructs a new mesh toon material.
  28164. *
  28165. * @param {Object} [parameters] - An object with one or more properties
  28166. * defining the material's appearance. Any property of the material
  28167. * (including any property from inherited materials) can be passed
  28168. * in here. Color values can be passed any type of value accepted
  28169. * by {@link Color#set}.
  28170. */
  28171. constructor( parameters ) {
  28172. super();
  28173. /**
  28174. * This flag can be used for type testing.
  28175. *
  28176. * @type {boolean}
  28177. * @readonly
  28178. * @default true
  28179. */
  28180. this.isMeshToonMaterial = true;
  28181. this.defines = { 'TOON': '' };
  28182. this.type = 'MeshToonMaterial';
  28183. /**
  28184. * Color of the material.
  28185. *
  28186. * @type {Color}
  28187. * @default (1,1,1)
  28188. */
  28189. this.color = new Color( 0xffffff );
  28190. /**
  28191. * The color map. May optionally include an alpha channel, typically combined
  28192. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28193. * color is modulated by the diffuse `color`.
  28194. *
  28195. * @type {?Texture}
  28196. * @default null
  28197. */
  28198. this.map = null;
  28199. /**
  28200. * Gradient map for toon shading. It's required to set
  28201. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28202. * when using this type of texture.
  28203. *
  28204. * @type {?Texture}
  28205. * @default null
  28206. */
  28207. this.gradientMap = null;
  28208. /**
  28209. * The light map. Requires a second set of UVs.
  28210. *
  28211. * @type {?Texture}
  28212. * @default null
  28213. */
  28214. this.lightMap = null;
  28215. /**
  28216. * Intensity of the baked light.
  28217. *
  28218. * @type {number}
  28219. * @default 1
  28220. */
  28221. this.lightMapIntensity = 1.0;
  28222. /**
  28223. * The red channel of this texture is used as the ambient occlusion map.
  28224. * Requires a second set of UVs.
  28225. *
  28226. * @type {?Texture}
  28227. * @default null
  28228. */
  28229. this.aoMap = null;
  28230. /**
  28231. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28232. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28233. * red channel is also `1`, ambient light is fully occluded on a surface.
  28234. *
  28235. * @type {number}
  28236. * @default 1
  28237. */
  28238. this.aoMapIntensity = 1.0;
  28239. /**
  28240. * Emissive (light) color of the material, essentially a solid color
  28241. * unaffected by other lighting.
  28242. *
  28243. * @type {Color}
  28244. * @default (0,0,0)
  28245. */
  28246. this.emissive = new Color( 0x000000 );
  28247. /**
  28248. * Intensity of the emissive light. Modulates the emissive color.
  28249. *
  28250. * @type {number}
  28251. * @default 1
  28252. */
  28253. this.emissiveIntensity = 1.0;
  28254. /**
  28255. * Set emissive (glow) map. The emissive map color is modulated by the
  28256. * emissive color and the emissive intensity. If you have an emissive map,
  28257. * be sure to set the emissive color to something other than black.
  28258. *
  28259. * @type {?Texture}
  28260. * @default null
  28261. */
  28262. this.emissiveMap = null;
  28263. /**
  28264. * The texture to create a bump map. The black and white values map to the
  28265. * perceived depth in relation to the lights. Bump doesn't actually affect
  28266. * the geometry of the object, only the lighting. If a normal map is defined
  28267. * this will be ignored.
  28268. *
  28269. * @type {?Texture}
  28270. * @default null
  28271. */
  28272. this.bumpMap = null;
  28273. /**
  28274. * How much the bump map affects the material. Typical range is `[0,1]`.
  28275. *
  28276. * @type {number}
  28277. * @default 1
  28278. */
  28279. this.bumpScale = 1;
  28280. /**
  28281. * The texture to create a normal map. The RGB values affect the surface
  28282. * normal for each pixel fragment and change the way the color is lit. Normal
  28283. * maps do not change the actual shape of the surface, only the lighting. In
  28284. * case the material has a normal map authored using the left handed
  28285. * convention, the `y` component of `normalScale` should be negated to compensate
  28286. * for the different handedness.
  28287. *
  28288. * @type {?Texture}
  28289. * @default null
  28290. */
  28291. this.normalMap = null;
  28292. /**
  28293. * The type of normal map.
  28294. *
  28295. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28296. * @default TangentSpaceNormalMap
  28297. */
  28298. this.normalMapType = TangentSpaceNormalMap;
  28299. /**
  28300. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28301. *
  28302. * @type {Vector2}
  28303. * @default (1,1)
  28304. */
  28305. this.normalScale = new Vector2( 1, 1 );
  28306. /**
  28307. * The displacement map affects the position of the mesh's vertices. Unlike
  28308. * other maps which only affect the light and shade of the material the
  28309. * displaced vertices can cast shadows, block other objects, and otherwise
  28310. * act as real geometry. The displacement texture is an image where the value
  28311. * of each pixel (white being the highest) is mapped against, and
  28312. * repositions, the vertices of the mesh.
  28313. *
  28314. * @type {?Texture}
  28315. * @default null
  28316. */
  28317. this.displacementMap = null;
  28318. /**
  28319. * How much the displacement map affects the mesh (where black is no
  28320. * displacement, and white is maximum displacement). Without a displacement
  28321. * map set, this value is not applied.
  28322. *
  28323. * @type {number}
  28324. * @default 0
  28325. */
  28326. this.displacementScale = 1;
  28327. /**
  28328. * The offset of the displacement map's values on the mesh's vertices.
  28329. * The bias is added to the scaled sample of the displacement map.
  28330. * Without a displacement map set, this value is not applied.
  28331. *
  28332. * @type {number}
  28333. * @default 0
  28334. */
  28335. this.displacementBias = 0;
  28336. /**
  28337. * The alpha map is a grayscale texture that controls the opacity across the
  28338. * surface (black: fully transparent; white: fully opaque).
  28339. *
  28340. * Only the color of the texture is used, ignoring the alpha channel if one
  28341. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28342. * when sampling this texture due to the extra bit of precision provided for
  28343. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28344. * luminance/alpha textures will also still work as expected.
  28345. *
  28346. * @type {?Texture}
  28347. * @default null
  28348. */
  28349. this.alphaMap = null;
  28350. /**
  28351. * Renders the geometry as a wireframe.
  28352. *
  28353. * @type {boolean}
  28354. * @default false
  28355. */
  28356. this.wireframe = false;
  28357. /**
  28358. * Controls the thickness of the wireframe.
  28359. *
  28360. * Can only be used with {@link SVGRenderer}.
  28361. *
  28362. * @type {number}
  28363. * @default 1
  28364. */
  28365. this.wireframeLinewidth = 1;
  28366. /**
  28367. * Defines appearance of wireframe ends.
  28368. *
  28369. * Can only be used with {@link SVGRenderer}.
  28370. *
  28371. * @type {('round'|'bevel'|'miter')}
  28372. * @default 'round'
  28373. */
  28374. this.wireframeLinecap = 'round';
  28375. /**
  28376. * Defines appearance of wireframe joints.
  28377. *
  28378. * Can only be used with {@link SVGRenderer}.
  28379. *
  28380. * @type {('round'|'bevel'|'miter')}
  28381. * @default 'round'
  28382. */
  28383. this.wireframeLinejoin = 'round';
  28384. /**
  28385. * Whether the material is affected by fog or not.
  28386. *
  28387. * @type {boolean}
  28388. * @default true
  28389. */
  28390. this.fog = true;
  28391. this.setValues( parameters );
  28392. }
  28393. copy( source ) {
  28394. super.copy( source );
  28395. this.color.copy( source.color );
  28396. this.map = source.map;
  28397. this.gradientMap = source.gradientMap;
  28398. this.lightMap = source.lightMap;
  28399. this.lightMapIntensity = source.lightMapIntensity;
  28400. this.aoMap = source.aoMap;
  28401. this.aoMapIntensity = source.aoMapIntensity;
  28402. this.emissive.copy( source.emissive );
  28403. this.emissiveMap = source.emissiveMap;
  28404. this.emissiveIntensity = source.emissiveIntensity;
  28405. this.bumpMap = source.bumpMap;
  28406. this.bumpScale = source.bumpScale;
  28407. this.normalMap = source.normalMap;
  28408. this.normalMapType = source.normalMapType;
  28409. this.normalScale.copy( source.normalScale );
  28410. this.displacementMap = source.displacementMap;
  28411. this.displacementScale = source.displacementScale;
  28412. this.displacementBias = source.displacementBias;
  28413. this.alphaMap = source.alphaMap;
  28414. this.wireframe = source.wireframe;
  28415. this.wireframeLinewidth = source.wireframeLinewidth;
  28416. this.wireframeLinecap = source.wireframeLinecap;
  28417. this.wireframeLinejoin = source.wireframeLinejoin;
  28418. this.fog = source.fog;
  28419. return this;
  28420. }
  28421. }
  28422. /**
  28423. * A material that maps the normal vectors to RGB colors.
  28424. *
  28425. * @augments Material
  28426. */
  28427. class MeshNormalMaterial extends Material {
  28428. /**
  28429. * Constructs a new mesh normal material.
  28430. *
  28431. * @param {Object} [parameters] - An object with one or more properties
  28432. * defining the material's appearance. Any property of the material
  28433. * (including any property from inherited materials) can be passed
  28434. * in here. Color values can be passed any type of value accepted
  28435. * by {@link Color#set}.
  28436. */
  28437. constructor( parameters ) {
  28438. super();
  28439. /**
  28440. * This flag can be used for type testing.
  28441. *
  28442. * @type {boolean}
  28443. * @readonly
  28444. * @default true
  28445. */
  28446. this.isMeshNormalMaterial = true;
  28447. this.type = 'MeshNormalMaterial';
  28448. /**
  28449. * The texture to create a bump map. The black and white values map to the
  28450. * perceived depth in relation to the lights. Bump doesn't actually affect
  28451. * the geometry of the object, only the lighting. If a normal map is defined
  28452. * this will be ignored.
  28453. *
  28454. * @type {?Texture}
  28455. * @default null
  28456. */
  28457. this.bumpMap = null;
  28458. /**
  28459. * How much the bump map affects the material. Typical range is `[0,1]`.
  28460. *
  28461. * @type {number}
  28462. * @default 1
  28463. */
  28464. this.bumpScale = 1;
  28465. /**
  28466. * The texture to create a normal map. The RGB values affect the surface
  28467. * normal for each pixel fragment and change the way the color is lit. Normal
  28468. * maps do not change the actual shape of the surface, only the lighting. In
  28469. * case the material has a normal map authored using the left handed
  28470. * convention, the `y` component of `normalScale` should be negated to compensate
  28471. * for the different handedness.
  28472. *
  28473. * @type {?Texture}
  28474. * @default null
  28475. */
  28476. this.normalMap = null;
  28477. /**
  28478. * The type of normal map.
  28479. *
  28480. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28481. * @default TangentSpaceNormalMap
  28482. */
  28483. this.normalMapType = TangentSpaceNormalMap;
  28484. /**
  28485. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28486. *
  28487. * @type {Vector2}
  28488. * @default (1,1)
  28489. */
  28490. this.normalScale = new Vector2( 1, 1 );
  28491. /**
  28492. * The displacement map affects the position of the mesh's vertices. Unlike
  28493. * other maps which only affect the light and shade of the material the
  28494. * displaced vertices can cast shadows, block other objects, and otherwise
  28495. * act as real geometry. The displacement texture is an image where the value
  28496. * of each pixel (white being the highest) is mapped against, and
  28497. * repositions, the vertices of the mesh.
  28498. *
  28499. * @type {?Texture}
  28500. * @default null
  28501. */
  28502. this.displacementMap = null;
  28503. /**
  28504. * How much the displacement map affects the mesh (where black is no
  28505. * displacement, and white is maximum displacement). Without a displacement
  28506. * map set, this value is not applied.
  28507. *
  28508. * @type {number}
  28509. * @default 0
  28510. */
  28511. this.displacementScale = 1;
  28512. /**
  28513. * The offset of the displacement map's values on the mesh's vertices.
  28514. * The bias is added to the scaled sample of the displacement map.
  28515. * Without a displacement map set, this value is not applied.
  28516. *
  28517. * @type {number}
  28518. * @default 0
  28519. */
  28520. this.displacementBias = 0;
  28521. /**
  28522. * Renders the geometry as a wireframe.
  28523. *
  28524. * @type {boolean}
  28525. * @default false
  28526. */
  28527. this.wireframe = false;
  28528. /**
  28529. * Controls the thickness of the wireframe.
  28530. *
  28531. * WebGL and WebGPU ignore this property and always render
  28532. * 1 pixel wide lines.
  28533. *
  28534. * @type {number}
  28535. * @default 1
  28536. */
  28537. this.wireframeLinewidth = 1;
  28538. /**
  28539. * Whether the material is rendered with flat shading or not.
  28540. *
  28541. * @type {boolean}
  28542. * @default false
  28543. */
  28544. this.flatShading = false;
  28545. this.setValues( parameters );
  28546. }
  28547. copy( source ) {
  28548. super.copy( source );
  28549. this.bumpMap = source.bumpMap;
  28550. this.bumpScale = source.bumpScale;
  28551. this.normalMap = source.normalMap;
  28552. this.normalMapType = source.normalMapType;
  28553. this.normalScale.copy( source.normalScale );
  28554. this.displacementMap = source.displacementMap;
  28555. this.displacementScale = source.displacementScale;
  28556. this.displacementBias = source.displacementBias;
  28557. this.wireframe = source.wireframe;
  28558. this.wireframeLinewidth = source.wireframeLinewidth;
  28559. this.flatShading = source.flatShading;
  28560. return this;
  28561. }
  28562. }
  28563. /**
  28564. * A material for non-shiny surfaces, without specular highlights.
  28565. *
  28566. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  28567. * model for calculating reflectance. This can simulate some surfaces (such
  28568. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  28569. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  28570. * shading.
  28571. *
  28572. * Due to the simplicity of the reflectance and illumination models,
  28573. * performance will be greater when using this material over the
  28574. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  28575. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  28576. *
  28577. * @augments Material
  28578. */
  28579. class MeshLambertMaterial extends Material {
  28580. /**
  28581. * Constructs a new mesh lambert material.
  28582. *
  28583. * @param {Object} [parameters] - An object with one or more properties
  28584. * defining the material's appearance. Any property of the material
  28585. * (including any property from inherited materials) can be passed
  28586. * in here. Color values can be passed any type of value accepted
  28587. * by {@link Color#set}.
  28588. */
  28589. constructor( parameters ) {
  28590. super();
  28591. /**
  28592. * This flag can be used for type testing.
  28593. *
  28594. * @type {boolean}
  28595. * @readonly
  28596. * @default true
  28597. */
  28598. this.isMeshLambertMaterial = true;
  28599. this.type = 'MeshLambertMaterial';
  28600. /**
  28601. * Color of the material.
  28602. *
  28603. * @type {Color}
  28604. * @default (1,1,1)
  28605. */
  28606. this.color = new Color( 0xffffff ); // diffuse
  28607. /**
  28608. * The color map. May optionally include an alpha channel, typically combined
  28609. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28610. * color is modulated by the diffuse `color`.
  28611. *
  28612. * @type {?Texture}
  28613. * @default null
  28614. */
  28615. this.map = null;
  28616. /**
  28617. * The light map. Requires a second set of UVs.
  28618. *
  28619. * @type {?Texture}
  28620. * @default null
  28621. */
  28622. this.lightMap = null;
  28623. /**
  28624. * Intensity of the baked light.
  28625. *
  28626. * @type {number}
  28627. * @default 1
  28628. */
  28629. this.lightMapIntensity = 1.0;
  28630. /**
  28631. * The red channel of this texture is used as the ambient occlusion map.
  28632. * Requires a second set of UVs.
  28633. *
  28634. * @type {?Texture}
  28635. * @default null
  28636. */
  28637. this.aoMap = null;
  28638. /**
  28639. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28640. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28641. * red channel is also `1`, ambient light is fully occluded on a surface.
  28642. *
  28643. * @type {number}
  28644. * @default 1
  28645. */
  28646. this.aoMapIntensity = 1.0;
  28647. /**
  28648. * Emissive (light) color of the material, essentially a solid color
  28649. * unaffected by other lighting.
  28650. *
  28651. * @type {Color}
  28652. * @default (0,0,0)
  28653. */
  28654. this.emissive = new Color( 0x000000 );
  28655. /**
  28656. * Intensity of the emissive light. Modulates the emissive color.
  28657. *
  28658. * @type {number}
  28659. * @default 1
  28660. */
  28661. this.emissiveIntensity = 1.0;
  28662. /**
  28663. * Set emissive (glow) map. The emissive map color is modulated by the
  28664. * emissive color and the emissive intensity. If you have an emissive map,
  28665. * be sure to set the emissive color to something other than black.
  28666. *
  28667. * @type {?Texture}
  28668. * @default null
  28669. */
  28670. this.emissiveMap = null;
  28671. /**
  28672. * The texture to create a bump map. The black and white values map to the
  28673. * perceived depth in relation to the lights. Bump doesn't actually affect
  28674. * the geometry of the object, only the lighting. If a normal map is defined
  28675. * this will be ignored.
  28676. *
  28677. * @type {?Texture}
  28678. * @default null
  28679. */
  28680. this.bumpMap = null;
  28681. /**
  28682. * How much the bump map affects the material. Typical range is `[0,1]`.
  28683. *
  28684. * @type {number}
  28685. * @default 1
  28686. */
  28687. this.bumpScale = 1;
  28688. /**
  28689. * The texture to create a normal map. The RGB values affect the surface
  28690. * normal for each pixel fragment and change the way the color is lit. Normal
  28691. * maps do not change the actual shape of the surface, only the lighting. In
  28692. * case the material has a normal map authored using the left handed
  28693. * convention, the `y` component of `normalScale` should be negated to compensate
  28694. * for the different handedness.
  28695. *
  28696. * @type {?Texture}
  28697. * @default null
  28698. */
  28699. this.normalMap = null;
  28700. /**
  28701. * The type of normal map.
  28702. *
  28703. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28704. * @default TangentSpaceNormalMap
  28705. */
  28706. this.normalMapType = TangentSpaceNormalMap;
  28707. /**
  28708. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28709. *
  28710. * @type {Vector2}
  28711. * @default (1,1)
  28712. */
  28713. this.normalScale = new Vector2( 1, 1 );
  28714. /**
  28715. * The displacement map affects the position of the mesh's vertices. Unlike
  28716. * other maps which only affect the light and shade of the material the
  28717. * displaced vertices can cast shadows, block other objects, and otherwise
  28718. * act as real geometry. The displacement texture is an image where the value
  28719. * of each pixel (white being the highest) is mapped against, and
  28720. * repositions, the vertices of the mesh.
  28721. *
  28722. * @type {?Texture}
  28723. * @default null
  28724. */
  28725. this.displacementMap = null;
  28726. /**
  28727. * How much the displacement map affects the mesh (where black is no
  28728. * displacement, and white is maximum displacement). Without a displacement
  28729. * map set, this value is not applied.
  28730. *
  28731. * @type {number}
  28732. * @default 0
  28733. */
  28734. this.displacementScale = 1;
  28735. /**
  28736. * The offset of the displacement map's values on the mesh's vertices.
  28737. * The bias is added to the scaled sample of the displacement map.
  28738. * Without a displacement map set, this value is not applied.
  28739. *
  28740. * @type {number}
  28741. * @default 0
  28742. */
  28743. this.displacementBias = 0;
  28744. /**
  28745. * Specular map used by the material.
  28746. *
  28747. * @type {?Texture}
  28748. * @default null
  28749. */
  28750. this.specularMap = null;
  28751. /**
  28752. * The alpha map is a grayscale texture that controls the opacity across the
  28753. * surface (black: fully transparent; white: fully opaque).
  28754. *
  28755. * Only the color of the texture is used, ignoring the alpha channel if one
  28756. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28757. * when sampling this texture due to the extra bit of precision provided for
  28758. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28759. * luminance/alpha textures will also still work as expected.
  28760. *
  28761. * @type {?Texture}
  28762. * @default null
  28763. */
  28764. this.alphaMap = null;
  28765. /**
  28766. * The environment map.
  28767. *
  28768. * @type {?Texture}
  28769. * @default null
  28770. */
  28771. this.envMap = null;
  28772. /**
  28773. * The rotation of the environment map in radians.
  28774. *
  28775. * @type {Euler}
  28776. * @default (0,0,0)
  28777. */
  28778. this.envMapRotation = new Euler();
  28779. /**
  28780. * How to combine the result of the surface's color with the environment map, if any.
  28781. *
  28782. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28783. * blend between the two colors.
  28784. *
  28785. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28786. * @default MultiplyOperation
  28787. */
  28788. this.combine = MultiplyOperation;
  28789. /**
  28790. * How much the environment map affects the surface.
  28791. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28792. *
  28793. * @type {number}
  28794. * @default 1
  28795. */
  28796. this.reflectivity = 1;
  28797. /**
  28798. * The index of refraction (IOR) of air (approximately 1) divided by the
  28799. * index of refraction of the material. It is used with environment mapping
  28800. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28801. * The refraction ratio should not exceed `1`.
  28802. *
  28803. * @type {number}
  28804. * @default 0.98
  28805. */
  28806. this.refractionRatio = 0.98;
  28807. /**
  28808. * Renders the geometry as a wireframe.
  28809. *
  28810. * @type {boolean}
  28811. * @default false
  28812. */
  28813. this.wireframe = false;
  28814. /**
  28815. * Controls the thickness of the wireframe.
  28816. *
  28817. * Can only be used with {@link SVGRenderer}.
  28818. *
  28819. * @type {number}
  28820. * @default 1
  28821. */
  28822. this.wireframeLinewidth = 1;
  28823. /**
  28824. * Defines appearance of wireframe ends.
  28825. *
  28826. * Can only be used with {@link SVGRenderer}.
  28827. *
  28828. * @type {('round'|'bevel'|'miter')}
  28829. * @default 'round'
  28830. */
  28831. this.wireframeLinecap = 'round';
  28832. /**
  28833. * Defines appearance of wireframe joints.
  28834. *
  28835. * Can only be used with {@link SVGRenderer}.
  28836. *
  28837. * @type {('round'|'bevel'|'miter')}
  28838. * @default 'round'
  28839. */
  28840. this.wireframeLinejoin = 'round';
  28841. /**
  28842. * Whether the material is rendered with flat shading or not.
  28843. *
  28844. * @type {boolean}
  28845. * @default false
  28846. */
  28847. this.flatShading = false;
  28848. /**
  28849. * Whether the material is affected by fog or not.
  28850. *
  28851. * @type {boolean}
  28852. * @default true
  28853. */
  28854. this.fog = true;
  28855. this.setValues( parameters );
  28856. }
  28857. copy( source ) {
  28858. super.copy( source );
  28859. this.color.copy( source.color );
  28860. this.map = source.map;
  28861. this.lightMap = source.lightMap;
  28862. this.lightMapIntensity = source.lightMapIntensity;
  28863. this.aoMap = source.aoMap;
  28864. this.aoMapIntensity = source.aoMapIntensity;
  28865. this.emissive.copy( source.emissive );
  28866. this.emissiveMap = source.emissiveMap;
  28867. this.emissiveIntensity = source.emissiveIntensity;
  28868. this.bumpMap = source.bumpMap;
  28869. this.bumpScale = source.bumpScale;
  28870. this.normalMap = source.normalMap;
  28871. this.normalMapType = source.normalMapType;
  28872. this.normalScale.copy( source.normalScale );
  28873. this.displacementMap = source.displacementMap;
  28874. this.displacementScale = source.displacementScale;
  28875. this.displacementBias = source.displacementBias;
  28876. this.specularMap = source.specularMap;
  28877. this.alphaMap = source.alphaMap;
  28878. this.envMap = source.envMap;
  28879. this.envMapRotation.copy( source.envMapRotation );
  28880. this.combine = source.combine;
  28881. this.reflectivity = source.reflectivity;
  28882. this.refractionRatio = source.refractionRatio;
  28883. this.wireframe = source.wireframe;
  28884. this.wireframeLinewidth = source.wireframeLinewidth;
  28885. this.wireframeLinecap = source.wireframeLinecap;
  28886. this.wireframeLinejoin = source.wireframeLinejoin;
  28887. this.flatShading = source.flatShading;
  28888. this.fog = source.fog;
  28889. return this;
  28890. }
  28891. }
  28892. /**
  28893. * A material for drawing geometry by depth. Depth is based off of the camera
  28894. * near and far plane. White is nearest, black is farthest.
  28895. *
  28896. * @augments Material
  28897. */
  28898. class MeshDepthMaterial extends Material {
  28899. /**
  28900. * Constructs a new mesh depth material.
  28901. *
  28902. * @param {Object} [parameters] - An object with one or more properties
  28903. * defining the material's appearance. Any property of the material
  28904. * (including any property from inherited materials) can be passed
  28905. * in here. Color values can be passed any type of value accepted
  28906. * by {@link Color#set}.
  28907. */
  28908. constructor( parameters ) {
  28909. super();
  28910. /**
  28911. * This flag can be used for type testing.
  28912. *
  28913. * @type {boolean}
  28914. * @readonly
  28915. * @default true
  28916. */
  28917. this.isMeshDepthMaterial = true;
  28918. this.type = 'MeshDepthMaterial';
  28919. /**
  28920. * Type for depth packing.
  28921. *
  28922. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  28923. * @default BasicDepthPacking
  28924. */
  28925. this.depthPacking = BasicDepthPacking;
  28926. /**
  28927. * The color map. May optionally include an alpha channel, typically combined
  28928. * with {@link Material#transparent} or {@link Material#alphaTest}.
  28929. *
  28930. * @type {?Texture}
  28931. * @default null
  28932. */
  28933. this.map = null;
  28934. /**
  28935. * The alpha map is a grayscale texture that controls the opacity across the
  28936. * surface (black: fully transparent; white: fully opaque).
  28937. *
  28938. * Only the color of the texture is used, ignoring the alpha channel if one
  28939. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28940. * when sampling this texture due to the extra bit of precision provided for
  28941. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28942. * luminance/alpha textures will also still work as expected.
  28943. *
  28944. * @type {?Texture}
  28945. * @default null
  28946. */
  28947. this.alphaMap = null;
  28948. /**
  28949. * The displacement map affects the position of the mesh's vertices. Unlike
  28950. * other maps which only affect the light and shade of the material the
  28951. * displaced vertices can cast shadows, block other objects, and otherwise
  28952. * act as real geometry. The displacement texture is an image where the value
  28953. * of each pixel (white being the highest) is mapped against, and
  28954. * repositions, the vertices of the mesh.
  28955. *
  28956. * @type {?Texture}
  28957. * @default null
  28958. */
  28959. this.displacementMap = null;
  28960. /**
  28961. * How much the displacement map affects the mesh (where black is no
  28962. * displacement, and white is maximum displacement). Without a displacement
  28963. * map set, this value is not applied.
  28964. *
  28965. * @type {number}
  28966. * @default 0
  28967. */
  28968. this.displacementScale = 1;
  28969. /**
  28970. * The offset of the displacement map's values on the mesh's vertices.
  28971. * The bias is added to the scaled sample of the displacement map.
  28972. * Without a displacement map set, this value is not applied.
  28973. *
  28974. * @type {number}
  28975. * @default 0
  28976. */
  28977. this.displacementBias = 0;
  28978. /**
  28979. * Renders the geometry as a wireframe.
  28980. *
  28981. * @type {boolean}
  28982. * @default false
  28983. */
  28984. this.wireframe = false;
  28985. /**
  28986. * Controls the thickness of the wireframe.
  28987. *
  28988. * WebGL and WebGPU ignore this property and always render
  28989. * 1 pixel wide lines.
  28990. *
  28991. * @type {number}
  28992. * @default 1
  28993. */
  28994. this.wireframeLinewidth = 1;
  28995. this.setValues( parameters );
  28996. }
  28997. copy( source ) {
  28998. super.copy( source );
  28999. this.depthPacking = source.depthPacking;
  29000. this.map = source.map;
  29001. this.alphaMap = source.alphaMap;
  29002. this.displacementMap = source.displacementMap;
  29003. this.displacementScale = source.displacementScale;
  29004. this.displacementBias = source.displacementBias;
  29005. this.wireframe = source.wireframe;
  29006. this.wireframeLinewidth = source.wireframeLinewidth;
  29007. return this;
  29008. }
  29009. }
  29010. /**
  29011. * A material used internally for implementing shadow mapping with
  29012. * point lights.
  29013. *
  29014. * Can also be used to customize the shadow casting of an object by assigning
  29015. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29016. * The following examples demonstrates this approach in order to ensure
  29017. * transparent parts of objects do no cast shadows.
  29018. *
  29019. * @augments Material
  29020. */
  29021. class MeshDistanceMaterial extends Material {
  29022. /**
  29023. * Constructs a new mesh distance 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.isMeshDistanceMaterial = true;
  29041. this.type = 'MeshDistanceMaterial';
  29042. /**
  29043. * The color map. May optionally include an alpha channel, typically combined
  29044. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29045. *
  29046. * @type {?Texture}
  29047. * @default null
  29048. */
  29049. this.map = null;
  29050. /**
  29051. * The alpha map is a grayscale texture that controls the opacity across the
  29052. * surface (black: fully transparent; white: fully opaque).
  29053. *
  29054. * Only the color of the texture is used, ignoring the alpha channel if one
  29055. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29056. * when sampling this texture due to the extra bit of precision provided for
  29057. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29058. * luminance/alpha textures will also still work as expected.
  29059. *
  29060. * @type {?Texture}
  29061. * @default null
  29062. */
  29063. this.alphaMap = null;
  29064. /**
  29065. * The displacement map affects the position of the mesh's vertices. Unlike
  29066. * other maps which only affect the light and shade of the material the
  29067. * displaced vertices can cast shadows, block other objects, and otherwise
  29068. * act as real geometry. The displacement texture is an image where the value
  29069. * of each pixel (white being the highest) is mapped against, and
  29070. * repositions, the vertices of the mesh.
  29071. *
  29072. * @type {?Texture}
  29073. * @default null
  29074. */
  29075. this.displacementMap = null;
  29076. /**
  29077. * How much the displacement map affects the mesh (where black is no
  29078. * displacement, and white is maximum displacement). Without a displacement
  29079. * map set, this value is not applied.
  29080. *
  29081. * @type {number}
  29082. * @default 0
  29083. */
  29084. this.displacementScale = 1;
  29085. /**
  29086. * The offset of the displacement map's values on the mesh's vertices.
  29087. * The bias is added to the scaled sample of the displacement map.
  29088. * Without a displacement map set, this value is not applied.
  29089. *
  29090. * @type {number}
  29091. * @default 0
  29092. */
  29093. this.displacementBias = 0;
  29094. this.setValues( parameters );
  29095. }
  29096. copy( source ) {
  29097. super.copy( source );
  29098. this.map = source.map;
  29099. this.alphaMap = source.alphaMap;
  29100. this.displacementMap = source.displacementMap;
  29101. this.displacementScale = source.displacementScale;
  29102. this.displacementBias = source.displacementBias;
  29103. return this;
  29104. }
  29105. }
  29106. /**
  29107. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29108. * material color and shading.
  29109. *
  29110. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29111. * baked lighting. It will cast a shadow onto an object that receives shadows
  29112. * (and shadow clipping works), but it will not self-shadow or receive
  29113. * shadows.
  29114. *
  29115. * @augments Material
  29116. */
  29117. class MeshMatcapMaterial extends Material {
  29118. /**
  29119. * Constructs a new mesh matcap material.
  29120. *
  29121. * @param {Object} [parameters] - An object with one or more properties
  29122. * defining the material's appearance. Any property of the material
  29123. * (including any property from inherited materials) can be passed
  29124. * in here. Color values can be passed any type of value accepted
  29125. * by {@link Color#set}.
  29126. */
  29127. constructor( parameters ) {
  29128. super();
  29129. /**
  29130. * This flag can be used for type testing.
  29131. *
  29132. * @type {boolean}
  29133. * @readonly
  29134. * @default true
  29135. */
  29136. this.isMeshMatcapMaterial = true;
  29137. this.defines = { 'MATCAP': '' };
  29138. this.type = 'MeshMatcapMaterial';
  29139. /**
  29140. * Color of the material.
  29141. *
  29142. * @type {Color}
  29143. * @default (1,1,1)
  29144. */
  29145. this.color = new Color( 0xffffff ); // diffuse
  29146. /**
  29147. * The matcap map.
  29148. *
  29149. * @type {?Texture}
  29150. * @default null
  29151. */
  29152. this.matcap = null;
  29153. /**
  29154. * The color map. May optionally include an alpha channel, typically combined
  29155. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29156. * color is modulated by the diffuse `color`.
  29157. *
  29158. * @type {?Texture}
  29159. * @default null
  29160. */
  29161. this.map = null;
  29162. /**
  29163. * The texture to create a bump map. The black and white values map to the
  29164. * perceived depth in relation to the lights. Bump doesn't actually affect
  29165. * the geometry of the object, only the lighting. If a normal map is defined
  29166. * this will be ignored.
  29167. *
  29168. * @type {?Texture}
  29169. * @default null
  29170. */
  29171. this.bumpMap = null;
  29172. /**
  29173. * How much the bump map affects the material. Typical range is `[0,1]`.
  29174. *
  29175. * @type {number}
  29176. * @default 1
  29177. */
  29178. this.bumpScale = 1;
  29179. /**
  29180. * The texture to create a normal map. The RGB values affect the surface
  29181. * normal for each pixel fragment and change the way the color is lit. Normal
  29182. * maps do not change the actual shape of the surface, only the lighting. In
  29183. * case the material has a normal map authored using the left handed
  29184. * convention, the `y` component of `normalScale` should be negated to compensate
  29185. * for the different handedness.
  29186. *
  29187. * @type {?Texture}
  29188. * @default null
  29189. */
  29190. this.normalMap = null;
  29191. /**
  29192. * The type of normal map.
  29193. *
  29194. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29195. * @default TangentSpaceNormalMap
  29196. */
  29197. this.normalMapType = TangentSpaceNormalMap;
  29198. /**
  29199. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29200. *
  29201. * @type {Vector2}
  29202. * @default (1,1)
  29203. */
  29204. this.normalScale = new Vector2( 1, 1 );
  29205. /**
  29206. * The displacement map affects the position of the mesh's vertices. Unlike
  29207. * other maps which only affect the light and shade of the material the
  29208. * displaced vertices can cast shadows, block other objects, and otherwise
  29209. * act as real geometry. The displacement texture is an image where the value
  29210. * of each pixel (white being the highest) is mapped against, and
  29211. * repositions, the vertices of the mesh.
  29212. *
  29213. * @type {?Texture}
  29214. * @default null
  29215. */
  29216. this.displacementMap = null;
  29217. /**
  29218. * How much the displacement map affects the mesh (where black is no
  29219. * displacement, and white is maximum displacement). Without a displacement
  29220. * map set, this value is not applied.
  29221. *
  29222. * @type {number}
  29223. * @default 0
  29224. */
  29225. this.displacementScale = 1;
  29226. /**
  29227. * The offset of the displacement map's values on the mesh's vertices.
  29228. * The bias is added to the scaled sample of the displacement map.
  29229. * Without a displacement map set, this value is not applied.
  29230. *
  29231. * @type {number}
  29232. * @default 0
  29233. */
  29234. this.displacementBias = 0;
  29235. /**
  29236. * The alpha map is a grayscale texture that controls the opacity across the
  29237. * surface (black: fully transparent; white: fully opaque).
  29238. *
  29239. * Only the color of the texture is used, ignoring the alpha channel if one
  29240. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29241. * when sampling this texture due to the extra bit of precision provided for
  29242. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29243. * luminance/alpha textures will also still work as expected.
  29244. *
  29245. * @type {?Texture}
  29246. * @default null
  29247. */
  29248. this.alphaMap = null;
  29249. /**
  29250. * Whether the material is rendered with flat shading or not.
  29251. *
  29252. * @type {boolean}
  29253. * @default false
  29254. */
  29255. this.flatShading = false;
  29256. /**
  29257. * Whether the material is affected by fog or not.
  29258. *
  29259. * @type {boolean}
  29260. * @default true
  29261. */
  29262. this.fog = true;
  29263. this.setValues( parameters );
  29264. }
  29265. copy( source ) {
  29266. super.copy( source );
  29267. this.defines = { 'MATCAP': '' };
  29268. this.color.copy( source.color );
  29269. this.matcap = source.matcap;
  29270. this.map = source.map;
  29271. this.bumpMap = source.bumpMap;
  29272. this.bumpScale = source.bumpScale;
  29273. this.normalMap = source.normalMap;
  29274. this.normalMapType = source.normalMapType;
  29275. this.normalScale.copy( source.normalScale );
  29276. this.displacementMap = source.displacementMap;
  29277. this.displacementScale = source.displacementScale;
  29278. this.displacementBias = source.displacementBias;
  29279. this.alphaMap = source.alphaMap;
  29280. this.flatShading = source.flatShading;
  29281. this.fog = source.fog;
  29282. return this;
  29283. }
  29284. }
  29285. /**
  29286. * A material for rendering line primitives.
  29287. *
  29288. * Materials define the appearance of renderable 3D objects.
  29289. *
  29290. * ```js
  29291. * const material = new THREE.LineDashedMaterial( {
  29292. * color: 0xffffff,
  29293. * scale: 1,
  29294. * dashSize: 3,
  29295. * gapSize: 1,
  29296. * } );
  29297. * ```
  29298. *
  29299. * @augments LineBasicMaterial
  29300. */
  29301. class LineDashedMaterial extends LineBasicMaterial {
  29302. /**
  29303. * Constructs a new line dashed material.
  29304. *
  29305. * @param {Object} [parameters] - An object with one or more properties
  29306. * defining the material's appearance. Any property of the material
  29307. * (including any property from inherited materials) can be passed
  29308. * in here. Color values can be passed any type of value accepted
  29309. * by {@link Color#set}.
  29310. */
  29311. constructor( parameters ) {
  29312. super();
  29313. /**
  29314. * This flag can be used for type testing.
  29315. *
  29316. * @type {boolean}
  29317. * @readonly
  29318. * @default true
  29319. */
  29320. this.isLineDashedMaterial = true;
  29321. this.type = 'LineDashedMaterial';
  29322. /**
  29323. * The scale of the dashed part of a line.
  29324. *
  29325. * @type {number}
  29326. * @default 1
  29327. */
  29328. this.scale = 1;
  29329. /**
  29330. * The size of the dash. This is both the gap with the stroke.
  29331. *
  29332. * @type {number}
  29333. * @default 3
  29334. */
  29335. this.dashSize = 3;
  29336. /**
  29337. * The size of the gap.
  29338. *
  29339. * @type {number}
  29340. * @default 1
  29341. */
  29342. this.gapSize = 1;
  29343. this.setValues( parameters );
  29344. }
  29345. copy( source ) {
  29346. super.copy( source );
  29347. this.scale = source.scale;
  29348. this.dashSize = source.dashSize;
  29349. this.gapSize = source.gapSize;
  29350. return this;
  29351. }
  29352. }
  29353. /**
  29354. * Converts an array to a specific type.
  29355. *
  29356. * @param {TypedArray|Array} array - The array to convert.
  29357. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29358. * @return {TypedArray} The converted array.
  29359. */
  29360. function convertArray( array, type ) {
  29361. if ( ! array || array.constructor === type ) return array;
  29362. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29363. return new type( array ); // create typed array
  29364. }
  29365. return Array.prototype.slice.call( array ); // create Array
  29366. }
  29367. /**
  29368. * Returns `true` if the given object is a typed array.
  29369. *
  29370. * @param {any} object - The object to check.
  29371. * @return {boolean} Whether the given object is a typed array.
  29372. */
  29373. function isTypedArray( object ) {
  29374. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29375. }
  29376. /**
  29377. * Returns an array by which times and values can be sorted.
  29378. *
  29379. * @param {Array<number>} times - The keyframe time values.
  29380. * @return {Array<number>} The array.
  29381. */
  29382. function getKeyframeOrder( times ) {
  29383. function compareTime( i, j ) {
  29384. return times[ i ] - times[ j ];
  29385. }
  29386. const n = times.length;
  29387. const result = new Array( n );
  29388. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29389. result.sort( compareTime );
  29390. return result;
  29391. }
  29392. /**
  29393. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29394. *
  29395. * @param {Array<number>} values - The values to sort.
  29396. * @param {number} stride - The stride.
  29397. * @param {Array<number>} order - The sort order.
  29398. * @return {Array<number>} The sorted values.
  29399. */
  29400. function sortedArray( values, stride, order ) {
  29401. const nValues = values.length;
  29402. const result = new values.constructor( nValues );
  29403. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29404. const srcOffset = order[ i ] * stride;
  29405. for ( let j = 0; j !== stride; ++ j ) {
  29406. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29407. }
  29408. }
  29409. return result;
  29410. }
  29411. /**
  29412. * Used for parsing AOS keyframe formats.
  29413. *
  29414. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29415. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29416. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29417. * @param {string} valuePropertyName - The name of the property to use.
  29418. */
  29419. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29420. let i = 1, key = jsonKeys[ 0 ];
  29421. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29422. key = jsonKeys[ i ++ ];
  29423. }
  29424. if ( key === undefined ) return; // no data
  29425. let value = key[ valuePropertyName ];
  29426. if ( value === undefined ) return; // no data
  29427. if ( Array.isArray( value ) ) {
  29428. do {
  29429. value = key[ valuePropertyName ];
  29430. if ( value !== undefined ) {
  29431. times.push( key.time );
  29432. values.push( ...value ); // push all elements
  29433. }
  29434. key = jsonKeys[ i ++ ];
  29435. } while ( key !== undefined );
  29436. } else if ( value.toArray !== undefined ) {
  29437. // ...assume THREE.Math-ish
  29438. do {
  29439. value = key[ valuePropertyName ];
  29440. if ( value !== undefined ) {
  29441. times.push( key.time );
  29442. value.toArray( values, values.length );
  29443. }
  29444. key = jsonKeys[ i ++ ];
  29445. } while ( key !== undefined );
  29446. } else {
  29447. // otherwise push as-is
  29448. do {
  29449. value = key[ valuePropertyName ];
  29450. if ( value !== undefined ) {
  29451. times.push( key.time );
  29452. values.push( value );
  29453. }
  29454. key = jsonKeys[ i ++ ];
  29455. } while ( key !== undefined );
  29456. }
  29457. }
  29458. /**
  29459. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29460. *
  29461. * @param {AnimationClip} sourceClip - The values to sort.
  29462. * @param {string} name - The name of the clip.
  29463. * @param {number} startFrame - The start frame.
  29464. * @param {number} endFrame - The end frame.
  29465. * @param {number} [fps=30] - The FPS.
  29466. * @return {AnimationClip} The new sub clip.
  29467. */
  29468. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29469. const clip = sourceClip.clone();
  29470. clip.name = name;
  29471. const tracks = [];
  29472. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29473. const track = clip.tracks[ i ];
  29474. const valueSize = track.getValueSize();
  29475. const times = [];
  29476. const values = [];
  29477. for ( let j = 0; j < track.times.length; ++ j ) {
  29478. const frame = track.times[ j ] * fps;
  29479. if ( frame < startFrame || frame >= endFrame ) continue;
  29480. times.push( track.times[ j ] );
  29481. for ( let k = 0; k < valueSize; ++ k ) {
  29482. values.push( track.values[ j * valueSize + k ] );
  29483. }
  29484. }
  29485. if ( times.length === 0 ) continue;
  29486. track.times = convertArray( times, track.times.constructor );
  29487. track.values = convertArray( values, track.values.constructor );
  29488. tracks.push( track );
  29489. }
  29490. clip.tracks = tracks;
  29491. // find minimum .times value across all tracks in the trimmed clip
  29492. let minStartTime = Infinity;
  29493. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29494. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  29495. minStartTime = clip.tracks[ i ].times[ 0 ];
  29496. }
  29497. }
  29498. // shift all tracks such that clip begins at t=0
  29499. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29500. clip.tracks[ i ].shift( - 1 * minStartTime );
  29501. }
  29502. clip.resetDuration();
  29503. return clip;
  29504. }
  29505. /**
  29506. * Converts the keyframes of the given animation clip to an additive format.
  29507. *
  29508. * @param {AnimationClip} targetClip - The clip to make additive.
  29509. * @param {number} [referenceFrame=0] - The reference frame.
  29510. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29511. * @param {number} [fps=30] - The FPS.
  29512. * @return {AnimationClip} The updated clip which is now additive.
  29513. */
  29514. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29515. if ( fps <= 0 ) fps = 30;
  29516. const numTracks = referenceClip.tracks.length;
  29517. const referenceTime = referenceFrame / fps;
  29518. // Make each track's values relative to the values at the reference frame
  29519. for ( let i = 0; i < numTracks; ++ i ) {
  29520. const referenceTrack = referenceClip.tracks[ i ];
  29521. const referenceTrackType = referenceTrack.ValueTypeName;
  29522. // Skip this track if it's non-numeric
  29523. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  29524. // Find the track in the target clip whose name and type matches the reference track
  29525. const targetTrack = targetClip.tracks.find( function ( track ) {
  29526. return track.name === referenceTrack.name
  29527. && track.ValueTypeName === referenceTrackType;
  29528. } );
  29529. if ( targetTrack === undefined ) continue;
  29530. let referenceOffset = 0;
  29531. const referenceValueSize = referenceTrack.getValueSize();
  29532. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29533. referenceOffset = referenceValueSize / 3;
  29534. }
  29535. let targetOffset = 0;
  29536. const targetValueSize = targetTrack.getValueSize();
  29537. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29538. targetOffset = targetValueSize / 3;
  29539. }
  29540. const lastIndex = referenceTrack.times.length - 1;
  29541. let referenceValue;
  29542. // Find the value to subtract out of the track
  29543. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  29544. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  29545. const startIndex = referenceOffset;
  29546. const endIndex = referenceValueSize - referenceOffset;
  29547. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29548. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  29549. // Reference frame is after the last keyframe, so just use the last keyframe
  29550. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  29551. const endIndex = startIndex + referenceValueSize - referenceOffset;
  29552. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  29553. } else {
  29554. // Interpolate to the reference value
  29555. const interpolant = referenceTrack.createInterpolant();
  29556. const startIndex = referenceOffset;
  29557. const endIndex = referenceValueSize - referenceOffset;
  29558. interpolant.evaluate( referenceTime );
  29559. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  29560. }
  29561. // Conjugate the quaternion
  29562. if ( referenceTrackType === 'quaternion' ) {
  29563. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  29564. referenceQuat.toArray( referenceValue );
  29565. }
  29566. // Subtract the reference value from all of the track values
  29567. const numTimes = targetTrack.times.length;
  29568. for ( let j = 0; j < numTimes; ++ j ) {
  29569. const valueStart = j * targetValueSize + targetOffset;
  29570. if ( referenceTrackType === 'quaternion' ) {
  29571. // Multiply the conjugate for quaternion track types
  29572. Quaternion.multiplyQuaternionsFlat(
  29573. targetTrack.values,
  29574. valueStart,
  29575. referenceValue,
  29576. 0,
  29577. targetTrack.values,
  29578. valueStart
  29579. );
  29580. } else {
  29581. const valueEnd = targetValueSize - targetOffset * 2;
  29582. // Subtract each value for all other numeric track types
  29583. for ( let k = 0; k < valueEnd; ++ k ) {
  29584. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  29585. }
  29586. }
  29587. }
  29588. }
  29589. targetClip.blendMode = AdditiveAnimationBlendMode;
  29590. return targetClip;
  29591. }
  29592. /**
  29593. * A class with various methods to assist with animations.
  29594. *
  29595. * @hideconstructor
  29596. */
  29597. class AnimationUtils {
  29598. /**
  29599. * Converts an array to a specific type
  29600. *
  29601. * @static
  29602. * @param {TypedArray|Array} array - The array to convert.
  29603. * @param {TypedArray.constructor} type - The constructor of a type array.
  29604. * @return {TypedArray} The converted array
  29605. */
  29606. static convertArray( array, type ) {
  29607. return convertArray( array, type );
  29608. }
  29609. /**
  29610. * Returns `true` if the given object is a typed array.
  29611. *
  29612. * @static
  29613. * @param {any} object - The object to check.
  29614. * @return {boolean} Whether the given object is a typed array.
  29615. */
  29616. static isTypedArray( object ) {
  29617. return isTypedArray( object );
  29618. }
  29619. /**
  29620. * Returns an array by which times and values can be sorted.
  29621. *
  29622. * @static
  29623. * @param {Array<number>} times - The keyframe time values.
  29624. * @return {Array<number>} The array.
  29625. */
  29626. static getKeyframeOrder( times ) {
  29627. return getKeyframeOrder( times );
  29628. }
  29629. /**
  29630. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29631. *
  29632. * @static
  29633. * @param {Array<number>} values - The values to sort.
  29634. * @param {number} stride - The stride.
  29635. * @param {Array<number>} order - The sort order.
  29636. * @return {Array<number>} The sorted values.
  29637. */
  29638. static sortedArray( values, stride, order ) {
  29639. return sortedArray( values, stride, order );
  29640. }
  29641. /**
  29642. * Used for parsing AOS keyframe formats.
  29643. *
  29644. * @static
  29645. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29646. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  29647. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  29648. * @param {string} valuePropertyName - The name of the property to use.
  29649. */
  29650. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29651. flattenJSON( jsonKeys, times, values, valuePropertyName );
  29652. }
  29653. /**
  29654. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29655. *
  29656. * @static
  29657. * @param {AnimationClip} sourceClip - The values to sort.
  29658. * @param {string} name - The name of the clip.
  29659. * @param {number} startFrame - The start frame.
  29660. * @param {number} endFrame - The end frame.
  29661. * @param {number} [fps=30] - The FPS.
  29662. * @return {AnimationClip} The new sub clip.
  29663. */
  29664. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29665. return subclip( sourceClip, name, startFrame, endFrame, fps );
  29666. }
  29667. /**
  29668. * Converts the keyframes of the given animation clip to an additive format.
  29669. *
  29670. * @static
  29671. * @param {AnimationClip} targetClip - The clip to make additive.
  29672. * @param {number} [referenceFrame=0] - The reference frame.
  29673. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29674. * @param {number} [fps=30] - The FPS.
  29675. * @return {AnimationClip} The updated clip which is now additive.
  29676. */
  29677. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29678. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  29679. }
  29680. }
  29681. /**
  29682. * Abstract base class of interpolants over parametric samples.
  29683. *
  29684. * The parameter domain is one dimensional, typically the time or a path
  29685. * along a curve defined by the data.
  29686. *
  29687. * The sample values can have any dimensionality and derived classes may
  29688. * apply special interpretations to the data.
  29689. *
  29690. * This class provides the interval seek in a Template Method, deferring
  29691. * the actual interpolation to derived classes.
  29692. *
  29693. * Time complexity is O(1) for linear access crossing at most two points
  29694. * and O(log N) for random access, where N is the number of positions.
  29695. *
  29696. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  29697. *
  29698. * @abstract
  29699. */
  29700. class Interpolant {
  29701. /**
  29702. * Constructs a new interpolant.
  29703. *
  29704. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  29705. * @param {TypedArray} sampleValues - The sample values.
  29706. * @param {number} sampleSize - The sample size
  29707. * @param {TypedArray} [resultBuffer] - The result buffer.
  29708. */
  29709. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  29710. /**
  29711. * The parameter positions.
  29712. *
  29713. * @type {TypedArray}
  29714. */
  29715. this.parameterPositions = parameterPositions;
  29716. /**
  29717. * A cache index.
  29718. *
  29719. * @private
  29720. * @type {number}
  29721. * @default 0
  29722. */
  29723. this._cachedIndex = 0;
  29724. /**
  29725. * The result buffer.
  29726. *
  29727. * @type {TypedArray}
  29728. */
  29729. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  29730. /**
  29731. * The sample values.
  29732. *
  29733. * @type {TypedArray}
  29734. */
  29735. this.sampleValues = sampleValues;
  29736. /**
  29737. * The value size.
  29738. *
  29739. * @type {TypedArray}
  29740. */
  29741. this.valueSize = sampleSize;
  29742. /**
  29743. * The interpolation settings.
  29744. *
  29745. * @type {?Object}
  29746. * @default null
  29747. */
  29748. this.settings = null;
  29749. /**
  29750. * The default settings object.
  29751. *
  29752. * @type {Object}
  29753. */
  29754. this.DefaultSettings_ = {};
  29755. }
  29756. /**
  29757. * Evaluate the interpolant at position `t`.
  29758. *
  29759. * @param {number} t - The interpolation factor.
  29760. * @return {TypedArray} The result buffer.
  29761. */
  29762. evaluate( t ) {
  29763. const pp = this.parameterPositions;
  29764. let i1 = this._cachedIndex,
  29765. t1 = pp[ i1 ],
  29766. t0 = pp[ i1 - 1 ];
  29767. validate_interval: {
  29768. seek: {
  29769. let right;
  29770. linear_scan: {
  29771. //- See http://jsperf.com/comparison-to-undefined/3
  29772. //- slower code:
  29773. //-
  29774. //- if ( t >= t1 || t1 === undefined ) {
  29775. forward_scan: if ( ! ( t < t1 ) ) {
  29776. for ( let giveUpAt = i1 + 2; ; ) {
  29777. if ( t1 === undefined ) {
  29778. if ( t < t0 ) break forward_scan;
  29779. // after end
  29780. i1 = pp.length;
  29781. this._cachedIndex = i1;
  29782. return this.copySampleValue_( i1 - 1 );
  29783. }
  29784. if ( i1 === giveUpAt ) break; // this loop
  29785. t0 = t1;
  29786. t1 = pp[ ++ i1 ];
  29787. if ( t < t1 ) {
  29788. // we have arrived at the sought interval
  29789. break seek;
  29790. }
  29791. }
  29792. // prepare binary search on the right side of the index
  29793. right = pp.length;
  29794. break linear_scan;
  29795. }
  29796. //- slower code:
  29797. //- if ( t < t0 || t0 === undefined ) {
  29798. if ( ! ( t >= t0 ) ) {
  29799. // looping?
  29800. const t1global = pp[ 1 ];
  29801. if ( t < t1global ) {
  29802. i1 = 2; // + 1, using the scan for the details
  29803. t0 = t1global;
  29804. }
  29805. // linear reverse scan
  29806. for ( let giveUpAt = i1 - 2; ; ) {
  29807. if ( t0 === undefined ) {
  29808. // before start
  29809. this._cachedIndex = 0;
  29810. return this.copySampleValue_( 0 );
  29811. }
  29812. if ( i1 === giveUpAt ) break; // this loop
  29813. t1 = t0;
  29814. t0 = pp[ -- i1 - 1 ];
  29815. if ( t >= t0 ) {
  29816. // we have arrived at the sought interval
  29817. break seek;
  29818. }
  29819. }
  29820. // prepare binary search on the left side of the index
  29821. right = i1;
  29822. i1 = 0;
  29823. break linear_scan;
  29824. }
  29825. // the interval is valid
  29826. break validate_interval;
  29827. } // linear scan
  29828. // binary search
  29829. while ( i1 < right ) {
  29830. const mid = ( i1 + right ) >>> 1;
  29831. if ( t < pp[ mid ] ) {
  29832. right = mid;
  29833. } else {
  29834. i1 = mid + 1;
  29835. }
  29836. }
  29837. t1 = pp[ i1 ];
  29838. t0 = pp[ i1 - 1 ];
  29839. // check boundary cases, again
  29840. if ( t0 === undefined ) {
  29841. this._cachedIndex = 0;
  29842. return this.copySampleValue_( 0 );
  29843. }
  29844. if ( t1 === undefined ) {
  29845. i1 = pp.length;
  29846. this._cachedIndex = i1;
  29847. return this.copySampleValue_( i1 - 1 );
  29848. }
  29849. } // seek
  29850. this._cachedIndex = i1;
  29851. this.intervalChanged_( i1, t0, t1 );
  29852. } // validate_interval
  29853. return this.interpolate_( i1, t0, t, t1 );
  29854. }
  29855. /**
  29856. * Returns the interpolation settings.
  29857. *
  29858. * @return {Object} The interpolation settings.
  29859. */
  29860. getSettings_() {
  29861. return this.settings || this.DefaultSettings_;
  29862. }
  29863. /**
  29864. * Copies a sample value to the result buffer.
  29865. *
  29866. * @param {number} index - An index into the sample value buffer.
  29867. * @return {TypedArray} The result buffer.
  29868. */
  29869. copySampleValue_( index ) {
  29870. // copies a sample value to the result buffer
  29871. const result = this.resultBuffer,
  29872. values = this.sampleValues,
  29873. stride = this.valueSize,
  29874. offset = index * stride;
  29875. for ( let i = 0; i !== stride; ++ i ) {
  29876. result[ i ] = values[ offset + i ];
  29877. }
  29878. return result;
  29879. }
  29880. /**
  29881. * Copies a sample value to the result buffer.
  29882. *
  29883. * @abstract
  29884. * @param {number} i1 - An index into the sample value buffer.
  29885. * @param {number} t0 - The previous interpolation factor.
  29886. * @param {number} t - The current interpolation factor.
  29887. * @param {number} t1 - The next interpolation factor.
  29888. * @return {TypedArray} The result buffer.
  29889. */
  29890. interpolate_( /* i1, t0, t, t1 */ ) {
  29891. throw new Error( 'call to abstract method' );
  29892. // implementations shall return this.resultBuffer
  29893. }
  29894. /**
  29895. * Optional method that is executed when the interval has changed.
  29896. *
  29897. * @param {number} i1 - An index into the sample value buffer.
  29898. * @param {number} t0 - The previous interpolation factor.
  29899. * @param {number} t - The current interpolation factor.
  29900. */
  29901. intervalChanged_( /* i1, t0, t1 */ ) {
  29902. // empty
  29903. }
  29904. }
  29905. /**
  29906. * Fast and simple cubic spline interpolant.
  29907. *
  29908. * It was derived from a Hermitian construction setting the first derivative
  29909. * at each sample position to the linear slope between neighboring positions
  29910. * over their parameter interval.
  29911. *
  29912. * @augments Interpolant
  29913. */
  29914. class CubicInterpolant extends Interpolant {
  29915. /**
  29916. * Constructs a new cubic interpolant.
  29917. *
  29918. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  29919. * @param {TypedArray} sampleValues - The sample values.
  29920. * @param {number} sampleSize - The sample size
  29921. * @param {TypedArray} [resultBuffer] - The result buffer.
  29922. */
  29923. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  29924. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  29925. this._weightPrev = - 0;
  29926. this._offsetPrev = - 0;
  29927. this._weightNext = - 0;
  29928. this._offsetNext = - 0;
  29929. this.DefaultSettings_ = {
  29930. endingStart: ZeroCurvatureEnding,
  29931. endingEnd: ZeroCurvatureEnding
  29932. };
  29933. }
  29934. intervalChanged_( i1, t0, t1 ) {
  29935. const pp = this.parameterPositions;
  29936. let iPrev = i1 - 2,
  29937. iNext = i1 + 1,
  29938. tPrev = pp[ iPrev ],
  29939. tNext = pp[ iNext ];
  29940. if ( tPrev === undefined ) {
  29941. switch ( this.getSettings_().endingStart ) {
  29942. case ZeroSlopeEnding:
  29943. // f'(t0) = 0
  29944. iPrev = i1;
  29945. tPrev = 2 * t0 - t1;
  29946. break;
  29947. case WrapAroundEnding:
  29948. // use the other end of the curve
  29949. iPrev = pp.length - 2;
  29950. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  29951. break;
  29952. default: // ZeroCurvatureEnding
  29953. // f''(t0) = 0 a.k.a. Natural Spline
  29954. iPrev = i1;
  29955. tPrev = t1;
  29956. }
  29957. }
  29958. if ( tNext === undefined ) {
  29959. switch ( this.getSettings_().endingEnd ) {
  29960. case ZeroSlopeEnding:
  29961. // f'(tN) = 0
  29962. iNext = i1;
  29963. tNext = 2 * t1 - t0;
  29964. break;
  29965. case WrapAroundEnding:
  29966. // use the other end of the curve
  29967. iNext = 1;
  29968. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  29969. break;
  29970. default: // ZeroCurvatureEnding
  29971. // f''(tN) = 0, a.k.a. Natural Spline
  29972. iNext = i1 - 1;
  29973. tNext = t0;
  29974. }
  29975. }
  29976. const halfDt = ( t1 - t0 ) * 0.5,
  29977. stride = this.valueSize;
  29978. this._weightPrev = halfDt / ( t0 - tPrev );
  29979. this._weightNext = halfDt / ( tNext - t1 );
  29980. this._offsetPrev = iPrev * stride;
  29981. this._offsetNext = iNext * stride;
  29982. }
  29983. interpolate_( i1, t0, t, t1 ) {
  29984. const result = this.resultBuffer,
  29985. values = this.sampleValues,
  29986. stride = this.valueSize,
  29987. o1 = i1 * stride, o0 = o1 - stride,
  29988. oP = this._offsetPrev, oN = this._offsetNext,
  29989. wP = this._weightPrev, wN = this._weightNext,
  29990. p = ( t - t0 ) / ( t1 - t0 ),
  29991. pp = p * p,
  29992. ppp = pp * p;
  29993. // evaluate polynomials
  29994. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  29995. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  29996. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  29997. const sN = wN * ppp - wN * pp;
  29998. // combine data linearly
  29999. for ( let i = 0; i !== stride; ++ i ) {
  30000. result[ i ] =
  30001. sP * values[ oP + i ] +
  30002. s0 * values[ o0 + i ] +
  30003. s1 * values[ o1 + i ] +
  30004. sN * values[ oN + i ];
  30005. }
  30006. return result;
  30007. }
  30008. }
  30009. /**
  30010. * A basic linear interpolant.
  30011. *
  30012. * @augments Interpolant
  30013. */
  30014. class LinearInterpolant extends Interpolant {
  30015. /**
  30016. * Constructs a new linear interpolant.
  30017. *
  30018. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30019. * @param {TypedArray} sampleValues - The sample values.
  30020. * @param {number} sampleSize - The sample size
  30021. * @param {TypedArray} [resultBuffer] - The result buffer.
  30022. */
  30023. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30024. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30025. }
  30026. interpolate_( i1, t0, t, t1 ) {
  30027. const result = this.resultBuffer,
  30028. values = this.sampleValues,
  30029. stride = this.valueSize,
  30030. offset1 = i1 * stride,
  30031. offset0 = offset1 - stride,
  30032. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30033. weight0 = 1 - weight1;
  30034. for ( let i = 0; i !== stride; ++ i ) {
  30035. result[ i ] =
  30036. values[ offset0 + i ] * weight0 +
  30037. values[ offset1 + i ] * weight1;
  30038. }
  30039. return result;
  30040. }
  30041. }
  30042. /**
  30043. * Interpolant that evaluates to the sample value at the position preceding
  30044. * the parameter.
  30045. *
  30046. * @augments Interpolant
  30047. */
  30048. class DiscreteInterpolant extends Interpolant {
  30049. /**
  30050. * Constructs a new discrete interpolant.
  30051. *
  30052. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30053. * @param {TypedArray} sampleValues - The sample values.
  30054. * @param {number} sampleSize - The sample size
  30055. * @param {TypedArray} [resultBuffer] - The result buffer.
  30056. */
  30057. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30058. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30059. }
  30060. interpolate_( i1 /*, t0, t, t1 */ ) {
  30061. return this.copySampleValue_( i1 - 1 );
  30062. }
  30063. }
  30064. /**
  30065. * Represents s a timed sequence of keyframes, which are composed of lists of
  30066. * times and related values, and which are used to animate a specific property
  30067. * of an object.
  30068. */
  30069. class KeyframeTrack {
  30070. /**
  30071. * Constructs a new keyframe track.
  30072. *
  30073. * @param {string} name - The keyframe track's name.
  30074. * @param {Array<number>} times - A list of keyframe times.
  30075. * @param {Array<number>} values - A list of keyframe values.
  30076. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30077. */
  30078. constructor( name, times, values, interpolation ) {
  30079. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30080. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30081. /**
  30082. * The track's name can refer to morph targets or bones or
  30083. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30084. * for the forms of strings that can be parsed for property binding.
  30085. *
  30086. * @type {string}
  30087. */
  30088. this.name = name;
  30089. /**
  30090. * The keyframe times.
  30091. *
  30092. * @type {Float32Array}
  30093. */
  30094. this.times = convertArray( times, this.TimeBufferType );
  30095. /**
  30096. * The keyframe values.
  30097. *
  30098. * @type {Float32Array}
  30099. */
  30100. this.values = convertArray( values, this.ValueBufferType );
  30101. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30102. }
  30103. /**
  30104. * Converts the keyframe track to JSON.
  30105. *
  30106. * @static
  30107. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30108. * @return {Object} The serialized keyframe track as JSON.
  30109. */
  30110. static toJSON( track ) {
  30111. const trackType = track.constructor;
  30112. let json;
  30113. // derived classes can define a static toJSON method
  30114. if ( trackType.toJSON !== this.toJSON ) {
  30115. json = trackType.toJSON( track );
  30116. } else {
  30117. // by default, we assume the data can be serialized as-is
  30118. json = {
  30119. 'name': track.name,
  30120. 'times': convertArray( track.times, Array ),
  30121. 'values': convertArray( track.values, Array )
  30122. };
  30123. const interpolation = track.getInterpolation();
  30124. if ( interpolation !== track.DefaultInterpolation ) {
  30125. json.interpolation = interpolation;
  30126. }
  30127. }
  30128. json.type = track.ValueTypeName; // mandatory
  30129. return json;
  30130. }
  30131. /**
  30132. * Factory method for creating a new discrete interpolant.
  30133. *
  30134. * @static
  30135. * @param {TypedArray} [result] - The result buffer.
  30136. * @return {DiscreteInterpolant} The new interpolant.
  30137. */
  30138. InterpolantFactoryMethodDiscrete( result ) {
  30139. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30140. }
  30141. /**
  30142. * Factory method for creating a new linear interpolant.
  30143. *
  30144. * @static
  30145. * @param {TypedArray} [result] - The result buffer.
  30146. * @return {LinearInterpolant} The new interpolant.
  30147. */
  30148. InterpolantFactoryMethodLinear( result ) {
  30149. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30150. }
  30151. /**
  30152. * Factory method for creating a new smooth interpolant.
  30153. *
  30154. * @static
  30155. * @param {TypedArray} [result] - The result buffer.
  30156. * @return {CubicInterpolant} The new interpolant.
  30157. */
  30158. InterpolantFactoryMethodSmooth( result ) {
  30159. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30160. }
  30161. /**
  30162. * Defines the interpolation factor method for this keyframe track.
  30163. *
  30164. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30165. * @return {KeyframeTrack} A reference to this keyframe track.
  30166. */
  30167. setInterpolation( interpolation ) {
  30168. let factoryMethod;
  30169. switch ( interpolation ) {
  30170. case InterpolateDiscrete:
  30171. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30172. break;
  30173. case InterpolateLinear:
  30174. factoryMethod = this.InterpolantFactoryMethodLinear;
  30175. break;
  30176. case InterpolateSmooth:
  30177. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30178. break;
  30179. }
  30180. if ( factoryMethod === undefined ) {
  30181. const message = 'unsupported interpolation for ' +
  30182. this.ValueTypeName + ' keyframe track named ' + this.name;
  30183. if ( this.createInterpolant === undefined ) {
  30184. // fall back to default, unless the default itself is messed up
  30185. if ( interpolation !== this.DefaultInterpolation ) {
  30186. this.setInterpolation( this.DefaultInterpolation );
  30187. } else {
  30188. throw new Error( message ); // fatal, in this case
  30189. }
  30190. }
  30191. console.warn( 'THREE.KeyframeTrack:', message );
  30192. return this;
  30193. }
  30194. this.createInterpolant = factoryMethod;
  30195. return this;
  30196. }
  30197. /**
  30198. * Returns the current interpolation type.
  30199. *
  30200. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30201. */
  30202. getInterpolation() {
  30203. switch ( this.createInterpolant ) {
  30204. case this.InterpolantFactoryMethodDiscrete:
  30205. return InterpolateDiscrete;
  30206. case this.InterpolantFactoryMethodLinear:
  30207. return InterpolateLinear;
  30208. case this.InterpolantFactoryMethodSmooth:
  30209. return InterpolateSmooth;
  30210. }
  30211. }
  30212. /**
  30213. * Returns the value size.
  30214. *
  30215. * @return {number} The value size.
  30216. */
  30217. getValueSize() {
  30218. return this.values.length / this.times.length;
  30219. }
  30220. /**
  30221. * Moves all keyframes either forward or backward in time.
  30222. *
  30223. * @param {number} timeOffset - The offset to move the time values.
  30224. * @return {KeyframeTrack} A reference to this keyframe track.
  30225. */
  30226. shift( timeOffset ) {
  30227. if ( timeOffset !== 0.0 ) {
  30228. const times = this.times;
  30229. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30230. times[ i ] += timeOffset;
  30231. }
  30232. }
  30233. return this;
  30234. }
  30235. /**
  30236. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30237. *
  30238. * @param {number} timeScale - The time scale.
  30239. * @return {KeyframeTrack} A reference to this keyframe track.
  30240. */
  30241. scale( timeScale ) {
  30242. if ( timeScale !== 1.0 ) {
  30243. const times = this.times;
  30244. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30245. times[ i ] *= timeScale;
  30246. }
  30247. }
  30248. return this;
  30249. }
  30250. /**
  30251. * Removes keyframes before and after animation without changing any values within the defined time range.
  30252. *
  30253. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30254. * keys this will change their values
  30255. *
  30256. * @param {number} startTime - The start time.
  30257. * @param {number} endTime - The end time.
  30258. * @return {KeyframeTrack} A reference to this keyframe track.
  30259. */
  30260. trim( startTime, endTime ) {
  30261. const times = this.times,
  30262. nKeys = times.length;
  30263. let from = 0,
  30264. to = nKeys - 1;
  30265. while ( from !== nKeys && times[ from ] < startTime ) {
  30266. ++ from;
  30267. }
  30268. while ( to !== - 1 && times[ to ] > endTime ) {
  30269. -- to;
  30270. }
  30271. ++ to; // inclusive -> exclusive bound
  30272. if ( from !== 0 || to !== nKeys ) {
  30273. // empty tracks are forbidden, so keep at least one keyframe
  30274. if ( from >= to ) {
  30275. to = Math.max( to, 1 );
  30276. from = to - 1;
  30277. }
  30278. const stride = this.getValueSize();
  30279. this.times = times.slice( from, to );
  30280. this.values = this.values.slice( from * stride, to * stride );
  30281. }
  30282. return this;
  30283. }
  30284. /**
  30285. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30286. * are valid.
  30287. *
  30288. * @return {boolean} Whether the keyframes are valid or not.
  30289. */
  30290. validate() {
  30291. let valid = true;
  30292. const valueSize = this.getValueSize();
  30293. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30294. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30295. valid = false;
  30296. }
  30297. const times = this.times,
  30298. values = this.values,
  30299. nKeys = times.length;
  30300. if ( nKeys === 0 ) {
  30301. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30302. valid = false;
  30303. }
  30304. let prevTime = null;
  30305. for ( let i = 0; i !== nKeys; i ++ ) {
  30306. const currTime = times[ i ];
  30307. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30308. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30309. valid = false;
  30310. break;
  30311. }
  30312. if ( prevTime !== null && prevTime > currTime ) {
  30313. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30314. valid = false;
  30315. break;
  30316. }
  30317. prevTime = currTime;
  30318. }
  30319. if ( values !== undefined ) {
  30320. if ( isTypedArray( values ) ) {
  30321. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30322. const value = values[ i ];
  30323. if ( isNaN( value ) ) {
  30324. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30325. valid = false;
  30326. break;
  30327. }
  30328. }
  30329. }
  30330. }
  30331. return valid;
  30332. }
  30333. /**
  30334. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30335. * common in morph target sequences).
  30336. *
  30337. * @return {AnimationClip} A reference to this animation clip.
  30338. */
  30339. optimize() {
  30340. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30341. // times or values may be shared with other tracks, so overwriting is unsafe
  30342. const times = this.times.slice(),
  30343. values = this.values.slice(),
  30344. stride = this.getValueSize(),
  30345. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30346. lastIndex = times.length - 1;
  30347. let writeIndex = 1;
  30348. for ( let i = 1; i < lastIndex; ++ i ) {
  30349. let keep = false;
  30350. const time = times[ i ];
  30351. const timeNext = times[ i + 1 ];
  30352. // remove adjacent keyframes scheduled at the same time
  30353. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30354. if ( ! smoothInterpolation ) {
  30355. // remove unnecessary keyframes same as their neighbors
  30356. const offset = i * stride,
  30357. offsetP = offset - stride,
  30358. offsetN = offset + stride;
  30359. for ( let j = 0; j !== stride; ++ j ) {
  30360. const value = values[ offset + j ];
  30361. if ( value !== values[ offsetP + j ] ||
  30362. value !== values[ offsetN + j ] ) {
  30363. keep = true;
  30364. break;
  30365. }
  30366. }
  30367. } else {
  30368. keep = true;
  30369. }
  30370. }
  30371. // in-place compaction
  30372. if ( keep ) {
  30373. if ( i !== writeIndex ) {
  30374. times[ writeIndex ] = times[ i ];
  30375. const readOffset = i * stride,
  30376. writeOffset = writeIndex * stride;
  30377. for ( let j = 0; j !== stride; ++ j ) {
  30378. values[ writeOffset + j ] = values[ readOffset + j ];
  30379. }
  30380. }
  30381. ++ writeIndex;
  30382. }
  30383. }
  30384. // flush last keyframe (compaction looks ahead)
  30385. if ( lastIndex > 0 ) {
  30386. times[ writeIndex ] = times[ lastIndex ];
  30387. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30388. values[ writeOffset + j ] = values[ readOffset + j ];
  30389. }
  30390. ++ writeIndex;
  30391. }
  30392. if ( writeIndex !== times.length ) {
  30393. this.times = times.slice( 0, writeIndex );
  30394. this.values = values.slice( 0, writeIndex * stride );
  30395. } else {
  30396. this.times = times;
  30397. this.values = values;
  30398. }
  30399. return this;
  30400. }
  30401. /**
  30402. * Returns a new keyframe track with copied values from this instance.
  30403. *
  30404. * @return {KeyframeTrack} A clone of this instance.
  30405. */
  30406. clone() {
  30407. const times = this.times.slice();
  30408. const values = this.values.slice();
  30409. const TypedKeyframeTrack = this.constructor;
  30410. const track = new TypedKeyframeTrack( this.name, times, values );
  30411. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30412. track.createInterpolant = this.createInterpolant;
  30413. return track;
  30414. }
  30415. }
  30416. /**
  30417. * The value type name.
  30418. *
  30419. * @type {String}
  30420. * @default ''
  30421. */
  30422. KeyframeTrack.prototype.ValueTypeName = '';
  30423. /**
  30424. * The time buffer type of this keyframe track.
  30425. *
  30426. * @type {TypedArray|Array}
  30427. * @default Float32Array.constructor
  30428. */
  30429. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30430. /**
  30431. * The value buffer type of this keyframe track.
  30432. *
  30433. * @type {TypedArray|Array}
  30434. * @default Float32Array.constructor
  30435. */
  30436. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30437. /**
  30438. * The default interpolation type of this keyframe track.
  30439. *
  30440. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30441. * @default InterpolateLinear
  30442. */
  30443. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30444. /**
  30445. * A track for boolean keyframe values.
  30446. *
  30447. * @augments KeyframeTrack
  30448. */
  30449. class BooleanKeyframeTrack extends KeyframeTrack {
  30450. /**
  30451. * Constructs a new boolean keyframe track.
  30452. *
  30453. * This keyframe track type has no `interpolation` parameter because the
  30454. * interpolation is always discrete.
  30455. *
  30456. * @param {string} name - The keyframe track's name.
  30457. * @param {Array<number>} times - A list of keyframe times.
  30458. * @param {Array<number>} values - A list of keyframe values.
  30459. */
  30460. constructor( name, times, values ) {
  30461. super( name, times, values );
  30462. }
  30463. }
  30464. /**
  30465. * The value type name.
  30466. *
  30467. * @type {String}
  30468. * @default 'bool'
  30469. */
  30470. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  30471. /**
  30472. * The value buffer type of this keyframe track.
  30473. *
  30474. * @type {TypedArray|Array}
  30475. * @default Array.constructor
  30476. */
  30477. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  30478. /**
  30479. * The default interpolation type of this keyframe track.
  30480. *
  30481. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30482. * @default InterpolateDiscrete
  30483. */
  30484. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  30485. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  30486. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30487. /**
  30488. * A track for color keyframe values.
  30489. *
  30490. * @augments KeyframeTrack
  30491. */
  30492. class ColorKeyframeTrack extends KeyframeTrack {
  30493. /**
  30494. * Constructs a new color keyframe track.
  30495. *
  30496. * @param {string} name - The keyframe track's name.
  30497. * @param {Array<number>} times - A list of keyframe times.
  30498. * @param {Array<number>} values - A list of keyframe values.
  30499. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30500. */
  30501. constructor( name, times, values, interpolation ) {
  30502. super( name, times, values, interpolation );
  30503. }
  30504. }
  30505. /**
  30506. * The value type name.
  30507. *
  30508. * @type {String}
  30509. * @default 'color'
  30510. */
  30511. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  30512. /**
  30513. * A track for numeric keyframe values.
  30514. *
  30515. * @augments KeyframeTrack
  30516. */
  30517. class NumberKeyframeTrack extends KeyframeTrack {
  30518. /**
  30519. * Constructs a new number keyframe track.
  30520. *
  30521. * @param {string} name - The keyframe track's name.
  30522. * @param {Array<number>} times - A list of keyframe times.
  30523. * @param {Array<number>} values - A list of keyframe values.
  30524. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30525. */
  30526. constructor( name, times, values, interpolation ) {
  30527. super( name, times, values, interpolation );
  30528. }
  30529. }
  30530. /**
  30531. * The value type name.
  30532. *
  30533. * @type {String}
  30534. * @default 'number'
  30535. */
  30536. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  30537. /**
  30538. * Spherical linear unit quaternion interpolant.
  30539. *
  30540. * @augments Interpolant
  30541. */
  30542. class QuaternionLinearInterpolant extends Interpolant {
  30543. /**
  30544. * Constructs a new SLERP interpolant.
  30545. *
  30546. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30547. * @param {TypedArray} sampleValues - The sample values.
  30548. * @param {number} sampleSize - The sample size
  30549. * @param {TypedArray} [resultBuffer] - The result buffer.
  30550. */
  30551. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30552. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30553. }
  30554. interpolate_( i1, t0, t, t1 ) {
  30555. const result = this.resultBuffer,
  30556. values = this.sampleValues,
  30557. stride = this.valueSize,
  30558. alpha = ( t - t0 ) / ( t1 - t0 );
  30559. let offset = i1 * stride;
  30560. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  30561. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  30562. }
  30563. return result;
  30564. }
  30565. }
  30566. /**
  30567. * A track for Quaternion keyframe values.
  30568. *
  30569. * @augments KeyframeTrack
  30570. */
  30571. class QuaternionKeyframeTrack extends KeyframeTrack {
  30572. /**
  30573. * Constructs a new Quaternion keyframe track.
  30574. *
  30575. * @param {string} name - The keyframe track's name.
  30576. * @param {Array<number>} times - A list of keyframe times.
  30577. * @param {Array<number>} values - A list of keyframe values.
  30578. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30579. */
  30580. constructor( name, times, values, interpolation ) {
  30581. super( name, times, values, interpolation );
  30582. }
  30583. /**
  30584. * Overwritten so the method returns Quaternion based interpolant.
  30585. *
  30586. * @static
  30587. * @param {TypedArray} [result] - The result buffer.
  30588. * @return {QuaternionLinearInterpolant} The new interpolant.
  30589. */
  30590. InterpolantFactoryMethodLinear( result ) {
  30591. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30592. }
  30593. }
  30594. /**
  30595. * The value type name.
  30596. *
  30597. * @type {String}
  30598. * @default 'quaternion'
  30599. */
  30600. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  30601. // ValueBufferType is inherited
  30602. // DefaultInterpolation is inherited;
  30603. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30604. /**
  30605. * A track for string keyframe values.
  30606. *
  30607. * @augments KeyframeTrack
  30608. */
  30609. class StringKeyframeTrack extends KeyframeTrack {
  30610. /**
  30611. * Constructs a new string keyframe track.
  30612. *
  30613. * This keyframe track type has no `interpolation` parameter because the
  30614. * interpolation is always discrete.
  30615. *
  30616. * @param {string} name - The keyframe track's name.
  30617. * @param {Array<number>} times - A list of keyframe times.
  30618. * @param {Array<number>} values - A list of keyframe values.
  30619. */
  30620. constructor( name, times, values ) {
  30621. super( name, times, values );
  30622. }
  30623. }
  30624. /**
  30625. * The value type name.
  30626. *
  30627. * @type {String}
  30628. * @default 'string'
  30629. */
  30630. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  30631. /**
  30632. * The value buffer type of this keyframe track.
  30633. *
  30634. * @type {TypedArray|Array}
  30635. * @default Array.constructor
  30636. */
  30637. StringKeyframeTrack.prototype.ValueBufferType = Array;
  30638. /**
  30639. * The default interpolation type of this keyframe track.
  30640. *
  30641. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30642. * @default InterpolateDiscrete
  30643. */
  30644. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  30645. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  30646. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  30647. /**
  30648. * A track for vector keyframe values.
  30649. *
  30650. * @augments KeyframeTrack
  30651. */
  30652. class VectorKeyframeTrack extends KeyframeTrack {
  30653. /**
  30654. * Constructs a new vector keyframe track.
  30655. *
  30656. * @param {string} name - The keyframe track's name.
  30657. * @param {Array<number>} times - A list of keyframe times.
  30658. * @param {Array<number>} values - A list of keyframe values.
  30659. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30660. */
  30661. constructor( name, times, values, interpolation ) {
  30662. super( name, times, values, interpolation );
  30663. }
  30664. }
  30665. /**
  30666. * The value type name.
  30667. *
  30668. * @type {String}
  30669. * @default 'vector'
  30670. */
  30671. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  30672. /**
  30673. * A reusable set of keyframe tracks which represent an animation.
  30674. */
  30675. class AnimationClip {
  30676. /**
  30677. * Constructs a new animation clip.
  30678. *
  30679. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  30680. * use the static interface of this class for creating clips. In most cases though, animation clips
  30681. * will automatically be created by loaders when importing animated 3D assets.
  30682. *
  30683. * @param {string} [name=''] - The clip's name.
  30684. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  30685. * the duration will be calculated from the passed keyframes.
  30686. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  30687. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  30688. * is blended/combined when two or more animations are simultaneously played.
  30689. */
  30690. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  30691. /**
  30692. * The clip's name.
  30693. *
  30694. * @type {string}
  30695. */
  30696. this.name = name;
  30697. /**
  30698. * An array of keyframe tracks.
  30699. *
  30700. * @type {Array<KeyframeTrack>}
  30701. */
  30702. this.tracks = tracks;
  30703. /**
  30704. * The clip's duration in seconds.
  30705. *
  30706. * @type {number}
  30707. */
  30708. this.duration = duration;
  30709. /**
  30710. * Defines how the animation is blended/combined when two or more animations
  30711. * are simultaneously played.
  30712. *
  30713. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  30714. */
  30715. this.blendMode = blendMode;
  30716. /**
  30717. * The UUID of the animation clip.
  30718. *
  30719. * @type {string}
  30720. * @readonly
  30721. */
  30722. this.uuid = generateUUID();
  30723. // this means it should figure out its duration by scanning the tracks
  30724. if ( this.duration < 0 ) {
  30725. this.resetDuration();
  30726. }
  30727. }
  30728. /**
  30729. * Factory method for creating an animation clip from the given JSON.
  30730. *
  30731. * @static
  30732. * @param {Object} json - The serialized animation clip.
  30733. * @return {AnimationClip} The new animation clip.
  30734. */
  30735. static parse( json ) {
  30736. const tracks = [],
  30737. jsonTracks = json.tracks,
  30738. frameTime = 1.0 / ( json.fps || 1.0 );
  30739. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  30740. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  30741. }
  30742. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  30743. clip.uuid = json.uuid;
  30744. return clip;
  30745. }
  30746. /**
  30747. * Serializes the given animation clip into JSON.
  30748. *
  30749. * @static
  30750. * @param {AnimationClip} clip - The animation clip to serialize.
  30751. * @return {Object} The JSON object.
  30752. */
  30753. static toJSON( clip ) {
  30754. const tracks = [],
  30755. clipTracks = clip.tracks;
  30756. const json = {
  30757. 'name': clip.name,
  30758. 'duration': clip.duration,
  30759. 'tracks': tracks,
  30760. 'uuid': clip.uuid,
  30761. 'blendMode': clip.blendMode
  30762. };
  30763. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  30764. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  30765. }
  30766. return json;
  30767. }
  30768. /**
  30769. * Returns a new animation clip from the passed morph targets array of a
  30770. * geometry, taking a name and the number of frames per second.
  30771. *
  30772. * Note: The fps parameter is required, but the animation speed can be
  30773. * overridden via {@link AnimationAction#setDuration}.
  30774. *
  30775. * @static
  30776. * @param {string} name - The name of the animation clip.
  30777. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  30778. * @param {number} fps - The Frames-Per-Second value.
  30779. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  30780. * @return {AnimationClip} The new animation clip.
  30781. */
  30782. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  30783. const numMorphTargets = morphTargetSequence.length;
  30784. const tracks = [];
  30785. for ( let i = 0; i < numMorphTargets; i ++ ) {
  30786. let times = [];
  30787. let values = [];
  30788. times.push(
  30789. ( i + numMorphTargets - 1 ) % numMorphTargets,
  30790. i,
  30791. ( i + 1 ) % numMorphTargets );
  30792. values.push( 0, 1, 0 );
  30793. const order = getKeyframeOrder( times );
  30794. times = sortedArray( times, 1, order );
  30795. values = sortedArray( values, 1, order );
  30796. // if there is a key at the first frame, duplicate it as the
  30797. // last frame as well for perfect loop.
  30798. if ( ! noLoop && times[ 0 ] === 0 ) {
  30799. times.push( numMorphTargets );
  30800. values.push( values[ 0 ] );
  30801. }
  30802. tracks.push(
  30803. new NumberKeyframeTrack(
  30804. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  30805. times, values
  30806. ).scale( 1.0 / fps ) );
  30807. }
  30808. return new this( name, - 1, tracks );
  30809. }
  30810. /**
  30811. * Searches for an animation clip by name, taking as its first parameter
  30812. * either an array of clips, or a mesh or geometry that contains an
  30813. * array named "animations" property.
  30814. *
  30815. * @static
  30816. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  30817. * @param {string} name - The name to search for.
  30818. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  30819. */
  30820. static findByName( objectOrClipArray, name ) {
  30821. let clipArray = objectOrClipArray;
  30822. if ( ! Array.isArray( objectOrClipArray ) ) {
  30823. const o = objectOrClipArray;
  30824. clipArray = o.geometry && o.geometry.animations || o.animations;
  30825. }
  30826. for ( let i = 0; i < clipArray.length; i ++ ) {
  30827. if ( clipArray[ i ].name === name ) {
  30828. return clipArray[ i ];
  30829. }
  30830. }
  30831. return null;
  30832. }
  30833. /**
  30834. * Returns an array of new AnimationClips created from the morph target
  30835. * sequences of a geometry, trying to sort morph target names into
  30836. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  30837. *
  30838. * See {@link MD2Loader#parse} as an example for how the method should be used.
  30839. *
  30840. * @static
  30841. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  30842. * @param {number} fps - The Frames-Per-Second value.
  30843. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  30844. * @return {Array<AnimationClip>} An array of new animation clips.
  30845. */
  30846. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  30847. const animationToMorphTargets = {};
  30848. // tested with https://regex101.com/ on trick sequences
  30849. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  30850. const pattern = /^([\w-]*?)([\d]+)$/;
  30851. // sort morph target names into animation groups based
  30852. // patterns like Walk_001, Walk_002, Run_001, Run_002
  30853. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  30854. const morphTarget = morphTargets[ i ];
  30855. const parts = morphTarget.name.match( pattern );
  30856. if ( parts && parts.length > 1 ) {
  30857. const name = parts[ 1 ];
  30858. let animationMorphTargets = animationToMorphTargets[ name ];
  30859. if ( ! animationMorphTargets ) {
  30860. animationToMorphTargets[ name ] = animationMorphTargets = [];
  30861. }
  30862. animationMorphTargets.push( morphTarget );
  30863. }
  30864. }
  30865. const clips = [];
  30866. for ( const name in animationToMorphTargets ) {
  30867. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  30868. }
  30869. return clips;
  30870. }
  30871. /**
  30872. * Parses the `animation.hierarchy` format and returns a new animation clip.
  30873. *
  30874. * @static
  30875. * @deprecated since r175.
  30876. * @param {Object} animation - A serialized animation clip as JSON.
  30877. * @param {Array<Bones>} bones - An array of bones.
  30878. * @return {?AnimationClip} The new animation clip.
  30879. */
  30880. static parseAnimation( animation, bones ) {
  30881. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  30882. if ( ! animation ) {
  30883. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  30884. return null;
  30885. }
  30886. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  30887. // only return track if there are actually keys.
  30888. if ( animationKeys.length !== 0 ) {
  30889. const times = [];
  30890. const values = [];
  30891. flattenJSON( animationKeys, times, values, propertyName );
  30892. // empty keys are filtered out, so check again
  30893. if ( times.length !== 0 ) {
  30894. destTracks.push( new trackType( trackName, times, values ) );
  30895. }
  30896. }
  30897. };
  30898. const tracks = [];
  30899. const clipName = animation.name || 'default';
  30900. const fps = animation.fps || 30;
  30901. const blendMode = animation.blendMode;
  30902. // automatic length determination in AnimationClip.
  30903. let duration = animation.length || - 1;
  30904. const hierarchyTracks = animation.hierarchy || [];
  30905. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  30906. const animationKeys = hierarchyTracks[ h ].keys;
  30907. // skip empty tracks
  30908. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  30909. // process morph targets
  30910. if ( animationKeys[ 0 ].morphTargets ) {
  30911. // figure out all morph targets used in this track
  30912. const morphTargetNames = {};
  30913. let k;
  30914. for ( k = 0; k < animationKeys.length; k ++ ) {
  30915. if ( animationKeys[ k ].morphTargets ) {
  30916. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  30917. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  30918. }
  30919. }
  30920. }
  30921. // create a track for each morph target with all zero
  30922. // morphTargetInfluences except for the keys in which
  30923. // the morphTarget is named.
  30924. for ( const morphTargetName in morphTargetNames ) {
  30925. const times = [];
  30926. const values = [];
  30927. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  30928. const animationKey = animationKeys[ k ];
  30929. times.push( animationKey.time );
  30930. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  30931. }
  30932. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  30933. }
  30934. duration = morphTargetNames.length * fps;
  30935. } else {
  30936. // ...assume skeletal animation
  30937. const boneName = '.bones[' + bones[ h ].name + ']';
  30938. addNonemptyTrack(
  30939. VectorKeyframeTrack, boneName + '.position',
  30940. animationKeys, 'pos', tracks );
  30941. addNonemptyTrack(
  30942. QuaternionKeyframeTrack, boneName + '.quaternion',
  30943. animationKeys, 'rot', tracks );
  30944. addNonemptyTrack(
  30945. VectorKeyframeTrack, boneName + '.scale',
  30946. animationKeys, 'scl', tracks );
  30947. }
  30948. }
  30949. if ( tracks.length === 0 ) {
  30950. return null;
  30951. }
  30952. const clip = new this( clipName, duration, tracks, blendMode );
  30953. return clip;
  30954. }
  30955. /**
  30956. * Sets the duration of this clip to the duration of its longest keyframe track.
  30957. *
  30958. * @return {AnimationClip} A reference to this animation clip.
  30959. */
  30960. resetDuration() {
  30961. const tracks = this.tracks;
  30962. let duration = 0;
  30963. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  30964. const track = this.tracks[ i ];
  30965. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  30966. }
  30967. this.duration = duration;
  30968. return this;
  30969. }
  30970. /**
  30971. * Trims all tracks to the clip's duration.
  30972. *
  30973. * @return {AnimationClip} A reference to this animation clip.
  30974. */
  30975. trim() {
  30976. for ( let i = 0; i < this.tracks.length; i ++ ) {
  30977. this.tracks[ i ].trim( 0, this.duration );
  30978. }
  30979. return this;
  30980. }
  30981. /**
  30982. * Performs minimal validation on each track in the clip. Returns `true` if all
  30983. * tracks are valid.
  30984. *
  30985. * @return {boolean} Whether the clip's keyframes are valid or not.
  30986. */
  30987. validate() {
  30988. let valid = true;
  30989. for ( let i = 0; i < this.tracks.length; i ++ ) {
  30990. valid = valid && this.tracks[ i ].validate();
  30991. }
  30992. return valid;
  30993. }
  30994. /**
  30995. * Optimizes each track by removing equivalent sequential keys (which are
  30996. * common in morph target sequences).
  30997. *
  30998. * @return {AnimationClip} A reference to this animation clip.
  30999. */
  31000. optimize() {
  31001. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31002. this.tracks[ i ].optimize();
  31003. }
  31004. return this;
  31005. }
  31006. /**
  31007. * Returns a new animation clip with copied values from this instance.
  31008. *
  31009. * @return {AnimationClip} A clone of this instance.
  31010. */
  31011. clone() {
  31012. const tracks = [];
  31013. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31014. tracks.push( this.tracks[ i ].clone() );
  31015. }
  31016. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31017. }
  31018. /**
  31019. * Serializes this animation clip into JSON.
  31020. *
  31021. * @return {Object} The JSON object.
  31022. */
  31023. toJSON() {
  31024. return this.constructor.toJSON( this );
  31025. }
  31026. }
  31027. function getTrackTypeForValueTypeName( typeName ) {
  31028. switch ( typeName.toLowerCase() ) {
  31029. case 'scalar':
  31030. case 'double':
  31031. case 'float':
  31032. case 'number':
  31033. case 'integer':
  31034. return NumberKeyframeTrack;
  31035. case 'vector':
  31036. case 'vector2':
  31037. case 'vector3':
  31038. case 'vector4':
  31039. return VectorKeyframeTrack;
  31040. case 'color':
  31041. return ColorKeyframeTrack;
  31042. case 'quaternion':
  31043. return QuaternionKeyframeTrack;
  31044. case 'bool':
  31045. case 'boolean':
  31046. return BooleanKeyframeTrack;
  31047. case 'string':
  31048. return StringKeyframeTrack;
  31049. }
  31050. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31051. }
  31052. function parseKeyframeTrack( json ) {
  31053. if ( json.type === undefined ) {
  31054. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31055. }
  31056. const trackType = getTrackTypeForValueTypeName( json.type );
  31057. if ( json.times === undefined ) {
  31058. const times = [], values = [];
  31059. flattenJSON( json.keys, times, values, 'value' );
  31060. json.times = times;
  31061. json.values = values;
  31062. }
  31063. // derived classes can define a static parse method
  31064. if ( trackType.parse !== undefined ) {
  31065. return trackType.parse( json );
  31066. } else {
  31067. // by default, we assume a constructor compatible with the base
  31068. return new trackType( json.name, json.times, json.values, json.interpolation );
  31069. }
  31070. }
  31071. /**
  31072. * @class
  31073. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31074. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31075. * @hideconstructor
  31076. */
  31077. const Cache = {
  31078. /**
  31079. * Whether caching is enabled or not.
  31080. *
  31081. * @static
  31082. * @type {boolean}
  31083. * @default false
  31084. */
  31085. enabled: false,
  31086. /**
  31087. * A dictionary that holds cached files.
  31088. *
  31089. * @static
  31090. * @type {Object<string,Object>}
  31091. */
  31092. files: {},
  31093. /**
  31094. * Adds a cache entry with a key to reference the file. If this key already
  31095. * holds a file, it is overwritten.
  31096. *
  31097. * @static
  31098. * @param {string} key - The key to reference the cached file.
  31099. * @param {Object} file - The file to be cached.
  31100. */
  31101. add: function ( key, file ) {
  31102. if ( this.enabled === false ) return;
  31103. // console.log( 'THREE.Cache', 'Adding key:', key );
  31104. this.files[ key ] = file;
  31105. },
  31106. /**
  31107. * Gets the cached value for the given key.
  31108. *
  31109. * @static
  31110. * @param {string} key - The key to reference the cached file.
  31111. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31112. */
  31113. get: function ( key ) {
  31114. if ( this.enabled === false ) return;
  31115. // console.log( 'THREE.Cache', 'Checking key:', key );
  31116. return this.files[ key ];
  31117. },
  31118. /**
  31119. * Removes the cached file associated with the given key.
  31120. *
  31121. * @static
  31122. * @param {string} key - The key to reference the cached file.
  31123. */
  31124. remove: function ( key ) {
  31125. delete this.files[ key ];
  31126. },
  31127. /**
  31128. * Remove all values from the cache.
  31129. *
  31130. * @static
  31131. */
  31132. clear: function () {
  31133. this.files = {};
  31134. }
  31135. };
  31136. /**
  31137. * Handles and keeps track of loaded and pending data. A default global
  31138. * instance of this class is created and used by loaders if not supplied
  31139. * manually.
  31140. *
  31141. * In general that should be sufficient, however there are times when it can
  31142. * be useful to have separate loaders - for example if you want to show
  31143. * separate loading bars for objects and textures.
  31144. *
  31145. * ```js
  31146. * const manager = new THREE.LoadingManager();
  31147. * manager.onLoad = () => console.log( 'Loading complete!' );
  31148. *
  31149. * const loader1 = new OBJLoader( manager );
  31150. * const loader2 = new ColladaLoader( manager );
  31151. * ```
  31152. */
  31153. class LoadingManager {
  31154. /**
  31155. * Constructs a new loading manager.
  31156. *
  31157. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31158. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31159. * @param {Function} [onError] - Executes when an error occurs.
  31160. */
  31161. constructor( onLoad, onProgress, onError ) {
  31162. const scope = this;
  31163. let isLoading = false;
  31164. let itemsLoaded = 0;
  31165. let itemsTotal = 0;
  31166. let urlModifier = undefined;
  31167. const handlers = [];
  31168. // Refer to #5689 for the reason why we don't set .onStart
  31169. // in the constructor
  31170. /**
  31171. * Executes when an item starts loading.
  31172. *
  31173. * @type {Function|undefined}
  31174. * @default undefined
  31175. */
  31176. this.onStart = undefined;
  31177. /**
  31178. * Executes when all items have been loaded.
  31179. *
  31180. * @type {Function|undefined}
  31181. * @default undefined
  31182. */
  31183. this.onLoad = onLoad;
  31184. /**
  31185. * Executes when single items have been loaded.
  31186. *
  31187. * @type {Function|undefined}
  31188. * @default undefined
  31189. */
  31190. this.onProgress = onProgress;
  31191. /**
  31192. * Executes when an error occurs.
  31193. *
  31194. * @type {Function|undefined}
  31195. * @default undefined
  31196. */
  31197. this.onError = onError;
  31198. /**
  31199. * This should be called by any loader using the manager when the loader
  31200. * starts loading an item.
  31201. *
  31202. * @param {string} url - The URL to load.
  31203. */
  31204. this.itemStart = function ( url ) {
  31205. itemsTotal ++;
  31206. if ( isLoading === false ) {
  31207. if ( scope.onStart !== undefined ) {
  31208. scope.onStart( url, itemsLoaded, itemsTotal );
  31209. }
  31210. }
  31211. isLoading = true;
  31212. };
  31213. /**
  31214. * This should be called by any loader using the manager when the loader
  31215. * ended loading an item.
  31216. *
  31217. * @param {string} url - The URL of the loaded item.
  31218. */
  31219. this.itemEnd = function ( url ) {
  31220. itemsLoaded ++;
  31221. if ( scope.onProgress !== undefined ) {
  31222. scope.onProgress( url, itemsLoaded, itemsTotal );
  31223. }
  31224. if ( itemsLoaded === itemsTotal ) {
  31225. isLoading = false;
  31226. if ( scope.onLoad !== undefined ) {
  31227. scope.onLoad();
  31228. }
  31229. }
  31230. };
  31231. /**
  31232. * This should be called by any loader using the manager when the loader
  31233. * encounters an error when loading an item.
  31234. *
  31235. * @param {string} url - The URL of the item that produces an error.
  31236. */
  31237. this.itemError = function ( url ) {
  31238. if ( scope.onError !== undefined ) {
  31239. scope.onError( url );
  31240. }
  31241. };
  31242. /**
  31243. * Given a URL, uses the URL modifier callback (if any) and returns a
  31244. * resolved URL. If no URL modifier is set, returns the original URL.
  31245. *
  31246. * @param {string} url - The URL to load.
  31247. * @return {string} The resolved URL.
  31248. */
  31249. this.resolveURL = function ( url ) {
  31250. if ( urlModifier ) {
  31251. return urlModifier( url );
  31252. }
  31253. return url;
  31254. };
  31255. /**
  31256. * If provided, the callback will be passed each resource URL before a
  31257. * request is sent. The callback may return the original URL, or a new URL to
  31258. * override loading behavior. This behavior can be used to load assets from
  31259. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31260. *
  31261. * ```js
  31262. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31263. *
  31264. * const manager = new THREE.LoadingManager();
  31265. *
  31266. * // Initialize loading manager with URL callback.
  31267. * const objectURLs = [];
  31268. * manager.setURLModifier( ( url ) => {
  31269. *
  31270. * url = URL.createObjectURL( blobs[ url ] );
  31271. * objectURLs.push( url );
  31272. * return url;
  31273. *
  31274. * } );
  31275. *
  31276. * // Load as usual, then revoke the blob URLs.
  31277. * const loader = new GLTFLoader( manager );
  31278. * loader.load( 'fish.gltf', (gltf) => {
  31279. *
  31280. * scene.add( gltf.scene );
  31281. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31282. *
  31283. * } );
  31284. * ```
  31285. *
  31286. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31287. * @return {LoadingManager} A reference to this loading manager.
  31288. */
  31289. this.setURLModifier = function ( transform ) {
  31290. urlModifier = transform;
  31291. return this;
  31292. };
  31293. /**
  31294. * Registers a loader with the given regular expression. Can be used to
  31295. * define what loader should be used in order to load specific files. A
  31296. * typical use case is to overwrite the default loader for textures.
  31297. *
  31298. * ```js
  31299. * // add handler for TGA textures
  31300. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31301. * ```
  31302. *
  31303. * @param {string} regex - A regular expression.
  31304. * @param {Loader} loader - A loader that should handle matched cases.
  31305. * @return {LoadingManager} A reference to this loading manager.
  31306. */
  31307. this.addHandler = function ( regex, loader ) {
  31308. handlers.push( regex, loader );
  31309. return this;
  31310. };
  31311. /**
  31312. * Removes the loader for the given regular expression.
  31313. *
  31314. * @param {string} regex - A regular expression.
  31315. * @return {LoadingManager} A reference to this loading manager.
  31316. */
  31317. this.removeHandler = function ( regex ) {
  31318. const index = handlers.indexOf( regex );
  31319. if ( index !== - 1 ) {
  31320. handlers.splice( index, 2 );
  31321. }
  31322. return this;
  31323. };
  31324. /**
  31325. * Can be used to retrieve the registered loader for the given file path.
  31326. *
  31327. * @param {string} file - The file path.
  31328. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31329. */
  31330. this.getHandler = function ( file ) {
  31331. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31332. const regex = handlers[ i ];
  31333. const loader = handlers[ i + 1 ];
  31334. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31335. if ( regex.test( file ) ) {
  31336. return loader;
  31337. }
  31338. }
  31339. return null;
  31340. };
  31341. }
  31342. }
  31343. /**
  31344. * The global default loading manager.
  31345. *
  31346. * @constant
  31347. * @type {LoadingManager}
  31348. */
  31349. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31350. /**
  31351. * Abstract base class for loaders.
  31352. *
  31353. * @abstract
  31354. */
  31355. class Loader {
  31356. /**
  31357. * Constructs a new loader.
  31358. *
  31359. * @param {LoadingManager} [manager] - The loading manager.
  31360. */
  31361. constructor( manager ) {
  31362. /**
  31363. * The loading manager.
  31364. *
  31365. * @type {LoadingManager}
  31366. * @default DefaultLoadingManager
  31367. */
  31368. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31369. /**
  31370. * The crossOrigin string to implement CORS for loading the url from a
  31371. * different domain that allows CORS.
  31372. *
  31373. * @type {string}
  31374. * @default 'anonymous'
  31375. */
  31376. this.crossOrigin = 'anonymous';
  31377. /**
  31378. * Whether the XMLHttpRequest uses credentials.
  31379. *
  31380. * @type {boolean}
  31381. * @default false
  31382. */
  31383. this.withCredentials = false;
  31384. /**
  31385. * The base path from which the asset will be loaded.
  31386. *
  31387. * @type {string}
  31388. */
  31389. this.path = '';
  31390. /**
  31391. * The base path from which additional resources like textures will be loaded.
  31392. *
  31393. * @type {string}
  31394. */
  31395. this.resourcePath = '';
  31396. /**
  31397. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31398. * used in HTTP request.
  31399. *
  31400. * @type {Object<string, any>}
  31401. */
  31402. this.requestHeader = {};
  31403. }
  31404. /**
  31405. * This method needs to be implemented by all concrete loaders. It holds the
  31406. * logic for loading assets from the backend.
  31407. *
  31408. * @param {string} url - The path/URL of the file to be loaded.
  31409. * @param {Function} onLoad - Executed when the loading process has been finished.
  31410. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31411. * @param {onErrorCallback} [onError] - Executed when errors occur.
  31412. */
  31413. load( /* url, onLoad, onProgress, onError */ ) {}
  31414. /**
  31415. * A async version of {@link Loader#load}.
  31416. *
  31417. * @param {string} url - The path/URL of the file to be loaded.
  31418. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31419. * @return {Promise} A Promise that resolves when the asset has been loaded.
  31420. */
  31421. loadAsync( url, onProgress ) {
  31422. const scope = this;
  31423. return new Promise( function ( resolve, reject ) {
  31424. scope.load( url, resolve, onProgress, reject );
  31425. } );
  31426. }
  31427. /**
  31428. * This method needs to be implemented by all concrete loaders. It holds the
  31429. * logic for parsing the asset into three.js entities.
  31430. *
  31431. * @param {any} data - The data to parse.
  31432. */
  31433. parse( /* data */ ) {}
  31434. /**
  31435. * Sets the `crossOrigin` String to implement CORS for loading the URL
  31436. * from a different domain that allows CORS.
  31437. *
  31438. * @param {string} crossOrigin - The `crossOrigin` value.
  31439. * @return {Loader} A reference to this instance.
  31440. */
  31441. setCrossOrigin( crossOrigin ) {
  31442. this.crossOrigin = crossOrigin;
  31443. return this;
  31444. }
  31445. /**
  31446. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  31447. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  31448. *
  31449. * Note: This setting has no effect if you are loading files locally or from the same domain.
  31450. *
  31451. * @param {boolean} value - The `withCredentials` value.
  31452. * @return {Loader} A reference to this instance.
  31453. */
  31454. setWithCredentials( value ) {
  31455. this.withCredentials = value;
  31456. return this;
  31457. }
  31458. /**
  31459. * Sets the base path for the asset.
  31460. *
  31461. * @param {string} path - The base path.
  31462. * @return {Loader} A reference to this instance.
  31463. */
  31464. setPath( path ) {
  31465. this.path = path;
  31466. return this;
  31467. }
  31468. /**
  31469. * Sets the base path for dependent resources like textures.
  31470. *
  31471. * @param {string} resourcePath - The resource path.
  31472. * @return {Loader} A reference to this instance.
  31473. */
  31474. setResourcePath( resourcePath ) {
  31475. this.resourcePath = resourcePath;
  31476. return this;
  31477. }
  31478. /**
  31479. * Sets the given request header.
  31480. *
  31481. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31482. * for configuring the HTTP request.
  31483. * @return {Loader} A reference to this instance.
  31484. */
  31485. setRequestHeader( requestHeader ) {
  31486. this.requestHeader = requestHeader;
  31487. return this;
  31488. }
  31489. }
  31490. /**
  31491. * Callback for onProgress in loaders.
  31492. *
  31493. * @callback onProgressCallback
  31494. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  31495. */
  31496. /**
  31497. * Callback for onError in loaders.
  31498. *
  31499. * @callback onErrorCallback
  31500. * @param {Error} error - The error which occurred during the loading process.
  31501. */
  31502. /**
  31503. * The default material name that is used by loaders
  31504. * when creating materials for loaded 3D objects.
  31505. *
  31506. * Note: Not all loaders might honor this setting.
  31507. *
  31508. * @static
  31509. * @type {string}
  31510. * @default '__DEFAULT'
  31511. */
  31512. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  31513. const loading = {};
  31514. class HttpError extends Error {
  31515. constructor( message, response ) {
  31516. super( message );
  31517. this.response = response;
  31518. }
  31519. }
  31520. /**
  31521. * A low level class for loading resources with the Fetch API, used internally by
  31522. * most loaders. It can also be used directly to load any file type that does
  31523. * not have a loader.
  31524. *
  31525. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  31526. * once to your application.
  31527. *
  31528. * ```js
  31529. * const loader = new THREE.FileLoader();
  31530. * const data = await loader.loadAsync( 'example.txt' );
  31531. * ```
  31532. *
  31533. * @augments Loader
  31534. */
  31535. class FileLoader extends Loader {
  31536. /**
  31537. * Constructs a new file loader.
  31538. *
  31539. * @param {LoadingManager} [manager] - The loading manager.
  31540. */
  31541. constructor( manager ) {
  31542. super( manager );
  31543. /**
  31544. * The expected mime type.
  31545. *
  31546. * @type {string}
  31547. */
  31548. this.mimeType = '';
  31549. /**
  31550. * The expected response type.
  31551. *
  31552. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  31553. * @default ''
  31554. */
  31555. this.responseType = '';
  31556. }
  31557. /**
  31558. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  31559. *
  31560. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31561. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  31562. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31563. * @param {onErrorCallback} [onError] - Executed when errors occur.
  31564. * @return {any|undefined} The cached resource if available.
  31565. */
  31566. load( url, onLoad, onProgress, onError ) {
  31567. if ( url === undefined ) url = '';
  31568. if ( this.path !== undefined ) url = this.path + url;
  31569. url = this.manager.resolveURL( url );
  31570. const cached = Cache.get( url );
  31571. if ( cached !== undefined ) {
  31572. this.manager.itemStart( url );
  31573. setTimeout( () => {
  31574. if ( onLoad ) onLoad( cached );
  31575. this.manager.itemEnd( url );
  31576. }, 0 );
  31577. return cached;
  31578. }
  31579. // Check if request is duplicate
  31580. if ( loading[ url ] !== undefined ) {
  31581. loading[ url ].push( {
  31582. onLoad: onLoad,
  31583. onProgress: onProgress,
  31584. onError: onError
  31585. } );
  31586. return;
  31587. }
  31588. // Initialise array for duplicate requests
  31589. loading[ url ] = [];
  31590. loading[ url ].push( {
  31591. onLoad: onLoad,
  31592. onProgress: onProgress,
  31593. onError: onError,
  31594. } );
  31595. // create request
  31596. const req = new Request( url, {
  31597. headers: new Headers( this.requestHeader ),
  31598. credentials: this.withCredentials ? 'include' : 'same-origin',
  31599. // An abort controller could be added within a future PR
  31600. } );
  31601. // record states ( avoid data race )
  31602. const mimeType = this.mimeType;
  31603. const responseType = this.responseType;
  31604. // start the fetch
  31605. fetch( req )
  31606. .then( response => {
  31607. if ( response.status === 200 || response.status === 0 ) {
  31608. // Some browsers return HTTP Status 0 when using non-http protocol
  31609. // e.g. 'file://' or 'data://'. Handle as success.
  31610. if ( response.status === 0 ) {
  31611. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  31612. }
  31613. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  31614. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  31615. return response;
  31616. }
  31617. const callbacks = loading[ url ];
  31618. const reader = response.body.getReader();
  31619. // Nginx needs X-File-Size check
  31620. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  31621. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  31622. const total = contentLength ? parseInt( contentLength ) : 0;
  31623. const lengthComputable = total !== 0;
  31624. let loaded = 0;
  31625. // periodically read data into the new stream tracking while download progress
  31626. const stream = new ReadableStream( {
  31627. start( controller ) {
  31628. readData();
  31629. function readData() {
  31630. reader.read().then( ( { done, value } ) => {
  31631. if ( done ) {
  31632. controller.close();
  31633. } else {
  31634. loaded += value.byteLength;
  31635. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  31636. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  31637. const callback = callbacks[ i ];
  31638. if ( callback.onProgress ) callback.onProgress( event );
  31639. }
  31640. controller.enqueue( value );
  31641. readData();
  31642. }
  31643. }, ( e ) => {
  31644. controller.error( e );
  31645. } );
  31646. }
  31647. }
  31648. } );
  31649. return new Response( stream );
  31650. } else {
  31651. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  31652. }
  31653. } )
  31654. .then( response => {
  31655. switch ( responseType ) {
  31656. case 'arraybuffer':
  31657. return response.arrayBuffer();
  31658. case 'blob':
  31659. return response.blob();
  31660. case 'document':
  31661. return response.text()
  31662. .then( text => {
  31663. const parser = new DOMParser();
  31664. return parser.parseFromString( text, mimeType );
  31665. } );
  31666. case 'json':
  31667. return response.json();
  31668. default:
  31669. if ( mimeType === '' ) {
  31670. return response.text();
  31671. } else {
  31672. // sniff encoding
  31673. const re = /charset="?([^;"\s]*)"?/i;
  31674. const exec = re.exec( mimeType );
  31675. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  31676. const decoder = new TextDecoder( label );
  31677. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  31678. }
  31679. }
  31680. } )
  31681. .then( data => {
  31682. // Add to cache only on HTTP success, so that we do not cache
  31683. // error response bodies as proper responses to requests.
  31684. Cache.add( url, data );
  31685. const callbacks = loading[ url ];
  31686. delete loading[ url ];
  31687. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  31688. const callback = callbacks[ i ];
  31689. if ( callback.onLoad ) callback.onLoad( data );
  31690. }
  31691. } )
  31692. .catch( err => {
  31693. // Abort errors and other errors are handled the same
  31694. const callbacks = loading[ url ];
  31695. if ( callbacks === undefined ) {
  31696. // When onLoad was called and url was deleted in `loading`
  31697. this.manager.itemError( url );
  31698. throw err;
  31699. }
  31700. delete loading[ url ];
  31701. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  31702. const callback = callbacks[ i ];
  31703. if ( callback.onError ) callback.onError( err );
  31704. }
  31705. this.manager.itemError( url );
  31706. } )
  31707. .finally( () => {
  31708. this.manager.itemEnd( url );
  31709. } );
  31710. this.manager.itemStart( url );
  31711. }
  31712. /**
  31713. * Sets the expected response type.
  31714. *
  31715. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  31716. * @return {FileLoader} A reference to this file loader.
  31717. */
  31718. setResponseType( value ) {
  31719. this.responseType = value;
  31720. return this;
  31721. }
  31722. /**
  31723. * Sets the expected mime type of the loaded file.
  31724. *
  31725. * @param {string} value - The mime type.
  31726. * @return {FileLoader} A reference to this file loader.
  31727. */
  31728. setMimeType( value ) {
  31729. this.mimeType = value;
  31730. return this;
  31731. }
  31732. }
  31733. /**
  31734. * Class for loading animation clips in the JSON format. The files are internally
  31735. * loaded via {@link FileLoader}.
  31736. *
  31737. * ```js
  31738. * const loader = new THREE.AnimationLoader();
  31739. * const animations = await loader.loadAsync( 'animations/animation.js' );
  31740. * ```
  31741. *
  31742. * @augments Loader
  31743. */
  31744. class AnimationLoader extends Loader {
  31745. /**
  31746. * Constructs a new animation loader.
  31747. *
  31748. * @param {LoadingManager} [manager] - The loading manager.
  31749. */
  31750. constructor( manager ) {
  31751. super( manager );
  31752. }
  31753. /**
  31754. * Starts loading from the given URL and pass the loaded animations as an array
  31755. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  31756. *
  31757. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31758. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  31759. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31760. * @param {onErrorCallback} onError - Executed when errors occur.
  31761. */
  31762. load( url, onLoad, onProgress, onError ) {
  31763. const scope = this;
  31764. const loader = new FileLoader( this.manager );
  31765. loader.setPath( this.path );
  31766. loader.setRequestHeader( this.requestHeader );
  31767. loader.setWithCredentials( this.withCredentials );
  31768. loader.load( url, function ( text ) {
  31769. try {
  31770. onLoad( scope.parse( JSON.parse( text ) ) );
  31771. } catch ( e ) {
  31772. if ( onError ) {
  31773. onError( e );
  31774. } else {
  31775. console.error( e );
  31776. }
  31777. scope.manager.itemError( url );
  31778. }
  31779. }, onProgress, onError );
  31780. }
  31781. /**
  31782. * Parses the given JSON object and returns an array of animation clips.
  31783. *
  31784. * @param {Object} json - The serialized animation clips.
  31785. * @return {Array<AnimationClip>} The parsed animation clips.
  31786. */
  31787. parse( json ) {
  31788. const animations = [];
  31789. for ( let i = 0; i < json.length; i ++ ) {
  31790. const clip = AnimationClip.parse( json[ i ] );
  31791. animations.push( clip );
  31792. }
  31793. return animations;
  31794. }
  31795. }
  31796. /**
  31797. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  31798. * Textures are internally loaded via {@link FileLoader}.
  31799. *
  31800. * Derived classes have to implement the `parse()` method which holds the parsing
  31801. * for the respective format.
  31802. *
  31803. * @abstract
  31804. * @augments Loader
  31805. */
  31806. class CompressedTextureLoader extends Loader {
  31807. /**
  31808. * Constructs a new compressed texture loader.
  31809. *
  31810. * @param {LoadingManager} [manager] - The loading manager.
  31811. */
  31812. constructor( manager ) {
  31813. super( manager );
  31814. }
  31815. /**
  31816. * Starts loading from the given URL and passes the loaded compressed texture
  31817. * to the `onLoad()` callback. The method also returns a new texture object which can
  31818. * directly be used for material creation. If you do it this way, the texture
  31819. * may pop up in your scene once the respective loading process is finished.
  31820. *
  31821. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31822. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  31823. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  31824. * @param {onErrorCallback} onError - Executed when errors occur.
  31825. * @return {CompressedTexture} The compressed texture.
  31826. */
  31827. load( url, onLoad, onProgress, onError ) {
  31828. const scope = this;
  31829. const images = [];
  31830. const texture = new CompressedTexture();
  31831. const loader = new FileLoader( this.manager );
  31832. loader.setPath( this.path );
  31833. loader.setResponseType( 'arraybuffer' );
  31834. loader.setRequestHeader( this.requestHeader );
  31835. loader.setWithCredentials( scope.withCredentials );
  31836. let loaded = 0;
  31837. function loadTexture( i ) {
  31838. loader.load( url[ i ], function ( buffer ) {
  31839. const texDatas = scope.parse( buffer, true );
  31840. images[ i ] = {
  31841. width: texDatas.width,
  31842. height: texDatas.height,
  31843. format: texDatas.format,
  31844. mipmaps: texDatas.mipmaps
  31845. };
  31846. loaded += 1;
  31847. if ( loaded === 6 ) {
  31848. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  31849. texture.image = images;
  31850. texture.format = texDatas.format;
  31851. texture.needsUpdate = true;
  31852. if ( onLoad ) onLoad( texture );
  31853. }
  31854. }, onProgress, onError );
  31855. }
  31856. if ( Array.isArray( url ) ) {
  31857. for ( let i = 0, il = url.length; i < il; ++ i ) {
  31858. loadTexture( i );
  31859. }
  31860. } else {
  31861. // compressed cubemap texture stored in a single DDS file
  31862. loader.load( url, function ( buffer ) {
  31863. const texDatas = scope.parse( buffer, true );
  31864. if ( texDatas.isCubemap ) {
  31865. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  31866. for ( let f = 0; f < faces; f ++ ) {
  31867. images[ f ] = { mipmaps: [] };
  31868. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  31869. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  31870. images[ f ].format = texDatas.format;
  31871. images[ f ].width = texDatas.width;
  31872. images[ f ].height = texDatas.height;
  31873. }
  31874. }
  31875. texture.image = images;
  31876. } else {
  31877. texture.image.width = texDatas.width;
  31878. texture.image.height = texDatas.height;
  31879. texture.mipmaps = texDatas.mipmaps;
  31880. }
  31881. if ( texDatas.mipmapCount === 1 ) {
  31882. texture.minFilter = LinearFilter;
  31883. }
  31884. texture.format = texDatas.format;
  31885. texture.needsUpdate = true;
  31886. if ( onLoad ) onLoad( texture );
  31887. }, onProgress, onError );
  31888. }
  31889. return texture;
  31890. }
  31891. }
  31892. /**
  31893. * A loader for loading images. The class loads images with the HTML `Image` API.
  31894. *
  31895. * ```js
  31896. * const loader = new THREE.ImageLoader();
  31897. * const image = await loader.loadAsync( 'image.png' );
  31898. * ```
  31899. * Please note that `ImageLoader` has dropped support for progress
  31900. * events in `r84`. For an `ImageLoader` that supports progress events, see
  31901. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  31902. *
  31903. * @augments Loader
  31904. */
  31905. class ImageLoader extends Loader {
  31906. /**
  31907. * Constructs a new image loader.
  31908. *
  31909. * @param {LoadingManager} [manager] - The loading manager.
  31910. */
  31911. constructor( manager ) {
  31912. super( manager );
  31913. }
  31914. /**
  31915. * Starts loading from the given URL and passes the loaded image
  31916. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  31917. * directly be used for texture creation. If you do it this way, the texture
  31918. * may pop up in your scene once the respective loading process is finished.
  31919. *
  31920. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  31921. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  31922. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  31923. * @param {onErrorCallback} onError - Executed when errors occur.
  31924. * @return {Image} The image.
  31925. */
  31926. load( url, onLoad, onProgress, onError ) {
  31927. if ( this.path !== undefined ) url = this.path + url;
  31928. url = this.manager.resolveURL( url );
  31929. const scope = this;
  31930. const cached = Cache.get( url );
  31931. if ( cached !== undefined ) {
  31932. scope.manager.itemStart( url );
  31933. setTimeout( function () {
  31934. if ( onLoad ) onLoad( cached );
  31935. scope.manager.itemEnd( url );
  31936. }, 0 );
  31937. return cached;
  31938. }
  31939. const image = createElementNS( 'img' );
  31940. function onImageLoad() {
  31941. removeEventListeners();
  31942. Cache.add( url, this );
  31943. if ( onLoad ) onLoad( this );
  31944. scope.manager.itemEnd( url );
  31945. }
  31946. function onImageError( event ) {
  31947. removeEventListeners();
  31948. if ( onError ) onError( event );
  31949. scope.manager.itemError( url );
  31950. scope.manager.itemEnd( url );
  31951. }
  31952. function removeEventListeners() {
  31953. image.removeEventListener( 'load', onImageLoad, false );
  31954. image.removeEventListener( 'error', onImageError, false );
  31955. }
  31956. image.addEventListener( 'load', onImageLoad, false );
  31957. image.addEventListener( 'error', onImageError, false );
  31958. if ( url.slice( 0, 5 ) !== 'data:' ) {
  31959. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  31960. }
  31961. scope.manager.itemStart( url );
  31962. image.src = url;
  31963. return image;
  31964. }
  31965. }
  31966. /**
  31967. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  31968. *
  31969. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  31970. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  31971. * like vertical and horizontal cross, column and row layouts are not supported.
  31972. *
  31973. * Note that, by convention, cube maps are specified in a coordinate system
  31974. * in which positive-x is to the right when looking up the positive-z axis --
  31975. * in other words, using a left-handed coordinate system. Since three.js uses
  31976. * a right-handed coordinate system, environment maps used in three.js will
  31977. * have pos-x and neg-x swapped.
  31978. *
  31979. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  31980. * is set to `SRGBColorSpace` by default.
  31981. *
  31982. * ```js
  31983. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  31984. * const cubeTexture = await loader.loadAsync( [
  31985. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  31986. * ] );
  31987. * scene.background = cubeTexture;
  31988. * ```
  31989. *
  31990. * @augments Loader
  31991. */
  31992. class CubeTextureLoader extends Loader {
  31993. /**
  31994. * Constructs a new cube texture loader.
  31995. *
  31996. * @param {LoadingManager} [manager] - The loading manager.
  31997. */
  31998. constructor( manager ) {
  31999. super( manager );
  32000. }
  32001. /**
  32002. * Starts loading from the given URL and pass the fully loaded cube texture
  32003. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32004. * directly be used for material creation. If you do it this way, the cube texture
  32005. * may pop up in your scene once the respective loading process is finished.
  32006. *
  32007. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32008. * cube texture. The urls should be specified in the following order: pos-x,
  32009. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32010. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32011. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32012. * @param {onErrorCallback} onError - Executed when errors occur.
  32013. * @return {CubeTexture} The cube texture.
  32014. */
  32015. load( urls, onLoad, onProgress, onError ) {
  32016. const texture = new CubeTexture();
  32017. texture.colorSpace = SRGBColorSpace;
  32018. const loader = new ImageLoader( this.manager );
  32019. loader.setCrossOrigin( this.crossOrigin );
  32020. loader.setPath( this.path );
  32021. let loaded = 0;
  32022. function loadTexture( i ) {
  32023. loader.load( urls[ i ], function ( image ) {
  32024. texture.images[ i ] = image;
  32025. loaded ++;
  32026. if ( loaded === 6 ) {
  32027. texture.needsUpdate = true;
  32028. if ( onLoad ) onLoad( texture );
  32029. }
  32030. }, undefined, onError );
  32031. }
  32032. for ( let i = 0; i < urls.length; ++ i ) {
  32033. loadTexture( i );
  32034. }
  32035. return texture;
  32036. }
  32037. }
  32038. /**
  32039. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32040. * Textures are internally loaded via {@link FileLoader}.
  32041. *
  32042. * Derived classes have to implement the `parse()` method which holds the parsing
  32043. * for the respective format.
  32044. *
  32045. * @abstract
  32046. * @augments Loader
  32047. */
  32048. class DataTextureLoader extends Loader {
  32049. /**
  32050. * Constructs a new data texture loader.
  32051. *
  32052. * @param {LoadingManager} [manager] - The loading manager.
  32053. */
  32054. constructor( manager ) {
  32055. super( manager );
  32056. }
  32057. /**
  32058. * Starts loading from the given URL and passes the loaded data texture
  32059. * to the `onLoad()` callback. The method also returns a new texture object which can
  32060. * directly be used for material creation. If you do it this way, the texture
  32061. * may pop up in your scene once the respective loading process is finished.
  32062. *
  32063. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32064. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32065. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32066. * @param {onErrorCallback} onError - Executed when errors occur.
  32067. * @return {DataTexture} The data texture.
  32068. */
  32069. load( url, onLoad, onProgress, onError ) {
  32070. const scope = this;
  32071. const texture = new DataTexture();
  32072. const loader = new FileLoader( this.manager );
  32073. loader.setResponseType( 'arraybuffer' );
  32074. loader.setRequestHeader( this.requestHeader );
  32075. loader.setPath( this.path );
  32076. loader.setWithCredentials( scope.withCredentials );
  32077. loader.load( url, function ( buffer ) {
  32078. let texData;
  32079. try {
  32080. texData = scope.parse( buffer );
  32081. } catch ( error ) {
  32082. if ( onError !== undefined ) {
  32083. onError( error );
  32084. } else {
  32085. console.error( error );
  32086. return;
  32087. }
  32088. }
  32089. if ( texData.image !== undefined ) {
  32090. texture.image = texData.image;
  32091. } else if ( texData.data !== undefined ) {
  32092. texture.image.width = texData.width;
  32093. texture.image.height = texData.height;
  32094. texture.image.data = texData.data;
  32095. }
  32096. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32097. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32098. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32099. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32100. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32101. if ( texData.colorSpace !== undefined ) {
  32102. texture.colorSpace = texData.colorSpace;
  32103. }
  32104. if ( texData.flipY !== undefined ) {
  32105. texture.flipY = texData.flipY;
  32106. }
  32107. if ( texData.format !== undefined ) {
  32108. texture.format = texData.format;
  32109. }
  32110. if ( texData.type !== undefined ) {
  32111. texture.type = texData.type;
  32112. }
  32113. if ( texData.mipmaps !== undefined ) {
  32114. texture.mipmaps = texData.mipmaps;
  32115. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32116. }
  32117. if ( texData.mipmapCount === 1 ) {
  32118. texture.minFilter = LinearFilter;
  32119. }
  32120. if ( texData.generateMipmaps !== undefined ) {
  32121. texture.generateMipmaps = texData.generateMipmaps;
  32122. }
  32123. texture.needsUpdate = true;
  32124. if ( onLoad ) onLoad( texture, texData );
  32125. }, onProgress, onError );
  32126. return texture;
  32127. }
  32128. }
  32129. /**
  32130. * Class for loading textures. Images are internally
  32131. * loaded via {@link ImageLoader}.
  32132. *
  32133. * ```js
  32134. * const loader = new THREE.TextureLoader();
  32135. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32136. *
  32137. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32138. * ```
  32139. * Please note that `TextureLoader` has dropped support for progress
  32140. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32141. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32142. *
  32143. * @augments Loader
  32144. */
  32145. class TextureLoader extends Loader {
  32146. /**
  32147. * Constructs a new texture loader.
  32148. *
  32149. * @param {LoadingManager} [manager] - The loading manager.
  32150. */
  32151. constructor( manager ) {
  32152. super( manager );
  32153. }
  32154. /**
  32155. * Starts loading from the given URL and pass the fully loaded texture
  32156. * to the `onLoad()` callback. The method also returns a new texture object which can
  32157. * directly be used for material creation. If you do it this way, the texture
  32158. * may pop up in your scene once the respective loading process is finished.
  32159. *
  32160. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32161. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32162. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32163. * @param {onErrorCallback} onError - Executed when errors occur.
  32164. * @return {Texture} The texture.
  32165. */
  32166. load( url, onLoad, onProgress, onError ) {
  32167. const texture = new Texture();
  32168. const loader = new ImageLoader( this.manager );
  32169. loader.setCrossOrigin( this.crossOrigin );
  32170. loader.setPath( this.path );
  32171. loader.load( url, function ( image ) {
  32172. texture.image = image;
  32173. texture.needsUpdate = true;
  32174. if ( onLoad !== undefined ) {
  32175. onLoad( texture );
  32176. }
  32177. }, onProgress, onError );
  32178. return texture;
  32179. }
  32180. }
  32181. /**
  32182. * Abstract base class for lights - all other light types inherit the
  32183. * properties and methods described here.
  32184. *
  32185. * @abstract
  32186. * @augments Object3D
  32187. */
  32188. class Light extends Object3D {
  32189. /**
  32190. * Constructs a new light.
  32191. *
  32192. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32193. * @param {number} [intensity=1] - The light's strength/intensity.
  32194. */
  32195. constructor( color, intensity = 1 ) {
  32196. super();
  32197. /**
  32198. * This flag can be used for type testing.
  32199. *
  32200. * @type {boolean}
  32201. * @readonly
  32202. * @default true
  32203. */
  32204. this.isLight = true;
  32205. this.type = 'Light';
  32206. /**
  32207. * The light's color.
  32208. *
  32209. * @type {Color}
  32210. */
  32211. this.color = new Color( color );
  32212. /**
  32213. * The light's intensity.
  32214. *
  32215. * @type {number}
  32216. * @default 1
  32217. */
  32218. this.intensity = intensity;
  32219. }
  32220. /**
  32221. * Frees the GPU-related resources allocated by this instance. Call this
  32222. * method whenever this instance is no longer used in your app.
  32223. */
  32224. dispose() {
  32225. // Empty here in base class; some subclasses override.
  32226. }
  32227. copy( source, recursive ) {
  32228. super.copy( source, recursive );
  32229. this.color.copy( source.color );
  32230. this.intensity = source.intensity;
  32231. return this;
  32232. }
  32233. toJSON( meta ) {
  32234. const data = super.toJSON( meta );
  32235. data.object.color = this.color.getHex();
  32236. data.object.intensity = this.intensity;
  32237. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32238. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32239. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32240. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32241. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32242. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32243. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32244. return data;
  32245. }
  32246. }
  32247. /**
  32248. * A light source positioned directly above the scene, with color fading from
  32249. * the sky color to the ground color.
  32250. *
  32251. * This light cannot be used to cast shadows.
  32252. *
  32253. * ```js
  32254. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32255. * scene.add( light );
  32256. * ```
  32257. *
  32258. * @augments Light
  32259. */
  32260. class HemisphereLight extends Light {
  32261. /**
  32262. * Constructs a new hemisphere light.
  32263. *
  32264. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32265. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32266. * @param {number} [intensity=1] - The light's strength/intensity.
  32267. */
  32268. constructor( skyColor, groundColor, intensity ) {
  32269. super( skyColor, intensity );
  32270. /**
  32271. * This flag can be used for type testing.
  32272. *
  32273. * @type {boolean}
  32274. * @readonly
  32275. * @default true
  32276. */
  32277. this.isHemisphereLight = true;
  32278. this.type = 'HemisphereLight';
  32279. this.position.copy( Object3D.DEFAULT_UP );
  32280. this.updateMatrix();
  32281. /**
  32282. * The light's ground color.
  32283. *
  32284. * @type {Color}
  32285. */
  32286. this.groundColor = new Color( groundColor );
  32287. }
  32288. copy( source, recursive ) {
  32289. super.copy( source, recursive );
  32290. this.groundColor.copy( source.groundColor );
  32291. return this;
  32292. }
  32293. }
  32294. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32295. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32296. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32297. /**
  32298. * Abstract base class for light shadow classes. These classes
  32299. * represent the shadow configuration for different light types.
  32300. *
  32301. * @abstract
  32302. */
  32303. class LightShadow {
  32304. /**
  32305. * Constructs a new light shadow.
  32306. *
  32307. * @param {Camera} camera - The light's view of the world.
  32308. */
  32309. constructor( camera ) {
  32310. /**
  32311. * The light's view of the world.
  32312. *
  32313. * @type {Camera}
  32314. */
  32315. this.camera = camera;
  32316. /**
  32317. * The intensity of the shadow. The default is `1`.
  32318. * Valid values are in the range `[0, 1]`.
  32319. *
  32320. * @type {number}
  32321. * @default 1
  32322. */
  32323. this.intensity = 1;
  32324. /**
  32325. * Shadow map bias, how much to add or subtract from the normalized depth
  32326. * when deciding whether a surface is in shadow.
  32327. *
  32328. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32329. * may help reduce artifacts in shadows.
  32330. *
  32331. * @type {number}
  32332. * @default 0
  32333. */
  32334. this.bias = 0;
  32335. /**
  32336. * Defines how much the position used to query the shadow map is offset along
  32337. * the object normal. The default is `0`. Increasing this value can be used to
  32338. * reduce shadow acne especially in large scenes where light shines onto
  32339. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32340. *
  32341. * @type {number}
  32342. * @default 0
  32343. */
  32344. this.normalBias = 0;
  32345. /**
  32346. * Setting this to values greater than 1 will blur the edges of the shadow.
  32347. * High values will cause unwanted banding effects in the shadows - a greater
  32348. * map size will allow for a higher value to be used here before these effects
  32349. * become visible.
  32350. *
  32351. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32352. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32353. *
  32354. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32355. *
  32356. * @type {number}
  32357. * @default 1
  32358. */
  32359. this.radius = 1;
  32360. /**
  32361. * The amount of samples to use when blurring a VSM shadow map.
  32362. *
  32363. * @type {number}
  32364. * @default 8
  32365. */
  32366. this.blurSamples = 8;
  32367. /**
  32368. * Defines the width and height of the shadow map. Higher values give better quality
  32369. * shadows at the cost of computation time. Values must be powers of two.
  32370. *
  32371. * @type {Vector2}
  32372. * @default (512,512)
  32373. */
  32374. this.mapSize = new Vector2( 512, 512 );
  32375. /**
  32376. * The depth map generated using the internal camera; a location beyond a
  32377. * pixel's depth is in shadow. Computed internally during rendering.
  32378. *
  32379. * @type {?RenderTarget}
  32380. * @default null
  32381. */
  32382. this.map = null;
  32383. /**
  32384. * The distribution map generated using the internal camera; an occlusion is
  32385. * calculated based on the distribution of depths. Computed internally during
  32386. * rendering.
  32387. *
  32388. * @type {?RenderTarget}
  32389. * @default null
  32390. */
  32391. this.mapPass = null;
  32392. /**
  32393. * Model to shadow camera space, to compute location and depth in shadow map.
  32394. * This is computed internally during rendering.
  32395. *
  32396. * @type {Matrix4}
  32397. */
  32398. this.matrix = new Matrix4();
  32399. /**
  32400. * Enables automatic updates of the light's shadow. If you do not require dynamic
  32401. * lighting / shadows, you may set this to `false`.
  32402. *
  32403. * @type {boolean}
  32404. * @default true
  32405. */
  32406. this.autoUpdate = true;
  32407. /**
  32408. * When set to `true`, shadow maps will be updated in the next `render` call.
  32409. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  32410. * set this property to `true` and then make a render call to update the light's shadow.
  32411. *
  32412. * @type {boolean}
  32413. * @default false
  32414. */
  32415. this.needsUpdate = false;
  32416. this._frustum = new Frustum();
  32417. this._frameExtents = new Vector2( 1, 1 );
  32418. this._viewportCount = 1;
  32419. this._viewports = [
  32420. new Vector4( 0, 0, 1, 1 )
  32421. ];
  32422. }
  32423. /**
  32424. * Used internally by the renderer to get the number of viewports that need
  32425. * to be rendered for this shadow.
  32426. *
  32427. * @return {number} The viewport count.
  32428. */
  32429. getViewportCount() {
  32430. return this._viewportCount;
  32431. }
  32432. /**
  32433. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  32434. *
  32435. * @return {Frustum} The shadow camera frustum.
  32436. */
  32437. getFrustum() {
  32438. return this._frustum;
  32439. }
  32440. /**
  32441. * Update the matrices for the camera and shadow, used internally by the renderer.
  32442. *
  32443. * @param {Light} light - The light for which the shadow is being rendered.
  32444. */
  32445. updateMatrices( light ) {
  32446. const shadowCamera = this.camera;
  32447. const shadowMatrix = this.matrix;
  32448. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  32449. shadowCamera.position.copy( _lightPositionWorld$1 );
  32450. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  32451. shadowCamera.lookAt( _lookTarget$1 );
  32452. shadowCamera.updateMatrixWorld();
  32453. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  32454. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  32455. shadowMatrix.set(
  32456. 0.5, 0.0, 0.0, 0.5,
  32457. 0.0, 0.5, 0.0, 0.5,
  32458. 0.0, 0.0, 0.5, 0.5,
  32459. 0.0, 0.0, 0.0, 1.0
  32460. );
  32461. shadowMatrix.multiply( _projScreenMatrix$1 );
  32462. }
  32463. /**
  32464. * Returns a viewport definition for the given viewport index.
  32465. *
  32466. * @param {number} viewportIndex - The viewport index.
  32467. * @return {Vector4} The viewport.
  32468. */
  32469. getViewport( viewportIndex ) {
  32470. return this._viewports[ viewportIndex ];
  32471. }
  32472. /**
  32473. * Returns the frame extends.
  32474. *
  32475. * @return {Vector2} The frame extends.
  32476. */
  32477. getFrameExtents() {
  32478. return this._frameExtents;
  32479. }
  32480. /**
  32481. * Frees the GPU-related resources allocated by this instance. Call this
  32482. * method whenever this instance is no longer used in your app.
  32483. */
  32484. dispose() {
  32485. if ( this.map ) {
  32486. this.map.dispose();
  32487. }
  32488. if ( this.mapPass ) {
  32489. this.mapPass.dispose();
  32490. }
  32491. }
  32492. /**
  32493. * Copies the values of the given light shadow instance to this instance.
  32494. *
  32495. * @param {LightShadow} source - The light shadow to copy.
  32496. * @return {LightShadow} A reference to this light shadow instance.
  32497. */
  32498. copy( source ) {
  32499. this.camera = source.camera.clone();
  32500. this.intensity = source.intensity;
  32501. this.bias = source.bias;
  32502. this.radius = source.radius;
  32503. this.mapSize.copy( source.mapSize );
  32504. return this;
  32505. }
  32506. /**
  32507. * Returns a new light shadow instance with copied values from this instance.
  32508. *
  32509. * @return {LightShadow} A clone of this instance.
  32510. */
  32511. clone() {
  32512. return new this.constructor().copy( this );
  32513. }
  32514. /**
  32515. * Serializes the light shadow into JSON.
  32516. *
  32517. * @return {Object} A JSON object representing the serialized light shadow.
  32518. * @see {@link ObjectLoader#parse}
  32519. */
  32520. toJSON() {
  32521. const object = {};
  32522. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  32523. if ( this.bias !== 0 ) object.bias = this.bias;
  32524. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  32525. if ( this.radius !== 1 ) object.radius = this.radius;
  32526. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  32527. object.camera = this.camera.toJSON( false ).object;
  32528. delete object.camera.matrix;
  32529. return object;
  32530. }
  32531. }
  32532. /**
  32533. * Represents the shadow configuration of directional lights.
  32534. *
  32535. * @augments LightShadow
  32536. */
  32537. class SpotLightShadow extends LightShadow {
  32538. /**
  32539. * Constructs a new spot light shadow.
  32540. */
  32541. constructor() {
  32542. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  32543. /**
  32544. * This flag can be used for type testing.
  32545. *
  32546. * @type {boolean}
  32547. * @readonly
  32548. * @default true
  32549. */
  32550. this.isSpotLightShadow = true;
  32551. /**
  32552. * Used to focus the shadow camera. The camera's field of view is set as a
  32553. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  32554. *
  32555. * @type {number}
  32556. * @default 1
  32557. */
  32558. this.focus = 1;
  32559. }
  32560. updateMatrices( light ) {
  32561. const camera = this.camera;
  32562. const fov = RAD2DEG * 2 * light.angle * this.focus;
  32563. const aspect = this.mapSize.width / this.mapSize.height;
  32564. const far = light.distance || camera.far;
  32565. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  32566. camera.fov = fov;
  32567. camera.aspect = aspect;
  32568. camera.far = far;
  32569. camera.updateProjectionMatrix();
  32570. }
  32571. super.updateMatrices( light );
  32572. }
  32573. copy( source ) {
  32574. super.copy( source );
  32575. this.focus = source.focus;
  32576. return this;
  32577. }
  32578. }
  32579. /**
  32580. * This light gets emitted from a single point in one direction, along a cone
  32581. * that increases in size the further from the light it gets.
  32582. *
  32583. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  32584. *
  32585. * ```js
  32586. * // white spotlight shining from the side, modulated by a texture
  32587. * const spotLight = new THREE.SpotLight( 0xffffff );
  32588. * spotLight.position.set( 100, 1000, 100 );
  32589. * spotLight.map = new THREE.TextureLoader().load( url );
  32590. *
  32591. * spotLight.castShadow = true;
  32592. * spotLight.shadow.mapSize.width = 1024;
  32593. * spotLight.shadow.mapSize.height = 1024;
  32594. * spotLight.shadow.camera.near = 500;
  32595. * spotLight.shadow.camera.far = 4000;
  32596. * spotLight.shadow.camera.fov = 30;s
  32597. * ```
  32598. *
  32599. * @augments Light
  32600. */
  32601. class SpotLight extends Light {
  32602. /**
  32603. * Constructs a new spot light.
  32604. *
  32605. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32606. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  32607. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  32608. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  32609. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  32610. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  32611. */
  32612. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  32613. super( color, intensity );
  32614. /**
  32615. * This flag can be used for type testing.
  32616. *
  32617. * @type {boolean}
  32618. * @readonly
  32619. * @default true
  32620. */
  32621. this.isSpotLight = true;
  32622. this.type = 'SpotLight';
  32623. this.position.copy( Object3D.DEFAULT_UP );
  32624. this.updateMatrix();
  32625. /**
  32626. * The spot light points from its position to the
  32627. * target's position.
  32628. *
  32629. * For the target's position to be changed to anything other
  32630. * than the default, it must be added to the scene.
  32631. *
  32632. * It is also possible to set the target to be another 3D object
  32633. * in the scene. The light will now track the target object.
  32634. *
  32635. * @type {Object3D}
  32636. */
  32637. this.target = new Object3D();
  32638. /**
  32639. * Maximum range of the light. `0` means no limit.
  32640. *
  32641. * @type {number}
  32642. * @default 0
  32643. */
  32644. this.distance = distance;
  32645. /**
  32646. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  32647. *
  32648. * @type {number}
  32649. * @default Math.PI/3
  32650. */
  32651. this.angle = angle;
  32652. /**
  32653. * Percent of the spotlight cone that is attenuated due to penumbra.
  32654. * Value range is `[0,1]`.
  32655. *
  32656. * @type {number}
  32657. * @default 0
  32658. */
  32659. this.penumbra = penumbra;
  32660. /**
  32661. * The amount the light dims along the distance of the light. In context of
  32662. * physically-correct rendering the default value should not be changed.
  32663. *
  32664. * @type {number}
  32665. * @default 2
  32666. */
  32667. this.decay = decay;
  32668. /**
  32669. * A texture used to modulate the color of the light. The spot light
  32670. * color is mixed with the RGB value of this texture, with a ratio
  32671. * corresponding to its alpha value. The cookie-like masking effect is
  32672. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  32673. *
  32674. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  32675. *
  32676. * @type {?Texture}
  32677. * @default null
  32678. */
  32679. this.map = null;
  32680. /**
  32681. * This property holds the light's shadow configuration.
  32682. *
  32683. * @type {SpotLightShadow}
  32684. */
  32685. this.shadow = new SpotLightShadow();
  32686. }
  32687. /**
  32688. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  32689. * Changing the power will also change the light's intensity.
  32690. *
  32691. * @type {number}
  32692. */
  32693. get power() {
  32694. // compute the light's luminous power (in lumens) from its intensity (in candela)
  32695. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  32696. return this.intensity * Math.PI;
  32697. }
  32698. set power( power ) {
  32699. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  32700. this.intensity = power / Math.PI;
  32701. }
  32702. dispose() {
  32703. this.shadow.dispose();
  32704. }
  32705. copy( source, recursive ) {
  32706. super.copy( source, recursive );
  32707. this.distance = source.distance;
  32708. this.angle = source.angle;
  32709. this.penumbra = source.penumbra;
  32710. this.decay = source.decay;
  32711. this.target = source.target.clone();
  32712. this.shadow = source.shadow.clone();
  32713. return this;
  32714. }
  32715. }
  32716. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  32717. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  32718. const _lookTarget = /*@__PURE__*/ new Vector3();
  32719. /**
  32720. * Represents the shadow configuration of point lights.
  32721. *
  32722. * @augments LightShadow
  32723. */
  32724. class PointLightShadow extends LightShadow {
  32725. /**
  32726. * Constructs a new point light shadow.
  32727. */
  32728. constructor() {
  32729. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  32730. /**
  32731. * This flag can be used for type testing.
  32732. *
  32733. * @type {boolean}
  32734. * @readonly
  32735. * @default true
  32736. */
  32737. this.isPointLightShadow = true;
  32738. this._frameExtents = new Vector2( 4, 2 );
  32739. this._viewportCount = 6;
  32740. this._viewports = [
  32741. // These viewports map a cube-map onto a 2D texture with the
  32742. // following orientation:
  32743. //
  32744. // xzXZ
  32745. // y Y
  32746. //
  32747. // X - Positive x direction
  32748. // x - Negative x direction
  32749. // Y - Positive y direction
  32750. // y - Negative y direction
  32751. // Z - Positive z direction
  32752. // z - Negative z direction
  32753. // positive X
  32754. new Vector4( 2, 1, 1, 1 ),
  32755. // negative X
  32756. new Vector4( 0, 1, 1, 1 ),
  32757. // positive Z
  32758. new Vector4( 3, 1, 1, 1 ),
  32759. // negative Z
  32760. new Vector4( 1, 1, 1, 1 ),
  32761. // positive Y
  32762. new Vector4( 3, 0, 1, 1 ),
  32763. // negative Y
  32764. new Vector4( 1, 0, 1, 1 )
  32765. ];
  32766. this._cubeDirections = [
  32767. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  32768. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  32769. ];
  32770. this._cubeUps = [
  32771. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  32772. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  32773. ];
  32774. }
  32775. /**
  32776. * Update the matrices for the camera and shadow, used internally by the renderer.
  32777. *
  32778. * @param {Light} light - The light for which the shadow is being rendered.
  32779. * @param {number} [viewportIndex=0] - The viewport index.
  32780. */
  32781. updateMatrices( light, viewportIndex = 0 ) {
  32782. const camera = this.camera;
  32783. const shadowMatrix = this.matrix;
  32784. const far = light.distance || camera.far;
  32785. if ( far !== camera.far ) {
  32786. camera.far = far;
  32787. camera.updateProjectionMatrix();
  32788. }
  32789. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  32790. camera.position.copy( _lightPositionWorld );
  32791. _lookTarget.copy( camera.position );
  32792. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  32793. camera.up.copy( this._cubeUps[ viewportIndex ] );
  32794. camera.lookAt( _lookTarget );
  32795. camera.updateMatrixWorld();
  32796. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  32797. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  32798. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  32799. }
  32800. }
  32801. /**
  32802. * A light that gets emitted from a single point in all directions. A common
  32803. * use case for this is to replicate the light emitted from a bare
  32804. * lightbulb.
  32805. *
  32806. * This light can cast shadows - see the {@link PointLightShadow} for details.
  32807. *
  32808. * ```js
  32809. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  32810. * light.position.set( 50, 50, 50 );
  32811. * scene.add( light );
  32812. * ```
  32813. *
  32814. * @augments Light
  32815. */
  32816. class PointLight extends Light {
  32817. /**
  32818. * Constructs a new point light.
  32819. *
  32820. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32821. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  32822. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  32823. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  32824. */
  32825. constructor( color, intensity, distance = 0, decay = 2 ) {
  32826. super( color, intensity );
  32827. /**
  32828. * This flag can be used for type testing.
  32829. *
  32830. * @type {boolean}
  32831. * @readonly
  32832. * @default true
  32833. */
  32834. this.isPointLight = true;
  32835. this.type = 'PointLight';
  32836. /**
  32837. * When distance is zero, light will attenuate according to inverse-square
  32838. * law to infinite distance. When distance is non-zero, light will attenuate
  32839. * according to inverse-square law until near the distance cutoff, where it
  32840. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  32841. * physically correct.
  32842. *
  32843. * @type {number}
  32844. * @default 0
  32845. */
  32846. this.distance = distance;
  32847. /**
  32848. * The amount the light dims along the distance of the light. In context of
  32849. * physically-correct rendering the default value should not be changed.
  32850. *
  32851. * @type {number}
  32852. * @default 2
  32853. */
  32854. this.decay = decay;
  32855. /**
  32856. * This property holds the light's shadow configuration.
  32857. *
  32858. * @type {PointLightShadow}
  32859. */
  32860. this.shadow = new PointLightShadow();
  32861. }
  32862. /**
  32863. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  32864. * Changing the power will also change the light's intensity.
  32865. *
  32866. * @type {number}
  32867. */
  32868. get power() {
  32869. // compute the light's luminous power (in lumens) from its intensity (in candela)
  32870. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  32871. return this.intensity * 4 * Math.PI;
  32872. }
  32873. set power( power ) {
  32874. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  32875. this.intensity = power / ( 4 * Math.PI );
  32876. }
  32877. dispose() {
  32878. this.shadow.dispose();
  32879. }
  32880. copy( source, recursive ) {
  32881. super.copy( source, recursive );
  32882. this.distance = source.distance;
  32883. this.decay = source.decay;
  32884. this.shadow = source.shadow.clone();
  32885. return this;
  32886. }
  32887. }
  32888. /**
  32889. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  32890. *
  32891. * In this projection mode, an object's size in the rendered image stays
  32892. * constant regardless of its distance from the camera. This can be useful
  32893. * for rendering 2D scenes and UI elements, amongst other things.
  32894. *
  32895. * ```js
  32896. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  32897. * scene.add( camera );
  32898. * ```
  32899. *
  32900. * @augments Camera
  32901. */
  32902. class OrthographicCamera extends Camera {
  32903. /**
  32904. * Constructs a new orthographic camera.
  32905. *
  32906. * @param {number} [left=-1] - The left plane of the camera's frustum.
  32907. * @param {number} [right=1] - The right plane of the camera's frustum.
  32908. * @param {number} [top=1] - The top plane of the camera's frustum.
  32909. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  32910. * @param {number} [near=0.1] - The camera's near plane.
  32911. * @param {number} [far=2000] - The camera's far plane.
  32912. */
  32913. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  32914. super();
  32915. /**
  32916. * This flag can be used for type testing.
  32917. *
  32918. * @type {boolean}
  32919. * @readonly
  32920. * @default true
  32921. */
  32922. this.isOrthographicCamera = true;
  32923. this.type = 'OrthographicCamera';
  32924. /**
  32925. * The zoom factor of the camera.
  32926. *
  32927. * @type {number}
  32928. * @default 1
  32929. */
  32930. this.zoom = 1;
  32931. /**
  32932. * Represents the frustum window specification. This property should not be edited
  32933. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  32934. *
  32935. * @type {?Object}
  32936. * @default null
  32937. */
  32938. this.view = null;
  32939. /**
  32940. * The left plane of the camera's frustum.
  32941. *
  32942. * @type {number}
  32943. * @default -1
  32944. */
  32945. this.left = left;
  32946. /**
  32947. * The right plane of the camera's frustum.
  32948. *
  32949. * @type {number}
  32950. * @default 1
  32951. */
  32952. this.right = right;
  32953. /**
  32954. * The top plane of the camera's frustum.
  32955. *
  32956. * @type {number}
  32957. * @default 1
  32958. */
  32959. this.top = top;
  32960. /**
  32961. * The bottom plane of the camera's frustum.
  32962. *
  32963. * @type {number}
  32964. * @default -1
  32965. */
  32966. this.bottom = bottom;
  32967. /**
  32968. * The camera's near plane. The valid range is greater than `0`
  32969. * and less than the current value of {@link OrthographicCamera#far}.
  32970. *
  32971. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  32972. * valid value for an orthographic camera's near plane.
  32973. *
  32974. * @type {number}
  32975. * @default 0.1
  32976. */
  32977. this.near = near;
  32978. /**
  32979. * The camera's far plane. Must be greater than the
  32980. * current value of {@link OrthographicCamera#near}.
  32981. *
  32982. * @type {number}
  32983. * @default 2000
  32984. */
  32985. this.far = far;
  32986. this.updateProjectionMatrix();
  32987. }
  32988. copy( source, recursive ) {
  32989. super.copy( source, recursive );
  32990. this.left = source.left;
  32991. this.right = source.right;
  32992. this.top = source.top;
  32993. this.bottom = source.bottom;
  32994. this.near = source.near;
  32995. this.far = source.far;
  32996. this.zoom = source.zoom;
  32997. this.view = source.view === null ? null : Object.assign( {}, source.view );
  32998. return this;
  32999. }
  33000. /**
  33001. * Sets an offset in a larger frustum. This is useful for multi-window or
  33002. * multi-monitor/multi-machine setups.
  33003. *
  33004. * @param {number} fullWidth - The full width of multiview setup.
  33005. * @param {number} fullHeight - The full height of multiview setup.
  33006. * @param {number} x - The horizontal offset of the subcamera.
  33007. * @param {number} y - The vertical offset of the subcamera.
  33008. * @param {number} width - The width of subcamera.
  33009. * @param {number} height - The height of subcamera.
  33010. * @see {@link PerspectiveCamera#setViewOffset}
  33011. */
  33012. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33013. if ( this.view === null ) {
  33014. this.view = {
  33015. enabled: true,
  33016. fullWidth: 1,
  33017. fullHeight: 1,
  33018. offsetX: 0,
  33019. offsetY: 0,
  33020. width: 1,
  33021. height: 1
  33022. };
  33023. }
  33024. this.view.enabled = true;
  33025. this.view.fullWidth = fullWidth;
  33026. this.view.fullHeight = fullHeight;
  33027. this.view.offsetX = x;
  33028. this.view.offsetY = y;
  33029. this.view.width = width;
  33030. this.view.height = height;
  33031. this.updateProjectionMatrix();
  33032. }
  33033. /**
  33034. * Removes the view offset from the projection matrix.
  33035. */
  33036. clearViewOffset() {
  33037. if ( this.view !== null ) {
  33038. this.view.enabled = false;
  33039. }
  33040. this.updateProjectionMatrix();
  33041. }
  33042. /**
  33043. * Updates the camera's projection matrix. Must be called after any change of
  33044. * camera properties.
  33045. */
  33046. updateProjectionMatrix() {
  33047. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33048. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33049. const cx = ( this.right + this.left ) / 2;
  33050. const cy = ( this.top + this.bottom ) / 2;
  33051. let left = cx - dx;
  33052. let right = cx + dx;
  33053. let top = cy + dy;
  33054. let bottom = cy - dy;
  33055. if ( this.view !== null && this.view.enabled ) {
  33056. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33057. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33058. left += scaleW * this.view.offsetX;
  33059. right = left + scaleW * this.view.width;
  33060. top -= scaleH * this.view.offsetY;
  33061. bottom = top - scaleH * this.view.height;
  33062. }
  33063. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  33064. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33065. }
  33066. toJSON( meta ) {
  33067. const data = super.toJSON( meta );
  33068. data.object.zoom = this.zoom;
  33069. data.object.left = this.left;
  33070. data.object.right = this.right;
  33071. data.object.top = this.top;
  33072. data.object.bottom = this.bottom;
  33073. data.object.near = this.near;
  33074. data.object.far = this.far;
  33075. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33076. return data;
  33077. }
  33078. }
  33079. /**
  33080. * Represents the shadow configuration of directional lights.
  33081. *
  33082. * @augments LightShadow
  33083. */
  33084. class DirectionalLightShadow extends LightShadow {
  33085. /**
  33086. * Constructs a new directional light shadow.
  33087. */
  33088. constructor() {
  33089. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  33090. /**
  33091. * This flag can be used for type testing.
  33092. *
  33093. * @type {boolean}
  33094. * @readonly
  33095. * @default true
  33096. */
  33097. this.isDirectionalLightShadow = true;
  33098. }
  33099. }
  33100. /**
  33101. * A light that gets emitted in a specific direction. This light will behave
  33102. * as though it is infinitely far away and the rays produced from it are all
  33103. * parallel. The common use case for this is to simulate daylight; the sun is
  33104. * far enough away that its position can be considered to be infinite, and
  33105. * all light rays coming from it are parallel.
  33106. *
  33107. * A common point of confusion for directional lights is that setting the
  33108. * rotation has no effect. This is because three.js's DirectionalLight is the
  33109. * equivalent to what is often called a 'Target Direct Light' in other
  33110. * applications.
  33111. *
  33112. * This means that its direction is calculated as pointing from the light's
  33113. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33114. * (as opposed to a 'Free Direct Light' that just has a rotation
  33115. * component).
  33116. *
  33117. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33118. *
  33119. * ```js
  33120. * // White directional light at half intensity shining from the top.
  33121. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33122. * scene.add( directionalLight );
  33123. * ```
  33124. *
  33125. * @augments Light
  33126. */
  33127. class DirectionalLight extends Light {
  33128. /**
  33129. * Constructs a new directional light.
  33130. *
  33131. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33132. * @param {number} [intensity=1] - The light's strength/intensity.
  33133. */
  33134. constructor( color, intensity ) {
  33135. super( color, intensity );
  33136. /**
  33137. * This flag can be used for type testing.
  33138. *
  33139. * @type {boolean}
  33140. * @readonly
  33141. * @default true
  33142. */
  33143. this.isDirectionalLight = true;
  33144. this.type = 'DirectionalLight';
  33145. this.position.copy( Object3D.DEFAULT_UP );
  33146. this.updateMatrix();
  33147. /**
  33148. * The directional light points from its position to the
  33149. * target's position.
  33150. *
  33151. * For the target's position to be changed to anything other
  33152. * than the default, it must be added to the scene.
  33153. *
  33154. * It is also possible to set the target to be another 3D object
  33155. * in the scene. The light will now track the target object.
  33156. *
  33157. * @type {Object3D}
  33158. */
  33159. this.target = new Object3D();
  33160. /**
  33161. * This property holds the light's shadow configuration.
  33162. *
  33163. * @type {DirectionalLightShadow}
  33164. */
  33165. this.shadow = new DirectionalLightShadow();
  33166. }
  33167. dispose() {
  33168. this.shadow.dispose();
  33169. }
  33170. copy( source ) {
  33171. super.copy( source );
  33172. this.target = source.target.clone();
  33173. this.shadow = source.shadow.clone();
  33174. return this;
  33175. }
  33176. }
  33177. /**
  33178. * This light globally illuminates all objects in the scene equally.
  33179. *
  33180. * It cannot be used to cast shadows as it does not have a direction.
  33181. *
  33182. * ```js
  33183. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33184. * scene.add( light );
  33185. * ```
  33186. *
  33187. * @augments Light
  33188. */
  33189. class AmbientLight extends Light {
  33190. /**
  33191. * Constructs a new ambient light.
  33192. *
  33193. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33194. * @param {number} [intensity=1] - The light's strength/intensity.
  33195. */
  33196. constructor( color, intensity ) {
  33197. super( color, intensity );
  33198. /**
  33199. * This flag can be used for type testing.
  33200. *
  33201. * @type {boolean}
  33202. * @readonly
  33203. * @default true
  33204. */
  33205. this.isAmbientLight = true;
  33206. this.type = 'AmbientLight';
  33207. }
  33208. }
  33209. /**
  33210. * This class emits light uniformly across the face a rectangular plane.
  33211. * This light type can be used to simulate light sources such as bright
  33212. * windows or strip lighting.
  33213. *
  33214. * Important Notes:
  33215. *
  33216. * - There is no shadow support.
  33217. * - Only PBR materials are supported.
  33218. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33219. * into your app and init the uniforms/textures.
  33220. *
  33221. * ```js
  33222. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33223. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33224. *
  33225. * const intensity = 1; const width = 10; const height = 10;
  33226. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33227. * rectLight.position.set( 5, 5, 0 );
  33228. * rectLight.lookAt( 0, 0, 0 );
  33229. * scene.add( rectLight )
  33230. * ```
  33231. *
  33232. * @augments Light
  33233. */
  33234. class RectAreaLight extends Light {
  33235. /**
  33236. * Constructs a new area light.
  33237. *
  33238. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33239. * @param {number} [intensity=1] - The light's strength/intensity.
  33240. * @param {number} [width=10] - The width of the light.
  33241. * @param {number} [height=10] - The height of the light.
  33242. */
  33243. constructor( color, intensity, width = 10, height = 10 ) {
  33244. super( color, intensity );
  33245. /**
  33246. * This flag can be used for type testing.
  33247. *
  33248. * @type {boolean}
  33249. * @readonly
  33250. * @default true
  33251. */
  33252. this.isRectAreaLight = true;
  33253. this.type = 'RectAreaLight';
  33254. /**
  33255. * The width of the light.
  33256. *
  33257. * @type {number}
  33258. * @default 10
  33259. */
  33260. this.width = width;
  33261. /**
  33262. * The height of the light.
  33263. *
  33264. * @type {number}
  33265. * @default 10
  33266. */
  33267. this.height = height;
  33268. }
  33269. /**
  33270. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33271. * Changing the power will also change the light's intensity.
  33272. *
  33273. * @type {number}
  33274. */
  33275. get power() {
  33276. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33277. return this.intensity * this.width * this.height * Math.PI;
  33278. }
  33279. set power( power ) {
  33280. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33281. this.intensity = power / ( this.width * this.height * Math.PI );
  33282. }
  33283. copy( source ) {
  33284. super.copy( source );
  33285. this.width = source.width;
  33286. this.height = source.height;
  33287. return this;
  33288. }
  33289. toJSON( meta ) {
  33290. const data = super.toJSON( meta );
  33291. data.object.width = this.width;
  33292. data.object.height = this.height;
  33293. return data;
  33294. }
  33295. }
  33296. /**
  33297. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33298. * to encode lighting information.
  33299. *
  33300. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33301. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33302. */
  33303. class SphericalHarmonics3 {
  33304. /**
  33305. * Constructs a new spherical harmonics.
  33306. */
  33307. constructor() {
  33308. /**
  33309. * This flag can be used for type testing.
  33310. *
  33311. * @type {boolean}
  33312. * @readonly
  33313. * @default true
  33314. */
  33315. this.isSphericalHarmonics3 = true;
  33316. /**
  33317. * An array holding the (9) SH coefficients.
  33318. *
  33319. * @type {Array<Vector3>}
  33320. */
  33321. this.coefficients = [];
  33322. for ( let i = 0; i < 9; i ++ ) {
  33323. this.coefficients.push( new Vector3() );
  33324. }
  33325. }
  33326. /**
  33327. * Sets the given SH coefficients to this instance by copying
  33328. * the values.
  33329. *
  33330. * @param {Array<Vector3>} coefficients - The SH coefficients.
  33331. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33332. */
  33333. set( coefficients ) {
  33334. for ( let i = 0; i < 9; i ++ ) {
  33335. this.coefficients[ i ].copy( coefficients[ i ] );
  33336. }
  33337. return this;
  33338. }
  33339. /**
  33340. * Sets all SH coefficients to `0`.
  33341. *
  33342. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33343. */
  33344. zero() {
  33345. for ( let i = 0; i < 9; i ++ ) {
  33346. this.coefficients[ i ].set( 0, 0, 0 );
  33347. }
  33348. return this;
  33349. }
  33350. /**
  33351. * Returns the radiance in the direction of the given normal.
  33352. *
  33353. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33354. * @param {Vector3} target - The target vector that is used to store the method's result.
  33355. * @return {Vector3} The radiance.
  33356. */
  33357. getAt( normal, target ) {
  33358. // normal is assumed to be unit length
  33359. const x = normal.x, y = normal.y, z = normal.z;
  33360. const coeff = this.coefficients;
  33361. // band 0
  33362. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  33363. // band 1
  33364. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  33365. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  33366. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  33367. // band 2
  33368. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  33369. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  33370. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  33371. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  33372. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  33373. return target;
  33374. }
  33375. /**
  33376. * Returns the irradiance (radiance convolved with cosine lobe) in the
  33377. * direction of the given normal.
  33378. *
  33379. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33380. * @param {Vector3} target - The target vector that is used to store the method's result.
  33381. * @return {Vector3} The irradiance.
  33382. */
  33383. getIrradianceAt( normal, target ) {
  33384. // normal is assumed to be unit length
  33385. const x = normal.x, y = normal.y, z = normal.z;
  33386. const coeff = this.coefficients;
  33387. // band 0
  33388. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  33389. // band 1
  33390. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  33391. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  33392. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  33393. // band 2
  33394. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  33395. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  33396. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  33397. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  33398. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  33399. return target;
  33400. }
  33401. /**
  33402. * Adds the given SH to this instance.
  33403. *
  33404. * @param {SphericalHarmonics3} sh - The SH to add.
  33405. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33406. */
  33407. add( sh ) {
  33408. for ( let i = 0; i < 9; i ++ ) {
  33409. this.coefficients[ i ].add( sh.coefficients[ i ] );
  33410. }
  33411. return this;
  33412. }
  33413. /**
  33414. * A convenience method for performing {@link SphericalHarmonics3#add} and
  33415. * {@link SphericalHarmonics3#scale} at once.
  33416. *
  33417. * @param {SphericalHarmonics3} sh - The SH to add.
  33418. * @param {number} s - The scale factor.
  33419. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33420. */
  33421. addScaledSH( sh, s ) {
  33422. for ( let i = 0; i < 9; i ++ ) {
  33423. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  33424. }
  33425. return this;
  33426. }
  33427. /**
  33428. * Scales this SH by the given scale factor.
  33429. *
  33430. * @param {number} s - The scale factor.
  33431. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33432. */
  33433. scale( s ) {
  33434. for ( let i = 0; i < 9; i ++ ) {
  33435. this.coefficients[ i ].multiplyScalar( s );
  33436. }
  33437. return this;
  33438. }
  33439. /**
  33440. * Linear interpolates between the given SH and this instance by the given
  33441. * alpha factor.
  33442. *
  33443. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  33444. * @param {number} alpha - The alpha factor.
  33445. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33446. */
  33447. lerp( sh, alpha ) {
  33448. for ( let i = 0; i < 9; i ++ ) {
  33449. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  33450. }
  33451. return this;
  33452. }
  33453. /**
  33454. * Returns `true` if this spherical harmonics is equal with the given one.
  33455. *
  33456. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  33457. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  33458. */
  33459. equals( sh ) {
  33460. for ( let i = 0; i < 9; i ++ ) {
  33461. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  33462. return false;
  33463. }
  33464. }
  33465. return true;
  33466. }
  33467. /**
  33468. * Copies the values of the given spherical harmonics to this instance.
  33469. *
  33470. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  33471. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33472. */
  33473. copy( sh ) {
  33474. return this.set( sh.coefficients );
  33475. }
  33476. /**
  33477. * Returns a new spherical harmonics with copied values from this instance.
  33478. *
  33479. * @return {SphericalHarmonics3} A clone of this instance.
  33480. */
  33481. clone() {
  33482. return new this.constructor().copy( this );
  33483. }
  33484. /**
  33485. * Sets the SH coefficients of this instance from the given array.
  33486. *
  33487. * @param {Array<number>} array - An array holding the SH coefficients.
  33488. * @param {number} [offset=0] - The array offset where to start copying.
  33489. * @return {SphericalHarmonics3} A clone of this instance.
  33490. */
  33491. fromArray( array, offset = 0 ) {
  33492. const coefficients = this.coefficients;
  33493. for ( let i = 0; i < 9; i ++ ) {
  33494. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  33495. }
  33496. return this;
  33497. }
  33498. /**
  33499. * Returns an array with the SH coefficients, or copies them into the provided
  33500. * array. The coefficients are represented as numbers.
  33501. *
  33502. * @param {Array<number>} [array=[]] - The target array.
  33503. * @param {number} [offset=0] - The array offset where to start copying.
  33504. * @return {Array<number>} An array with flat SH coefficients.
  33505. */
  33506. toArray( array = [], offset = 0 ) {
  33507. const coefficients = this.coefficients;
  33508. for ( let i = 0; i < 9; i ++ ) {
  33509. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  33510. }
  33511. return array;
  33512. }
  33513. /**
  33514. * Computes the SH basis for the given normal vector.
  33515. *
  33516. * @param {Vector3} normal - The normal.
  33517. * @param {Array<number>} shBasis - The target array holding the SH basis.
  33518. */
  33519. static getBasisAt( normal, shBasis ) {
  33520. // normal is assumed to be unit length
  33521. const x = normal.x, y = normal.y, z = normal.z;
  33522. // band 0
  33523. shBasis[ 0 ] = 0.282095;
  33524. // band 1
  33525. shBasis[ 1 ] = 0.488603 * y;
  33526. shBasis[ 2 ] = 0.488603 * z;
  33527. shBasis[ 3 ] = 0.488603 * x;
  33528. // band 2
  33529. shBasis[ 4 ] = 1.092548 * x * y;
  33530. shBasis[ 5 ] = 1.092548 * y * z;
  33531. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  33532. shBasis[ 7 ] = 1.092548 * x * z;
  33533. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  33534. }
  33535. }
  33536. /**
  33537. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  33538. * classical light sources (e.g. directional, point or spot lights), light
  33539. * probes do not emit light. Instead they store information about light
  33540. * passing through 3D space. During rendering, the light that hits a 3D
  33541. * object is approximated by using the data from the light probe.
  33542. *
  33543. * Light probes are usually created from (radiance) environment maps. The
  33544. * class {@link LightProbeGenerator} can be used to create light probes from
  33545. * cube textures or render targets. However, light estimation data could also
  33546. * be provided in other forms e.g. by WebXR. This enables the rendering of
  33547. * augmented reality content that reacts to real world lighting.
  33548. *
  33549. * The current probe implementation in three.js supports so-called diffuse
  33550. * light probes. This type of light probe is functionally equivalent to an
  33551. * irradiance environment map.
  33552. *
  33553. * @augments Light
  33554. */
  33555. class LightProbe extends Light {
  33556. /**
  33557. * Constructs a new light probe.
  33558. *
  33559. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  33560. * @param {number} [intensity=1] - The light's strength/intensity.
  33561. */
  33562. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  33563. super( undefined, intensity );
  33564. /**
  33565. * This flag can be used for type testing.
  33566. *
  33567. * @type {boolean}
  33568. * @readonly
  33569. * @default true
  33570. */
  33571. this.isLightProbe = true;
  33572. /**
  33573. * A light probe uses spherical harmonics to encode lighting information.
  33574. *
  33575. * @type {SphericalHarmonics3}
  33576. */
  33577. this.sh = sh;
  33578. }
  33579. copy( source ) {
  33580. super.copy( source );
  33581. this.sh.copy( source.sh );
  33582. return this;
  33583. }
  33584. /**
  33585. * Deserializes the light prove from the given JSON.
  33586. *
  33587. * @param {Object} json - The JSON holding the serialized light probe.
  33588. * @return {LightProbe} A reference to this light probe.
  33589. */
  33590. fromJSON( json ) {
  33591. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  33592. this.sh.fromArray( json.sh );
  33593. return this;
  33594. }
  33595. toJSON( meta ) {
  33596. const data = super.toJSON( meta );
  33597. data.object.sh = this.sh.toArray();
  33598. return data;
  33599. }
  33600. }
  33601. /**
  33602. * Class for loading geometries. The files are internally
  33603. * loaded via {@link FileLoader}.
  33604. *
  33605. * ```js
  33606. * const loader = new THREE.MaterialLoader();
  33607. * const material = await loader.loadAsync( 'material.json' );
  33608. * ```
  33609. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  33610. *
  33611. * @augments Loader
  33612. */
  33613. class MaterialLoader extends Loader {
  33614. /**
  33615. * Constructs a new material loader.
  33616. *
  33617. * @param {LoadingManager} [manager] - The loading manager.
  33618. */
  33619. constructor( manager ) {
  33620. super( manager );
  33621. /**
  33622. * A dictionary holding textures used by the material.
  33623. *
  33624. * @type {Object<string,Texture>}
  33625. */
  33626. this.textures = {};
  33627. }
  33628. /**
  33629. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  33630. *
  33631. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33632. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  33633. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33634. * @param {onErrorCallback} onError - Executed when errors occur.
  33635. */
  33636. load( url, onLoad, onProgress, onError ) {
  33637. const scope = this;
  33638. const loader = new FileLoader( scope.manager );
  33639. loader.setPath( scope.path );
  33640. loader.setRequestHeader( scope.requestHeader );
  33641. loader.setWithCredentials( scope.withCredentials );
  33642. loader.load( url, function ( text ) {
  33643. try {
  33644. onLoad( scope.parse( JSON.parse( text ) ) );
  33645. } catch ( e ) {
  33646. if ( onError ) {
  33647. onError( e );
  33648. } else {
  33649. console.error( e );
  33650. }
  33651. scope.manager.itemError( url );
  33652. }
  33653. }, onProgress, onError );
  33654. }
  33655. /**
  33656. * Parses the given JSON object and returns a material.
  33657. *
  33658. * @param {Object} json - The serialized material.
  33659. * @return {Material} The parsed material.
  33660. */
  33661. parse( json ) {
  33662. const textures = this.textures;
  33663. function getTexture( name ) {
  33664. if ( textures[ name ] === undefined ) {
  33665. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  33666. }
  33667. return textures[ name ];
  33668. }
  33669. const material = this.createMaterialFromType( json.type );
  33670. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  33671. if ( json.name !== undefined ) material.name = json.name;
  33672. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  33673. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  33674. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  33675. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  33676. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  33677. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  33678. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  33679. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  33680. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  33681. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  33682. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  33683. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  33684. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  33685. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  33686. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  33687. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  33688. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  33689. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  33690. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  33691. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  33692. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  33693. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  33694. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  33695. if ( json.fog !== undefined ) material.fog = json.fog;
  33696. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  33697. if ( json.blending !== undefined ) material.blending = json.blending;
  33698. if ( json.combine !== undefined ) material.combine = json.combine;
  33699. if ( json.side !== undefined ) material.side = json.side;
  33700. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  33701. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  33702. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  33703. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  33704. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  33705. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  33706. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  33707. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  33708. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  33709. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  33710. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  33711. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  33712. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  33713. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  33714. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  33715. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  33716. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  33717. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  33718. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  33719. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  33720. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  33721. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  33722. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  33723. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  33724. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  33725. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  33726. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  33727. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  33728. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  33729. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  33730. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  33731. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  33732. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  33733. if ( json.scale !== undefined ) material.scale = json.scale;
  33734. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  33735. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  33736. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  33737. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  33738. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  33739. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  33740. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  33741. if ( json.visible !== undefined ) material.visible = json.visible;
  33742. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  33743. if ( json.userData !== undefined ) material.userData = json.userData;
  33744. if ( json.vertexColors !== undefined ) {
  33745. if ( typeof json.vertexColors === 'number' ) {
  33746. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  33747. } else {
  33748. material.vertexColors = json.vertexColors;
  33749. }
  33750. }
  33751. // Shader Material
  33752. if ( json.uniforms !== undefined ) {
  33753. for ( const name in json.uniforms ) {
  33754. const uniform = json.uniforms[ name ];
  33755. material.uniforms[ name ] = {};
  33756. switch ( uniform.type ) {
  33757. case 't':
  33758. material.uniforms[ name ].value = getTexture( uniform.value );
  33759. break;
  33760. case 'c':
  33761. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  33762. break;
  33763. case 'v2':
  33764. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  33765. break;
  33766. case 'v3':
  33767. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  33768. break;
  33769. case 'v4':
  33770. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  33771. break;
  33772. case 'm3':
  33773. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  33774. break;
  33775. case 'm4':
  33776. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  33777. break;
  33778. default:
  33779. material.uniforms[ name ].value = uniform.value;
  33780. }
  33781. }
  33782. }
  33783. if ( json.defines !== undefined ) material.defines = json.defines;
  33784. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  33785. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  33786. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  33787. if ( json.extensions !== undefined ) {
  33788. for ( const key in json.extensions ) {
  33789. material.extensions[ key ] = json.extensions[ key ];
  33790. }
  33791. }
  33792. if ( json.lights !== undefined ) material.lights = json.lights;
  33793. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  33794. // for PointsMaterial
  33795. if ( json.size !== undefined ) material.size = json.size;
  33796. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  33797. // maps
  33798. if ( json.map !== undefined ) material.map = getTexture( json.map );
  33799. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  33800. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  33801. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  33802. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  33803. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  33804. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  33805. if ( json.normalScale !== undefined ) {
  33806. let normalScale = json.normalScale;
  33807. if ( Array.isArray( normalScale ) === false ) {
  33808. // Blender exporter used to export a scalar. See #7459
  33809. normalScale = [ normalScale, normalScale ];
  33810. }
  33811. material.normalScale = new Vector2().fromArray( normalScale );
  33812. }
  33813. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  33814. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  33815. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  33816. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  33817. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  33818. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  33819. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  33820. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  33821. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  33822. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  33823. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  33824. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  33825. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  33826. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  33827. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  33828. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  33829. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  33830. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  33831. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  33832. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  33833. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  33834. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  33835. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  33836. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  33837. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  33838. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  33839. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  33840. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  33841. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  33842. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  33843. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  33844. return material;
  33845. }
  33846. /**
  33847. * Textures are not embedded in the material JSON so they have
  33848. * to be injected before the loading process starts.
  33849. *
  33850. * @param {Object} value - A dictionary holding textures for material properties.
  33851. * @return {MaterialLoader} A reference to this material loader.
  33852. */
  33853. setTextures( value ) {
  33854. this.textures = value;
  33855. return this;
  33856. }
  33857. /**
  33858. * Creates a material for the given type.
  33859. *
  33860. * @param {string} type - The material type.
  33861. * @return {Material} The new material.
  33862. */
  33863. createMaterialFromType( type ) {
  33864. return MaterialLoader.createMaterialFromType( type );
  33865. }
  33866. /**
  33867. * Creates a material for the given type.
  33868. *
  33869. * @static
  33870. * @param {string} type - The material type.
  33871. * @return {Material} The new material.
  33872. */
  33873. static createMaterialFromType( type ) {
  33874. const materialLib = {
  33875. ShadowMaterial,
  33876. SpriteMaterial,
  33877. RawShaderMaterial,
  33878. ShaderMaterial,
  33879. PointsMaterial,
  33880. MeshPhysicalMaterial,
  33881. MeshStandardMaterial,
  33882. MeshPhongMaterial,
  33883. MeshToonMaterial,
  33884. MeshNormalMaterial,
  33885. MeshLambertMaterial,
  33886. MeshDepthMaterial,
  33887. MeshDistanceMaterial,
  33888. MeshBasicMaterial,
  33889. MeshMatcapMaterial,
  33890. LineDashedMaterial,
  33891. LineBasicMaterial,
  33892. Material
  33893. };
  33894. return new materialLib[ type ]();
  33895. }
  33896. }
  33897. /**
  33898. * A class with loader utility functions.
  33899. */
  33900. class LoaderUtils {
  33901. /**
  33902. * Extracts the base URL from the given URL.
  33903. *
  33904. * @param {string} url -The URL to extract the base URL from.
  33905. * @return {string} The extracted base URL.
  33906. */
  33907. static extractUrlBase( url ) {
  33908. const index = url.lastIndexOf( '/' );
  33909. if ( index === - 1 ) return './';
  33910. return url.slice( 0, index + 1 );
  33911. }
  33912. /**
  33913. * Resolves relative URLs against the given path. Absolute paths, data urls,
  33914. * and blob URLs will be returned as is. Invalid URLs will return an empty
  33915. * string.
  33916. *
  33917. * @param {string} url -The URL to resolve.
  33918. * @param {string} path - The base path for relative URLs to be resolved against.
  33919. * @return {string} The resolved URL.
  33920. */
  33921. static resolveURL( url, path ) {
  33922. // Invalid URL
  33923. if ( typeof url !== 'string' || url === '' ) return '';
  33924. // Host Relative URL
  33925. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  33926. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  33927. }
  33928. // Absolute URL http://,https://,//
  33929. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  33930. // Data URI
  33931. if ( /^data:.*,.*$/i.test( url ) ) return url;
  33932. // Blob URL
  33933. if ( /^blob:.*$/i.test( url ) ) return url;
  33934. // Relative URL
  33935. return path + url;
  33936. }
  33937. }
  33938. /**
  33939. * An instanced version of a geometry.
  33940. */
  33941. class InstancedBufferGeometry extends BufferGeometry {
  33942. /**
  33943. * Constructs a new instanced buffer geometry.
  33944. */
  33945. constructor() {
  33946. super();
  33947. /**
  33948. * This flag can be used for type testing.
  33949. *
  33950. * @type {boolean}
  33951. * @readonly
  33952. * @default true
  33953. */
  33954. this.isInstancedBufferGeometry = true;
  33955. this.type = 'InstancedBufferGeometry';
  33956. /**
  33957. * The instance count.
  33958. *
  33959. * @type {number}
  33960. * @default Infinity
  33961. */
  33962. this.instanceCount = Infinity;
  33963. }
  33964. copy( source ) {
  33965. super.copy( source );
  33966. this.instanceCount = source.instanceCount;
  33967. return this;
  33968. }
  33969. toJSON() {
  33970. const data = super.toJSON();
  33971. data.instanceCount = this.instanceCount;
  33972. data.isInstancedBufferGeometry = true;
  33973. return data;
  33974. }
  33975. }
  33976. /**
  33977. * Class for loading geometries. The files are internally
  33978. * loaded via {@link FileLoader}.
  33979. *
  33980. * ```js
  33981. * const loader = new THREE.BufferGeometryLoader();
  33982. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  33983. *
  33984. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  33985. * const object = new THREE.Mesh( geometry, material );
  33986. * scene.add( object );
  33987. * ```
  33988. *
  33989. * @augments Loader
  33990. */
  33991. class BufferGeometryLoader extends Loader {
  33992. /**
  33993. * Constructs a new geometry loader.
  33994. *
  33995. * @param {LoadingManager} [manager] - The loading manager.
  33996. */
  33997. constructor( manager ) {
  33998. super( manager );
  33999. }
  34000. /**
  34001. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34002. *
  34003. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34004. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34005. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34006. * @param {onErrorCallback} onError - Executed when errors occur.
  34007. */
  34008. load( url, onLoad, onProgress, onError ) {
  34009. const scope = this;
  34010. const loader = new FileLoader( scope.manager );
  34011. loader.setPath( scope.path );
  34012. loader.setRequestHeader( scope.requestHeader );
  34013. loader.setWithCredentials( scope.withCredentials );
  34014. loader.load( url, function ( text ) {
  34015. try {
  34016. onLoad( scope.parse( JSON.parse( text ) ) );
  34017. } catch ( e ) {
  34018. if ( onError ) {
  34019. onError( e );
  34020. } else {
  34021. console.error( e );
  34022. }
  34023. scope.manager.itemError( url );
  34024. }
  34025. }, onProgress, onError );
  34026. }
  34027. /**
  34028. * Parses the given JSON object and returns a geometry.
  34029. *
  34030. * @param {Object} json - The serialized geometry.
  34031. * @return {BufferGeometry} The parsed geometry.
  34032. */
  34033. parse( json ) {
  34034. const interleavedBufferMap = {};
  34035. const arrayBufferMap = {};
  34036. function getInterleavedBuffer( json, uuid ) {
  34037. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34038. const interleavedBuffers = json.interleavedBuffers;
  34039. const interleavedBuffer = interleavedBuffers[ uuid ];
  34040. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34041. const array = getTypedArray( interleavedBuffer.type, buffer );
  34042. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34043. ib.uuid = interleavedBuffer.uuid;
  34044. interleavedBufferMap[ uuid ] = ib;
  34045. return ib;
  34046. }
  34047. function getArrayBuffer( json, uuid ) {
  34048. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34049. const arrayBuffers = json.arrayBuffers;
  34050. const arrayBuffer = arrayBuffers[ uuid ];
  34051. const ab = new Uint32Array( arrayBuffer ).buffer;
  34052. arrayBufferMap[ uuid ] = ab;
  34053. return ab;
  34054. }
  34055. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34056. const index = json.data.index;
  34057. if ( index !== undefined ) {
  34058. const typedArray = getTypedArray( index.type, index.array );
  34059. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34060. }
  34061. const attributes = json.data.attributes;
  34062. for ( const key in attributes ) {
  34063. const attribute = attributes[ key ];
  34064. let bufferAttribute;
  34065. if ( attribute.isInterleavedBufferAttribute ) {
  34066. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34067. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34068. } else {
  34069. const typedArray = getTypedArray( attribute.type, attribute.array );
  34070. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34071. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34072. }
  34073. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34074. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34075. geometry.setAttribute( key, bufferAttribute );
  34076. }
  34077. const morphAttributes = json.data.morphAttributes;
  34078. if ( morphAttributes ) {
  34079. for ( const key in morphAttributes ) {
  34080. const attributeArray = morphAttributes[ key ];
  34081. const array = [];
  34082. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34083. const attribute = attributeArray[ i ];
  34084. let bufferAttribute;
  34085. if ( attribute.isInterleavedBufferAttribute ) {
  34086. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34087. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34088. } else {
  34089. const typedArray = getTypedArray( attribute.type, attribute.array );
  34090. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34091. }
  34092. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34093. array.push( bufferAttribute );
  34094. }
  34095. geometry.morphAttributes[ key ] = array;
  34096. }
  34097. }
  34098. const morphTargetsRelative = json.data.morphTargetsRelative;
  34099. if ( morphTargetsRelative ) {
  34100. geometry.morphTargetsRelative = true;
  34101. }
  34102. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34103. if ( groups !== undefined ) {
  34104. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34105. const group = groups[ i ];
  34106. geometry.addGroup( group.start, group.count, group.materialIndex );
  34107. }
  34108. }
  34109. const boundingSphere = json.data.boundingSphere;
  34110. if ( boundingSphere !== undefined ) {
  34111. const center = new Vector3();
  34112. if ( boundingSphere.center !== undefined ) {
  34113. center.fromArray( boundingSphere.center );
  34114. }
  34115. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  34116. }
  34117. if ( json.name ) geometry.name = json.name;
  34118. if ( json.userData ) geometry.userData = json.userData;
  34119. return geometry;
  34120. }
  34121. }
  34122. /**
  34123. * A loader for loading a JSON resource in the [JSON Object/Scene format]{@link https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4}.
  34124. * The files are internally loaded via {@link FileLoader}.
  34125. *
  34126. * ```js
  34127. * const loader = new THREE.ObjectLoader();
  34128. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34129. * scene.add( obj );
  34130. *
  34131. * // Alternatively, to parse a previously loaded JSON structure
  34132. * const object = await loader.parseAsync( a_json_object );
  34133. * scene.add( object );
  34134. * ```
  34135. *
  34136. * @augments Loader
  34137. */
  34138. class ObjectLoader extends Loader {
  34139. /**
  34140. * Constructs a new object loader.
  34141. *
  34142. * @param {LoadingManager} [manager] - The loading manager.
  34143. */
  34144. constructor( manager ) {
  34145. super( manager );
  34146. }
  34147. /**
  34148. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34149. *
  34150. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34151. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34152. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34153. * @param {onErrorCallback} onError - Executed when errors occur.
  34154. */
  34155. load( url, onLoad, onProgress, onError ) {
  34156. const scope = this;
  34157. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34158. this.resourcePath = this.resourcePath || path;
  34159. const loader = new FileLoader( this.manager );
  34160. loader.setPath( this.path );
  34161. loader.setRequestHeader( this.requestHeader );
  34162. loader.setWithCredentials( this.withCredentials );
  34163. loader.load( url, function ( text ) {
  34164. let json = null;
  34165. try {
  34166. json = JSON.parse( text );
  34167. } catch ( error ) {
  34168. if ( onError !== undefined ) onError( error );
  34169. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34170. return;
  34171. }
  34172. const metadata = json.metadata;
  34173. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34174. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34175. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34176. return;
  34177. }
  34178. scope.parse( json, onLoad );
  34179. }, onProgress, onError );
  34180. }
  34181. /**
  34182. * Async version of {@link ObjectLoader#load}.
  34183. *
  34184. * @async
  34185. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34186. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34187. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34188. */
  34189. async loadAsync( url, onProgress ) {
  34190. const scope = this;
  34191. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34192. this.resourcePath = this.resourcePath || path;
  34193. const loader = new FileLoader( this.manager );
  34194. loader.setPath( this.path );
  34195. loader.setRequestHeader( this.requestHeader );
  34196. loader.setWithCredentials( this.withCredentials );
  34197. const text = await loader.loadAsync( url, onProgress );
  34198. const json = JSON.parse( text );
  34199. const metadata = json.metadata;
  34200. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34201. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34202. }
  34203. return await scope.parseAsync( json );
  34204. }
  34205. /**
  34206. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34207. * but can also be used directly to parse a previously loaded JSON structure.
  34208. *
  34209. * @param {Object} json - The serialized 3D object.
  34210. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34211. * @return {Object3D} The parsed 3D object.
  34212. */
  34213. parse( json, onLoad ) {
  34214. const animations = this.parseAnimations( json.animations );
  34215. const shapes = this.parseShapes( json.shapes );
  34216. const geometries = this.parseGeometries( json.geometries, shapes );
  34217. const images = this.parseImages( json.images, function () {
  34218. if ( onLoad !== undefined ) onLoad( object );
  34219. } );
  34220. const textures = this.parseTextures( json.textures, images );
  34221. const materials = this.parseMaterials( json.materials, textures );
  34222. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34223. const skeletons = this.parseSkeletons( json.skeletons, object );
  34224. this.bindSkeletons( object, skeletons );
  34225. this.bindLightTargets( object );
  34226. //
  34227. if ( onLoad !== undefined ) {
  34228. let hasImages = false;
  34229. for ( const uuid in images ) {
  34230. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34231. hasImages = true;
  34232. break;
  34233. }
  34234. }
  34235. if ( hasImages === false ) onLoad( object );
  34236. }
  34237. return object;
  34238. }
  34239. /**
  34240. * Async version of {@link ObjectLoader#parse}.
  34241. *
  34242. * @param {Object} json - The serialized 3D object.
  34243. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34244. */
  34245. async parseAsync( json ) {
  34246. const animations = this.parseAnimations( json.animations );
  34247. const shapes = this.parseShapes( json.shapes );
  34248. const geometries = this.parseGeometries( json.geometries, shapes );
  34249. const images = await this.parseImagesAsync( json.images );
  34250. const textures = this.parseTextures( json.textures, images );
  34251. const materials = this.parseMaterials( json.materials, textures );
  34252. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34253. const skeletons = this.parseSkeletons( json.skeletons, object );
  34254. this.bindSkeletons( object, skeletons );
  34255. this.bindLightTargets( object );
  34256. return object;
  34257. }
  34258. // internals
  34259. parseShapes( json ) {
  34260. const shapes = {};
  34261. if ( json !== undefined ) {
  34262. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34263. const shape = new Shape().fromJSON( json[ i ] );
  34264. shapes[ shape.uuid ] = shape;
  34265. }
  34266. }
  34267. return shapes;
  34268. }
  34269. parseSkeletons( json, object ) {
  34270. const skeletons = {};
  34271. const bones = {};
  34272. // generate bone lookup table
  34273. object.traverse( function ( child ) {
  34274. if ( child.isBone ) bones[ child.uuid ] = child;
  34275. } );
  34276. // create skeletons
  34277. if ( json !== undefined ) {
  34278. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34279. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34280. skeletons[ skeleton.uuid ] = skeleton;
  34281. }
  34282. }
  34283. return skeletons;
  34284. }
  34285. parseGeometries( json, shapes ) {
  34286. const geometries = {};
  34287. if ( json !== undefined ) {
  34288. const bufferGeometryLoader = new BufferGeometryLoader();
  34289. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34290. let geometry;
  34291. const data = json[ i ];
  34292. switch ( data.type ) {
  34293. case 'BufferGeometry':
  34294. case 'InstancedBufferGeometry':
  34295. geometry = bufferGeometryLoader.parse( data );
  34296. break;
  34297. default:
  34298. if ( data.type in Geometries ) {
  34299. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34300. } else {
  34301. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34302. }
  34303. }
  34304. geometry.uuid = data.uuid;
  34305. if ( data.name !== undefined ) geometry.name = data.name;
  34306. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34307. geometries[ data.uuid ] = geometry;
  34308. }
  34309. }
  34310. return geometries;
  34311. }
  34312. parseMaterials( json, textures ) {
  34313. const cache = {}; // MultiMaterial
  34314. const materials = {};
  34315. if ( json !== undefined ) {
  34316. const loader = new MaterialLoader();
  34317. loader.setTextures( textures );
  34318. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34319. const data = json[ i ];
  34320. if ( cache[ data.uuid ] === undefined ) {
  34321. cache[ data.uuid ] = loader.parse( data );
  34322. }
  34323. materials[ data.uuid ] = cache[ data.uuid ];
  34324. }
  34325. }
  34326. return materials;
  34327. }
  34328. parseAnimations( json ) {
  34329. const animations = {};
  34330. if ( json !== undefined ) {
  34331. for ( let i = 0; i < json.length; i ++ ) {
  34332. const data = json[ i ];
  34333. const clip = AnimationClip.parse( data );
  34334. animations[ clip.uuid ] = clip;
  34335. }
  34336. }
  34337. return animations;
  34338. }
  34339. parseImages( json, onLoad ) {
  34340. const scope = this;
  34341. const images = {};
  34342. let loader;
  34343. function loadImage( url ) {
  34344. scope.manager.itemStart( url );
  34345. return loader.load( url, function () {
  34346. scope.manager.itemEnd( url );
  34347. }, undefined, function () {
  34348. scope.manager.itemError( url );
  34349. scope.manager.itemEnd( url );
  34350. } );
  34351. }
  34352. function deserializeImage( image ) {
  34353. if ( typeof image === 'string' ) {
  34354. const url = image;
  34355. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34356. return loadImage( path );
  34357. } else {
  34358. if ( image.data ) {
  34359. return {
  34360. data: getTypedArray( image.type, image.data ),
  34361. width: image.width,
  34362. height: image.height
  34363. };
  34364. } else {
  34365. return null;
  34366. }
  34367. }
  34368. }
  34369. if ( json !== undefined && json.length > 0 ) {
  34370. const manager = new LoadingManager( onLoad );
  34371. loader = new ImageLoader( manager );
  34372. loader.setCrossOrigin( this.crossOrigin );
  34373. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34374. const image = json[ i ];
  34375. const url = image.url;
  34376. if ( Array.isArray( url ) ) {
  34377. // load array of images e.g CubeTexture
  34378. const imageArray = [];
  34379. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34380. const currentUrl = url[ j ];
  34381. const deserializedImage = deserializeImage( currentUrl );
  34382. if ( deserializedImage !== null ) {
  34383. if ( deserializedImage instanceof HTMLImageElement ) {
  34384. imageArray.push( deserializedImage );
  34385. } else {
  34386. // special case: handle array of data textures for cube textures
  34387. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34388. }
  34389. }
  34390. }
  34391. images[ image.uuid ] = new Source( imageArray );
  34392. } else {
  34393. // load single image
  34394. const deserializedImage = deserializeImage( image.url );
  34395. images[ image.uuid ] = new Source( deserializedImage );
  34396. }
  34397. }
  34398. }
  34399. return images;
  34400. }
  34401. async parseImagesAsync( json ) {
  34402. const scope = this;
  34403. const images = {};
  34404. let loader;
  34405. async function deserializeImage( image ) {
  34406. if ( typeof image === 'string' ) {
  34407. const url = image;
  34408. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34409. return await loader.loadAsync( path );
  34410. } else {
  34411. if ( image.data ) {
  34412. return {
  34413. data: getTypedArray( image.type, image.data ),
  34414. width: image.width,
  34415. height: image.height
  34416. };
  34417. } else {
  34418. return null;
  34419. }
  34420. }
  34421. }
  34422. if ( json !== undefined && json.length > 0 ) {
  34423. loader = new ImageLoader( this.manager );
  34424. loader.setCrossOrigin( this.crossOrigin );
  34425. for ( let i = 0, il = json.length; i < il; i ++ ) {
  34426. const image = json[ i ];
  34427. const url = image.url;
  34428. if ( Array.isArray( url ) ) {
  34429. // load array of images e.g CubeTexture
  34430. const imageArray = [];
  34431. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  34432. const currentUrl = url[ j ];
  34433. const deserializedImage = await deserializeImage( currentUrl );
  34434. if ( deserializedImage !== null ) {
  34435. if ( deserializedImage instanceof HTMLImageElement ) {
  34436. imageArray.push( deserializedImage );
  34437. } else {
  34438. // special case: handle array of data textures for cube textures
  34439. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  34440. }
  34441. }
  34442. }
  34443. images[ image.uuid ] = new Source( imageArray );
  34444. } else {
  34445. // load single image
  34446. const deserializedImage = await deserializeImage( image.url );
  34447. images[ image.uuid ] = new Source( deserializedImage );
  34448. }
  34449. }
  34450. }
  34451. return images;
  34452. }
  34453. parseTextures( json, images ) {
  34454. function parseConstant( value, type ) {
  34455. if ( typeof value === 'number' ) return value;
  34456. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  34457. return type[ value ];
  34458. }
  34459. const textures = {};
  34460. if ( json !== undefined ) {
  34461. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34462. const data = json[ i ];
  34463. if ( data.image === undefined ) {
  34464. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  34465. }
  34466. if ( images[ data.image ] === undefined ) {
  34467. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  34468. }
  34469. const source = images[ data.image ];
  34470. const image = source.data;
  34471. let texture;
  34472. if ( Array.isArray( image ) ) {
  34473. texture = new CubeTexture();
  34474. if ( image.length === 6 ) texture.needsUpdate = true;
  34475. } else {
  34476. if ( image && image.data ) {
  34477. texture = new DataTexture();
  34478. } else {
  34479. texture = new Texture();
  34480. }
  34481. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  34482. }
  34483. texture.source = source;
  34484. texture.uuid = data.uuid;
  34485. if ( data.name !== undefined ) texture.name = data.name;
  34486. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  34487. if ( data.channel !== undefined ) texture.channel = data.channel;
  34488. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  34489. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  34490. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  34491. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  34492. if ( data.wrap !== undefined ) {
  34493. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  34494. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  34495. }
  34496. if ( data.format !== undefined ) texture.format = data.format;
  34497. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  34498. if ( data.type !== undefined ) texture.type = data.type;
  34499. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  34500. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  34501. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  34502. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  34503. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  34504. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  34505. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  34506. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  34507. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  34508. if ( data.userData !== undefined ) texture.userData = data.userData;
  34509. textures[ data.uuid ] = texture;
  34510. }
  34511. }
  34512. return textures;
  34513. }
  34514. parseObject( data, geometries, materials, textures, animations ) {
  34515. let object;
  34516. function getGeometry( name ) {
  34517. if ( geometries[ name ] === undefined ) {
  34518. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  34519. }
  34520. return geometries[ name ];
  34521. }
  34522. function getMaterial( name ) {
  34523. if ( name === undefined ) return undefined;
  34524. if ( Array.isArray( name ) ) {
  34525. const array = [];
  34526. for ( let i = 0, l = name.length; i < l; i ++ ) {
  34527. const uuid = name[ i ];
  34528. if ( materials[ uuid ] === undefined ) {
  34529. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  34530. }
  34531. array.push( materials[ uuid ] );
  34532. }
  34533. return array;
  34534. }
  34535. if ( materials[ name ] === undefined ) {
  34536. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  34537. }
  34538. return materials[ name ];
  34539. }
  34540. function getTexture( uuid ) {
  34541. if ( textures[ uuid ] === undefined ) {
  34542. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  34543. }
  34544. return textures[ uuid ];
  34545. }
  34546. let geometry, material;
  34547. switch ( data.type ) {
  34548. case 'Scene':
  34549. object = new Scene();
  34550. if ( data.background !== undefined ) {
  34551. if ( Number.isInteger( data.background ) ) {
  34552. object.background = new Color( data.background );
  34553. } else {
  34554. object.background = getTexture( data.background );
  34555. }
  34556. }
  34557. if ( data.environment !== undefined ) {
  34558. object.environment = getTexture( data.environment );
  34559. }
  34560. if ( data.fog !== undefined ) {
  34561. if ( data.fog.type === 'Fog' ) {
  34562. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  34563. } else if ( data.fog.type === 'FogExp2' ) {
  34564. object.fog = new FogExp2( data.fog.color, data.fog.density );
  34565. }
  34566. if ( data.fog.name !== '' ) {
  34567. object.fog.name = data.fog.name;
  34568. }
  34569. }
  34570. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  34571. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  34572. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  34573. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  34574. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  34575. break;
  34576. case 'PerspectiveCamera':
  34577. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  34578. if ( data.focus !== undefined ) object.focus = data.focus;
  34579. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  34580. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  34581. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  34582. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  34583. break;
  34584. case 'OrthographicCamera':
  34585. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  34586. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  34587. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  34588. break;
  34589. case 'AmbientLight':
  34590. object = new AmbientLight( data.color, data.intensity );
  34591. break;
  34592. case 'DirectionalLight':
  34593. object = new DirectionalLight( data.color, data.intensity );
  34594. object.target = data.target || '';
  34595. break;
  34596. case 'PointLight':
  34597. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  34598. break;
  34599. case 'RectAreaLight':
  34600. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  34601. break;
  34602. case 'SpotLight':
  34603. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  34604. object.target = data.target || '';
  34605. break;
  34606. case 'HemisphereLight':
  34607. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  34608. break;
  34609. case 'LightProbe':
  34610. object = new LightProbe().fromJSON( data );
  34611. break;
  34612. case 'SkinnedMesh':
  34613. geometry = getGeometry( data.geometry );
  34614. material = getMaterial( data.material );
  34615. object = new SkinnedMesh( geometry, material );
  34616. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  34617. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  34618. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  34619. break;
  34620. case 'Mesh':
  34621. geometry = getGeometry( data.geometry );
  34622. material = getMaterial( data.material );
  34623. object = new Mesh( geometry, material );
  34624. break;
  34625. case 'InstancedMesh':
  34626. geometry = getGeometry( data.geometry );
  34627. material = getMaterial( data.material );
  34628. const count = data.count;
  34629. const instanceMatrix = data.instanceMatrix;
  34630. const instanceColor = data.instanceColor;
  34631. object = new InstancedMesh( geometry, material, count );
  34632. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  34633. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  34634. break;
  34635. case 'BatchedMesh':
  34636. geometry = getGeometry( data.geometry );
  34637. material = getMaterial( data.material );
  34638. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  34639. object.geometry = geometry;
  34640. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  34641. object.sortObjects = data.sortObjects;
  34642. object._drawRanges = data.drawRanges;
  34643. object._reservedRanges = data.reservedRanges;
  34644. object._visibility = data.visibility;
  34645. object._active = data.active;
  34646. object._bounds = data.bounds.map( bound => {
  34647. const box = new Box3();
  34648. box.min.fromArray( bound.boxMin );
  34649. box.max.fromArray( bound.boxMax );
  34650. const sphere = new Sphere();
  34651. sphere.radius = bound.sphereRadius;
  34652. sphere.center.fromArray( bound.sphereCenter );
  34653. return {
  34654. boxInitialized: bound.boxInitialized,
  34655. box: box,
  34656. sphereInitialized: bound.sphereInitialized,
  34657. sphere: sphere
  34658. };
  34659. } );
  34660. object._maxInstanceCount = data.maxInstanceCount;
  34661. object._maxVertexCount = data.maxVertexCount;
  34662. object._maxIndexCount = data.maxIndexCount;
  34663. object._geometryInitialized = data.geometryInitialized;
  34664. object._geometryCount = data.geometryCount;
  34665. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  34666. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  34667. break;
  34668. case 'LOD':
  34669. object = new LOD();
  34670. break;
  34671. case 'Line':
  34672. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  34673. break;
  34674. case 'LineLoop':
  34675. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  34676. break;
  34677. case 'LineSegments':
  34678. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  34679. break;
  34680. case 'PointCloud':
  34681. case 'Points':
  34682. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  34683. break;
  34684. case 'Sprite':
  34685. object = new Sprite( getMaterial( data.material ) );
  34686. break;
  34687. case 'Group':
  34688. object = new Group();
  34689. break;
  34690. case 'Bone':
  34691. object = new Bone();
  34692. break;
  34693. default:
  34694. object = new Object3D();
  34695. }
  34696. object.uuid = data.uuid;
  34697. if ( data.name !== undefined ) object.name = data.name;
  34698. if ( data.matrix !== undefined ) {
  34699. object.matrix.fromArray( data.matrix );
  34700. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  34701. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  34702. } else {
  34703. if ( data.position !== undefined ) object.position.fromArray( data.position );
  34704. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  34705. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  34706. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  34707. }
  34708. if ( data.up !== undefined ) object.up.fromArray( data.up );
  34709. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  34710. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  34711. if ( data.shadow ) {
  34712. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  34713. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  34714. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  34715. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  34716. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  34717. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  34718. }
  34719. if ( data.visible !== undefined ) object.visible = data.visible;
  34720. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  34721. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  34722. if ( data.userData !== undefined ) object.userData = data.userData;
  34723. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  34724. if ( data.children !== undefined ) {
  34725. const children = data.children;
  34726. for ( let i = 0; i < children.length; i ++ ) {
  34727. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  34728. }
  34729. }
  34730. if ( data.animations !== undefined ) {
  34731. const objectAnimations = data.animations;
  34732. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  34733. const uuid = objectAnimations[ i ];
  34734. object.animations.push( animations[ uuid ] );
  34735. }
  34736. }
  34737. if ( data.type === 'LOD' ) {
  34738. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  34739. const levels = data.levels;
  34740. for ( let l = 0; l < levels.length; l ++ ) {
  34741. const level = levels[ l ];
  34742. const child = object.getObjectByProperty( 'uuid', level.object );
  34743. if ( child !== undefined ) {
  34744. object.addLevel( child, level.distance, level.hysteresis );
  34745. }
  34746. }
  34747. }
  34748. return object;
  34749. }
  34750. bindSkeletons( object, skeletons ) {
  34751. if ( Object.keys( skeletons ).length === 0 ) return;
  34752. object.traverse( function ( child ) {
  34753. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  34754. const skeleton = skeletons[ child.skeleton ];
  34755. if ( skeleton === undefined ) {
  34756. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  34757. } else {
  34758. child.bind( skeleton, child.bindMatrix );
  34759. }
  34760. }
  34761. } );
  34762. }
  34763. bindLightTargets( object ) {
  34764. object.traverse( function ( child ) {
  34765. if ( child.isDirectionalLight || child.isSpotLight ) {
  34766. const uuid = child.target;
  34767. const target = object.getObjectByProperty( 'uuid', uuid );
  34768. if ( target !== undefined ) {
  34769. child.target = target;
  34770. } else {
  34771. child.target = new Object3D();
  34772. }
  34773. }
  34774. } );
  34775. }
  34776. }
  34777. const TEXTURE_MAPPING = {
  34778. UVMapping: UVMapping,
  34779. CubeReflectionMapping: CubeReflectionMapping,
  34780. CubeRefractionMapping: CubeRefractionMapping,
  34781. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  34782. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  34783. CubeUVReflectionMapping: CubeUVReflectionMapping
  34784. };
  34785. const TEXTURE_WRAPPING = {
  34786. RepeatWrapping: RepeatWrapping,
  34787. ClampToEdgeWrapping: ClampToEdgeWrapping,
  34788. MirroredRepeatWrapping: MirroredRepeatWrapping
  34789. };
  34790. const TEXTURE_FILTER = {
  34791. NearestFilter: NearestFilter,
  34792. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  34793. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  34794. LinearFilter: LinearFilter,
  34795. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  34796. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  34797. };
  34798. /**
  34799. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  34800. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  34801. * textures for rendering.
  34802. *
  34803. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  34804. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  34805. *
  34806. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  34807. *
  34808. * Also note that unlike {@link FileLoader}, this loader does not avoid multiple concurrent requests to the same URL.
  34809. *
  34810. * ```js
  34811. * const loader = new THREE.ImageBitmapLoader();
  34812. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  34813. * const imageBitmap = await loader.loadAsync( 'image.png' );
  34814. *
  34815. * const texture = new THREE.Texture( imageBitmap );
  34816. * texture.needsUpdate = true;
  34817. * ```
  34818. *
  34819. * @augments Loader
  34820. */
  34821. class ImageBitmapLoader extends Loader {
  34822. /**
  34823. * Constructs a new image bitmap loader.
  34824. *
  34825. * @param {LoadingManager} [manager] - The loading manager.
  34826. */
  34827. constructor( manager ) {
  34828. super( manager );
  34829. /**
  34830. * This flag can be used for type testing.
  34831. *
  34832. * @type {boolean}
  34833. * @readonly
  34834. * @default true
  34835. */
  34836. this.isImageBitmapLoader = true;
  34837. if ( typeof createImageBitmap === 'undefined' ) {
  34838. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  34839. }
  34840. if ( typeof fetch === 'undefined' ) {
  34841. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  34842. }
  34843. /**
  34844. * Represents the loader options.
  34845. *
  34846. * @type {Object}
  34847. * @default {premultiplyAlpha:'none'}
  34848. */
  34849. this.options = { premultiplyAlpha: 'none' };
  34850. }
  34851. /**
  34852. * Sets the given loader options. The structure of the object must match the `options` parameter of
  34853. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  34854. *
  34855. * @param {Object} options - The loader options to set.
  34856. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  34857. */
  34858. setOptions( options ) {
  34859. this.options = options;
  34860. return this;
  34861. }
  34862. /**
  34863. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  34864. *
  34865. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34866. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  34867. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  34868. * @param {onErrorCallback} onError - Executed when errors occur.
  34869. * @return {ImageBitmap|undefined} The image bitmap.
  34870. */
  34871. load( url, onLoad, onProgress, onError ) {
  34872. if ( url === undefined ) url = '';
  34873. if ( this.path !== undefined ) url = this.path + url;
  34874. url = this.manager.resolveURL( url );
  34875. const scope = this;
  34876. const cached = Cache.get( url );
  34877. if ( cached !== undefined ) {
  34878. scope.manager.itemStart( url );
  34879. // If cached is a promise, wait for it to resolve
  34880. if ( cached.then ) {
  34881. cached.then( imageBitmap => {
  34882. if ( onLoad ) onLoad( imageBitmap );
  34883. scope.manager.itemEnd( url );
  34884. } ).catch( e => {
  34885. if ( onError ) onError( e );
  34886. } );
  34887. return;
  34888. }
  34889. // If cached is not a promise (i.e., it's already an imageBitmap)
  34890. setTimeout( function () {
  34891. if ( onLoad ) onLoad( cached );
  34892. scope.manager.itemEnd( url );
  34893. }, 0 );
  34894. return cached;
  34895. }
  34896. const fetchOptions = {};
  34897. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  34898. fetchOptions.headers = this.requestHeader;
  34899. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  34900. return res.blob();
  34901. } ).then( function ( blob ) {
  34902. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  34903. } ).then( function ( imageBitmap ) {
  34904. Cache.add( url, imageBitmap );
  34905. if ( onLoad ) onLoad( imageBitmap );
  34906. scope.manager.itemEnd( url );
  34907. return imageBitmap;
  34908. } ).catch( function ( e ) {
  34909. if ( onError ) onError( e );
  34910. Cache.remove( url );
  34911. scope.manager.itemError( url );
  34912. scope.manager.itemEnd( url );
  34913. } );
  34914. Cache.add( url, promise );
  34915. scope.manager.itemStart( url );
  34916. }
  34917. }
  34918. let _context;
  34919. /**
  34920. * Manages the global audio context in the engine.
  34921. *
  34922. * @hideconstructor
  34923. */
  34924. class AudioContext {
  34925. /**
  34926. * Returns the global native audio context.
  34927. *
  34928. * @return {AudioContext} The native audio context.
  34929. */
  34930. static getContext() {
  34931. if ( _context === undefined ) {
  34932. _context = new ( window.AudioContext || window.webkitAudioContext )();
  34933. }
  34934. return _context;
  34935. }
  34936. /**
  34937. * Allows to set the global native audio context from outside.
  34938. *
  34939. * @param {AudioContext} value - The native context to set.
  34940. */
  34941. static setContext( value ) {
  34942. _context = value;
  34943. }
  34944. }
  34945. /**
  34946. * Class for loading audio buffers. Audios are internally
  34947. * loaded via {@link FileLoader}.
  34948. *
  34949. * ```js
  34950. * const audioListener = new THREE.AudioListener();
  34951. * const ambientSound = new THREE.Audio( audioListener );
  34952. *
  34953. * const loader = new THREE.AudioLoader();
  34954. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  34955. *
  34956. * ambientSound.setBuffer( audioBuffer );
  34957. * ambientSound.play();
  34958. * ```
  34959. *
  34960. * @augments Loader
  34961. */
  34962. class AudioLoader extends Loader {
  34963. /**
  34964. * Constructs a new audio loader.
  34965. *
  34966. * @param {LoadingManager} [manager] - The loading manager.
  34967. */
  34968. constructor( manager ) {
  34969. super( manager );
  34970. }
  34971. /**
  34972. * Starts loading from the given URL and passes the loaded audio buffer
  34973. * to the `onLoad()` callback.
  34974. *
  34975. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34976. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  34977. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34978. * @param {onErrorCallback} onError - Executed when errors occur.
  34979. */
  34980. load( url, onLoad, onProgress, onError ) {
  34981. const scope = this;
  34982. const loader = new FileLoader( this.manager );
  34983. loader.setResponseType( 'arraybuffer' );
  34984. loader.setPath( this.path );
  34985. loader.setRequestHeader( this.requestHeader );
  34986. loader.setWithCredentials( this.withCredentials );
  34987. loader.load( url, function ( buffer ) {
  34988. try {
  34989. // Create a copy of the buffer. The `decodeAudioData` method
  34990. // detaches the buffer when complete, preventing reuse.
  34991. const bufferCopy = buffer.slice( 0 );
  34992. const context = AudioContext.getContext();
  34993. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  34994. onLoad( audioBuffer );
  34995. } ).catch( handleError );
  34996. } catch ( e ) {
  34997. handleError( e );
  34998. }
  34999. }, onProgress, onError );
  35000. function handleError( e ) {
  35001. if ( onError ) {
  35002. onError( e );
  35003. } else {
  35004. console.error( e );
  35005. }
  35006. scope.manager.itemError( url );
  35007. }
  35008. }
  35009. }
  35010. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35011. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35012. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35013. /**
  35014. * A special type of camera that uses two perspective cameras with
  35015. * stereoscopic projection. Can be used for rendering stereo effects
  35016. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35017. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35018. */
  35019. class StereoCamera {
  35020. /**
  35021. * Constructs a new stereo camera.
  35022. */
  35023. constructor() {
  35024. /**
  35025. * The type property is used for detecting the object type
  35026. * in context of serialization/deserialization.
  35027. *
  35028. * @type {string}
  35029. * @readonly
  35030. */
  35031. this.type = 'StereoCamera';
  35032. /**
  35033. * The aspect.
  35034. *
  35035. * @type {number}
  35036. * @default 1
  35037. */
  35038. this.aspect = 1;
  35039. /**
  35040. * The eye separation which represents the distance
  35041. * between the left and right camera.
  35042. *
  35043. * @type {number}
  35044. * @default 0.064
  35045. */
  35046. this.eyeSep = 0.064;
  35047. /**
  35048. * The camera representing the left eye. This is added to layer `1` so objects to be
  35049. * rendered by the left camera must also be added to this layer.
  35050. *
  35051. * @type {PerspectiveCamera}
  35052. */
  35053. this.cameraL = new PerspectiveCamera();
  35054. this.cameraL.layers.enable( 1 );
  35055. this.cameraL.matrixAutoUpdate = false;
  35056. /**
  35057. * The camera representing the right eye. This is added to layer `2` so objects to be
  35058. * rendered by the right camera must also be added to this layer.
  35059. *
  35060. * @type {PerspectiveCamera}
  35061. */
  35062. this.cameraR = new PerspectiveCamera();
  35063. this.cameraR.layers.enable( 2 );
  35064. this.cameraR.matrixAutoUpdate = false;
  35065. this._cache = {
  35066. focus: null,
  35067. fov: null,
  35068. aspect: null,
  35069. near: null,
  35070. far: null,
  35071. zoom: null,
  35072. eyeSep: null
  35073. };
  35074. }
  35075. /**
  35076. * Updates the stereo camera based on the given perspective camera.
  35077. *
  35078. * @param {PerspectiveCamera} camera - The perspective camera.
  35079. */
  35080. update( camera ) {
  35081. const cache = this._cache;
  35082. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35083. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35084. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35085. if ( needsUpdate ) {
  35086. cache.focus = camera.focus;
  35087. cache.fov = camera.fov;
  35088. cache.aspect = camera.aspect * this.aspect;
  35089. cache.near = camera.near;
  35090. cache.far = camera.far;
  35091. cache.zoom = camera.zoom;
  35092. cache.eyeSep = this.eyeSep;
  35093. // Off-axis stereoscopic effect based on
  35094. // http://paulbourke.net/stereographics/stereorender/
  35095. _projectionMatrix.copy( camera.projectionMatrix );
  35096. const eyeSepHalf = cache.eyeSep / 2;
  35097. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35098. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35099. let xmin, xmax;
  35100. // translate xOffset
  35101. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35102. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35103. // for left eye
  35104. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35105. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35106. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35107. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35108. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35109. // for right eye
  35110. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35111. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35112. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35113. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35114. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35115. }
  35116. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35117. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35118. }
  35119. }
  35120. /**
  35121. * This type of camera can be used in order to efficiently render a scene with a
  35122. * predefined set of cameras. This is an important performance aspect for
  35123. * rendering VR scenes.
  35124. *
  35125. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35126. * to define for each sub camera the `viewport` property which determines the
  35127. * part of the viewport that is rendered with this camera.
  35128. *
  35129. * @augments PerspectiveCamera
  35130. */
  35131. class ArrayCamera extends PerspectiveCamera {
  35132. /**
  35133. * Constructs a new array camera.
  35134. *
  35135. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35136. */
  35137. constructor( array = [] ) {
  35138. super();
  35139. /**
  35140. * This flag can be used for type testing.
  35141. *
  35142. * @type {boolean}
  35143. * @readonly
  35144. * @default true
  35145. */
  35146. this.isArrayCamera = true;
  35147. /**
  35148. * An array of perspective sub cameras.
  35149. *
  35150. * @type {Array<PerspectiveCamera>}
  35151. */
  35152. this.cameras = array;
  35153. this.index = 0;
  35154. }
  35155. }
  35156. /**
  35157. * Class for keeping track of time.
  35158. */
  35159. class Clock {
  35160. /**
  35161. * Constructs a new clock.
  35162. *
  35163. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35164. * `getDelta()` is called for the first time.
  35165. */
  35166. constructor( autoStart = true ) {
  35167. /**
  35168. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35169. * for the first time.
  35170. *
  35171. * @type {boolean}
  35172. * @default true
  35173. */
  35174. this.autoStart = autoStart;
  35175. /**
  35176. * Holds the time at which the clock's `start()` method was last called.
  35177. *
  35178. * @type {number}
  35179. * @default 0
  35180. */
  35181. this.startTime = 0;
  35182. /**
  35183. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35184. * `getDelta()` methods were last called.
  35185. *
  35186. * @type {number}
  35187. * @default 0
  35188. */
  35189. this.oldTime = 0;
  35190. /**
  35191. * Keeps track of the total time that the clock has been running.
  35192. *
  35193. * @type {number}
  35194. * @default 0
  35195. */
  35196. this.elapsedTime = 0;
  35197. /**
  35198. * Whether the clock is running or not.
  35199. *
  35200. * @type {boolean}
  35201. * @default true
  35202. */
  35203. this.running = false;
  35204. }
  35205. /**
  35206. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35207. * called by the class.
  35208. */
  35209. start() {
  35210. this.startTime = now();
  35211. this.oldTime = this.startTime;
  35212. this.elapsedTime = 0;
  35213. this.running = true;
  35214. }
  35215. /**
  35216. * Stops the clock.
  35217. */
  35218. stop() {
  35219. this.getElapsedTime();
  35220. this.running = false;
  35221. this.autoStart = false;
  35222. }
  35223. /**
  35224. * Returns the elapsed time in seconds.
  35225. *
  35226. * @return {number} The elapsed time.
  35227. */
  35228. getElapsedTime() {
  35229. this.getDelta();
  35230. return this.elapsedTime;
  35231. }
  35232. /**
  35233. * Returns the delta time in seconds.
  35234. *
  35235. * @return {number} The delta time.
  35236. */
  35237. getDelta() {
  35238. let diff = 0;
  35239. if ( this.autoStart && ! this.running ) {
  35240. this.start();
  35241. return 0;
  35242. }
  35243. if ( this.running ) {
  35244. const newTime = now();
  35245. diff = ( newTime - this.oldTime ) / 1000;
  35246. this.oldTime = newTime;
  35247. this.elapsedTime += diff;
  35248. }
  35249. return diff;
  35250. }
  35251. }
  35252. function now() {
  35253. return performance.now();
  35254. }
  35255. const _position$1 = /*@__PURE__*/ new Vector3();
  35256. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35257. const _scale$1 = /*@__PURE__*/ new Vector3();
  35258. const _orientation$1 = /*@__PURE__*/ new Vector3();
  35259. /**
  35260. * The class represents a virtual listener of the all positional and non-positional audio effects
  35261. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35262. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35263. *
  35264. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35265. * camera represents the 3D transformation of the listener.
  35266. *
  35267. * @augments Object3D
  35268. */
  35269. class AudioListener extends Object3D {
  35270. /**
  35271. * Constructs a new audio listener.
  35272. */
  35273. constructor() {
  35274. super();
  35275. this.type = 'AudioListener';
  35276. /**
  35277. * The native audio context.
  35278. *
  35279. * @type {AudioContext}
  35280. * @readonly
  35281. */
  35282. this.context = AudioContext.getContext();
  35283. /**
  35284. * The gain node used for volume control.
  35285. *
  35286. * @type {GainNode}
  35287. * @readonly
  35288. */
  35289. this.gain = this.context.createGain();
  35290. this.gain.connect( this.context.destination );
  35291. /**
  35292. * An optional filter.
  35293. *
  35294. * Defined via {@link AudioListener#setFilter}.
  35295. *
  35296. * @type {?AudioNode}
  35297. * @default null
  35298. * @readonly
  35299. */
  35300. this.filter = null;
  35301. /**
  35302. * Time delta values required for `linearRampToValueAtTime()` usage.
  35303. *
  35304. * @type {number}
  35305. * @default 0
  35306. * @readonly
  35307. */
  35308. this.timeDelta = 0;
  35309. // private
  35310. this._clock = new Clock();
  35311. }
  35312. /**
  35313. * Returns the listener's input node.
  35314. *
  35315. * This method is used by other audio nodes to connect to this listener.
  35316. *
  35317. * @return {GainNode} The input node.
  35318. */
  35319. getInput() {
  35320. return this.gain;
  35321. }
  35322. /**
  35323. * Removes the current filter from this listener.
  35324. *
  35325. * @return {AudioListener} A reference to this listener.
  35326. */
  35327. removeFilter() {
  35328. if ( this.filter !== null ) {
  35329. this.gain.disconnect( this.filter );
  35330. this.filter.disconnect( this.context.destination );
  35331. this.gain.connect( this.context.destination );
  35332. this.filter = null;
  35333. }
  35334. return this;
  35335. }
  35336. /**
  35337. * Returns the current set filter.
  35338. *
  35339. * @return {?AudioNode} The filter.
  35340. */
  35341. getFilter() {
  35342. return this.filter;
  35343. }
  35344. /**
  35345. * Sets the given filter to this listener.
  35346. *
  35347. * @param {AudioNode} value - The filter to set.
  35348. * @return {AudioListener} A reference to this listener.
  35349. */
  35350. setFilter( value ) {
  35351. if ( this.filter !== null ) {
  35352. this.gain.disconnect( this.filter );
  35353. this.filter.disconnect( this.context.destination );
  35354. } else {
  35355. this.gain.disconnect( this.context.destination );
  35356. }
  35357. this.filter = value;
  35358. this.gain.connect( this.filter );
  35359. this.filter.connect( this.context.destination );
  35360. return this;
  35361. }
  35362. /**
  35363. * Returns the applications master volume.
  35364. *
  35365. * @return {number} The master volume.
  35366. */
  35367. getMasterVolume() {
  35368. return this.gain.gain.value;
  35369. }
  35370. /**
  35371. * Sets the applications master volume. This volume setting affects
  35372. * all audio nodes in the scene.
  35373. *
  35374. * @param {number} value - The master volume to set.
  35375. * @return {AudioListener} A reference to this listener.
  35376. */
  35377. setMasterVolume( value ) {
  35378. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  35379. return this;
  35380. }
  35381. updateMatrixWorld( force ) {
  35382. super.updateMatrixWorld( force );
  35383. const listener = this.context.listener;
  35384. const up = this.up;
  35385. this.timeDelta = this._clock.getDelta();
  35386. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  35387. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  35388. if ( listener.positionX ) {
  35389. // code path for Chrome (see #14393)
  35390. const endTime = this.context.currentTime + this.timeDelta;
  35391. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  35392. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  35393. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  35394. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  35395. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  35396. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  35397. listener.upX.linearRampToValueAtTime( up.x, endTime );
  35398. listener.upY.linearRampToValueAtTime( up.y, endTime );
  35399. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  35400. } else {
  35401. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  35402. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  35403. }
  35404. }
  35405. }
  35406. /**
  35407. * Represents a non-positional ( global ) audio object.
  35408. *
  35409. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  35410. *
  35411. * ```js
  35412. * // create an AudioListener and add it to the camera
  35413. * const listener = new THREE.AudioListener();
  35414. * camera.add( listener );
  35415. *
  35416. * // create a global audio source
  35417. * const sound = new THREE.Audio( listener );
  35418. *
  35419. * // load a sound and set it as the Audio object's buffer
  35420. * const audioLoader = new THREE.AudioLoader();
  35421. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  35422. * sound.setBuffer( buffer );
  35423. * sound.setLoop( true );
  35424. * sound.setVolume( 0.5 );
  35425. * sound.play();
  35426. * });
  35427. * ```
  35428. *
  35429. * @augments Object3D
  35430. */
  35431. class Audio extends Object3D {
  35432. /**
  35433. * Constructs a new audio.
  35434. *
  35435. * @param {AudioListener} listener - The global audio listener.
  35436. */
  35437. constructor( listener ) {
  35438. super();
  35439. this.type = 'Audio';
  35440. /**
  35441. * The global audio listener.
  35442. *
  35443. * @type {AudioListener}
  35444. * @readonly
  35445. */
  35446. this.listener = listener;
  35447. /**
  35448. * The audio context.
  35449. *
  35450. * @type {AudioContext}
  35451. * @readonly
  35452. */
  35453. this.context = listener.context;
  35454. /**
  35455. * The gain node used for volume control.
  35456. *
  35457. * @type {GainNode}
  35458. * @readonly
  35459. */
  35460. this.gain = this.context.createGain();
  35461. this.gain.connect( listener.getInput() );
  35462. /**
  35463. * Whether to start playback automatically or not.
  35464. *
  35465. * @type {boolean}
  35466. * @default false
  35467. */
  35468. this.autoplay = false;
  35469. /**
  35470. * A reference to an audio buffer.
  35471. *
  35472. * Defined via {@link Audio#setBuffer}.
  35473. *
  35474. * @type {?AudioBuffer}
  35475. * @default null
  35476. * @readonly
  35477. */
  35478. this.buffer = null;
  35479. /**
  35480. * Modify pitch, measured in cents. +/- 100 is a semitone.
  35481. * +/- 1200 is an octave.
  35482. *
  35483. * Defined via {@link Audio#setDetune}.
  35484. *
  35485. * @type {number}
  35486. * @default 0
  35487. * @readonly
  35488. */
  35489. this.detune = 0;
  35490. /**
  35491. * Whether the audio should loop or not.
  35492. *
  35493. * Defined via {@link Audio#setLoop}.
  35494. *
  35495. * @type {boolean}
  35496. * @default false
  35497. * @readonly
  35498. */
  35499. this.loop = false;
  35500. /**
  35501. * Defines where in the audio buffer the replay should
  35502. * start, in seconds.
  35503. *
  35504. * @type {number}
  35505. * @default 0
  35506. */
  35507. this.loopStart = 0;
  35508. /**
  35509. * Defines where in the audio buffer the replay should
  35510. * stop, in seconds.
  35511. *
  35512. * @type {number}
  35513. * @default 0
  35514. */
  35515. this.loopEnd = 0;
  35516. /**
  35517. * An offset to the time within the audio buffer the playback
  35518. * should begin, in seconds.
  35519. *
  35520. * @type {number}
  35521. * @default 0
  35522. */
  35523. this.offset = 0;
  35524. /**
  35525. * Overrides the default duration of the audio.
  35526. *
  35527. * @type {undefined|number}
  35528. * @default undefined
  35529. */
  35530. this.duration = undefined;
  35531. /**
  35532. * The playback speed.
  35533. *
  35534. * Defined via {@link Audio#setPlaybackRate}.
  35535. *
  35536. * @type {number}
  35537. * @readonly
  35538. * @default 1
  35539. */
  35540. this.playbackRate = 1;
  35541. /**
  35542. * Indicates whether the audio is playing or not.
  35543. *
  35544. * This flag will be automatically set when using {@link Audio#play},
  35545. * {@link Audio#pause}, {@link Audio#stop}.
  35546. *
  35547. * @type {boolean}
  35548. * @readonly
  35549. * @default false
  35550. */
  35551. this.isPlaying = false;
  35552. /**
  35553. * Indicates whether the audio playback can be controlled
  35554. * with method like {@link Audio#play} or {@link Audio#pause}.
  35555. *
  35556. * This flag will be automatically set when audio sources are
  35557. * defined.
  35558. *
  35559. * @type {boolean}
  35560. * @readonly
  35561. * @default true
  35562. */
  35563. this.hasPlaybackControl = true;
  35564. /**
  35565. * Holds a reference to the current audio source.
  35566. *
  35567. * The property is automatically by one of the `set*()` methods.
  35568. *
  35569. * @type {?AudioNode}
  35570. * @readonly
  35571. * @default null
  35572. */
  35573. this.source = null;
  35574. /**
  35575. * Defines the source type.
  35576. *
  35577. * The property is automatically by one of the `set*()` methods.
  35578. *
  35579. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  35580. * @readonly
  35581. * @default 'empty'
  35582. */
  35583. this.sourceType = 'empty';
  35584. this._startedAt = 0;
  35585. this._progress = 0;
  35586. this._connected = false;
  35587. /**
  35588. * Can be used to apply a variety of low-order filters to create
  35589. * more complex sound effects e.g. via `BiquadFilterNode`.
  35590. *
  35591. * The property is automatically set by {@link Audio#setFilters}.
  35592. *
  35593. * @type {Array<AudioNode>}
  35594. * @readonly
  35595. */
  35596. this.filters = [];
  35597. }
  35598. /**
  35599. * Returns the output audio node.
  35600. *
  35601. * @return {GainNode} The output node.
  35602. */
  35603. getOutput() {
  35604. return this.gain;
  35605. }
  35606. /**
  35607. * Sets the given audio node as the source of this instance.
  35608. *
  35609. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  35610. *
  35611. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  35612. * @return {Audio} A reference to this instance.
  35613. */
  35614. setNodeSource( audioNode ) {
  35615. this.hasPlaybackControl = false;
  35616. this.sourceType = 'audioNode';
  35617. this.source = audioNode;
  35618. this.connect();
  35619. return this;
  35620. }
  35621. /**
  35622. * Sets the given media element as the source of this instance.
  35623. *
  35624. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  35625. *
  35626. * @param {HTMLMediaElement} mediaElement - The media element.
  35627. * @return {Audio} A reference to this instance.
  35628. */
  35629. setMediaElementSource( mediaElement ) {
  35630. this.hasPlaybackControl = false;
  35631. this.sourceType = 'mediaNode';
  35632. this.source = this.context.createMediaElementSource( mediaElement );
  35633. this.connect();
  35634. return this;
  35635. }
  35636. /**
  35637. * Sets the given media stream as the source of this instance.
  35638. *
  35639. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  35640. *
  35641. * @param {MediaStream} mediaStream - The media stream.
  35642. * @return {Audio} A reference to this instance.
  35643. */
  35644. setMediaStreamSource( mediaStream ) {
  35645. this.hasPlaybackControl = false;
  35646. this.sourceType = 'mediaStreamNode';
  35647. this.source = this.context.createMediaStreamSource( mediaStream );
  35648. this.connect();
  35649. return this;
  35650. }
  35651. /**
  35652. * Sets the given audio buffer as the source of this instance.
  35653. *
  35654. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  35655. *
  35656. * @param {AudioBuffer} audioBuffer - The audio buffer.
  35657. * @return {Audio} A reference to this instance.
  35658. */
  35659. setBuffer( audioBuffer ) {
  35660. this.buffer = audioBuffer;
  35661. this.sourceType = 'buffer';
  35662. if ( this.autoplay ) this.play();
  35663. return this;
  35664. }
  35665. /**
  35666. * Starts the playback of the audio.
  35667. *
  35668. * Can only be used with compatible audio sources that allow playback control.
  35669. *
  35670. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  35671. * @return {Audio|undefined} A reference to this instance.
  35672. */
  35673. play( delay = 0 ) {
  35674. if ( this.isPlaying === true ) {
  35675. console.warn( 'THREE.Audio: Audio is already playing.' );
  35676. return;
  35677. }
  35678. if ( this.hasPlaybackControl === false ) {
  35679. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35680. return;
  35681. }
  35682. this._startedAt = this.context.currentTime + delay;
  35683. const source = this.context.createBufferSource();
  35684. source.buffer = this.buffer;
  35685. source.loop = this.loop;
  35686. source.loopStart = this.loopStart;
  35687. source.loopEnd = this.loopEnd;
  35688. source.onended = this.onEnded.bind( this );
  35689. source.start( this._startedAt, this._progress + this.offset, this.duration );
  35690. this.isPlaying = true;
  35691. this.source = source;
  35692. this.setDetune( this.detune );
  35693. this.setPlaybackRate( this.playbackRate );
  35694. return this.connect();
  35695. }
  35696. /**
  35697. * Pauses the playback of the audio.
  35698. *
  35699. * Can only be used with compatible audio sources that allow playback control.
  35700. *
  35701. * @return {Audio|undefined} A reference to this instance.
  35702. */
  35703. pause() {
  35704. if ( this.hasPlaybackControl === false ) {
  35705. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35706. return;
  35707. }
  35708. if ( this.isPlaying === true ) {
  35709. // update current progress
  35710. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  35711. if ( this.loop === true ) {
  35712. // ensure _progress does not exceed duration with looped audios
  35713. this._progress = this._progress % ( this.duration || this.buffer.duration );
  35714. }
  35715. this.source.stop();
  35716. this.source.onended = null;
  35717. this.isPlaying = false;
  35718. }
  35719. return this;
  35720. }
  35721. /**
  35722. * Stops the playback of the audio.
  35723. *
  35724. * Can only be used with compatible audio sources that allow playback control.
  35725. *
  35726. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  35727. * @return {Audio|undefined} A reference to this instance.
  35728. */
  35729. stop( delay = 0 ) {
  35730. if ( this.hasPlaybackControl === false ) {
  35731. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35732. return;
  35733. }
  35734. this._progress = 0;
  35735. if ( this.source !== null ) {
  35736. this.source.stop( this.context.currentTime + delay );
  35737. this.source.onended = null;
  35738. }
  35739. this.isPlaying = false;
  35740. return this;
  35741. }
  35742. /**
  35743. * Connects to the audio source. This is used internally on
  35744. * initialisation and when setting / removing filters.
  35745. *
  35746. * @return {Audio} A reference to this instance.
  35747. */
  35748. connect() {
  35749. if ( this.filters.length > 0 ) {
  35750. this.source.connect( this.filters[ 0 ] );
  35751. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  35752. this.filters[ i - 1 ].connect( this.filters[ i ] );
  35753. }
  35754. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  35755. } else {
  35756. this.source.connect( this.getOutput() );
  35757. }
  35758. this._connected = true;
  35759. return this;
  35760. }
  35761. /**
  35762. * Disconnects to the audio source. This is used internally on
  35763. * initialisation and when setting / removing filters.
  35764. *
  35765. * @return {Audio|undefined} A reference to this instance.
  35766. */
  35767. disconnect() {
  35768. if ( this._connected === false ) {
  35769. return;
  35770. }
  35771. if ( this.filters.length > 0 ) {
  35772. this.source.disconnect( this.filters[ 0 ] );
  35773. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  35774. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  35775. }
  35776. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  35777. } else {
  35778. this.source.disconnect( this.getOutput() );
  35779. }
  35780. this._connected = false;
  35781. return this;
  35782. }
  35783. /**
  35784. * Returns the current set filters.
  35785. *
  35786. * @return {Array<AudioNode>} The list of filters.
  35787. */
  35788. getFilters() {
  35789. return this.filters;
  35790. }
  35791. /**
  35792. * Sets an array of filters and connects them with the audio source.
  35793. *
  35794. * @param {Array<AudioNode>} [value] - A list of filters.
  35795. * @return {Audio} A reference to this instance.
  35796. */
  35797. setFilters( value ) {
  35798. if ( ! value ) value = [];
  35799. if ( this._connected === true ) {
  35800. this.disconnect();
  35801. this.filters = value.slice();
  35802. this.connect();
  35803. } else {
  35804. this.filters = value.slice();
  35805. }
  35806. return this;
  35807. }
  35808. /**
  35809. * Defines the detuning of oscillation in cents.
  35810. *
  35811. * @param {number} value - The detuning of oscillation in cents.
  35812. * @return {Audio} A reference to this instance.
  35813. */
  35814. setDetune( value ) {
  35815. this.detune = value;
  35816. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  35817. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  35818. }
  35819. return this;
  35820. }
  35821. /**
  35822. * Returns the detuning of oscillation in cents.
  35823. *
  35824. * @return {number} The detuning of oscillation in cents.
  35825. */
  35826. getDetune() {
  35827. return this.detune;
  35828. }
  35829. /**
  35830. * Returns the first filter in the list of filters.
  35831. *
  35832. * @return {AudioNode|undefined} The first filter in the list of filters.
  35833. */
  35834. getFilter() {
  35835. return this.getFilters()[ 0 ];
  35836. }
  35837. /**
  35838. * Applies a single filter node to the audio.
  35839. *
  35840. * @param {AudioNode} [filter] - The filter to set.
  35841. * @return {Audio} A reference to this instance.
  35842. */
  35843. setFilter( filter ) {
  35844. return this.setFilters( filter ? [ filter ] : [] );
  35845. }
  35846. /**
  35847. * Sets the playback rate.
  35848. *
  35849. * Can only be used with compatible audio sources that allow playback control.
  35850. *
  35851. * @param {number} [value] - The playback rate to set.
  35852. * @return {Audio|undefined} A reference to this instance.
  35853. */
  35854. setPlaybackRate( value ) {
  35855. if ( this.hasPlaybackControl === false ) {
  35856. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35857. return;
  35858. }
  35859. this.playbackRate = value;
  35860. if ( this.isPlaying === true ) {
  35861. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  35862. }
  35863. return this;
  35864. }
  35865. /**
  35866. * Returns the current playback rate.
  35867. * @return {number} The playback rate.
  35868. */
  35869. getPlaybackRate() {
  35870. return this.playbackRate;
  35871. }
  35872. /**
  35873. * Automatically called when playback finished.
  35874. */
  35875. onEnded() {
  35876. this.isPlaying = false;
  35877. this._progress = 0;
  35878. }
  35879. /**
  35880. * Returns the loop flag.
  35881. *
  35882. * Can only be used with compatible audio sources that allow playback control.
  35883. *
  35884. * @return {boolean} Whether the audio should loop or not.
  35885. */
  35886. getLoop() {
  35887. if ( this.hasPlaybackControl === false ) {
  35888. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35889. return false;
  35890. }
  35891. return this.loop;
  35892. }
  35893. /**
  35894. * Sets the loop flag.
  35895. *
  35896. * Can only be used with compatible audio sources that allow playback control.
  35897. *
  35898. * @param {boolean} value - Whether the audio should loop or not.
  35899. * @return {Audio|undefined} A reference to this instance.
  35900. */
  35901. setLoop( value ) {
  35902. if ( this.hasPlaybackControl === false ) {
  35903. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  35904. return;
  35905. }
  35906. this.loop = value;
  35907. if ( this.isPlaying === true ) {
  35908. this.source.loop = this.loop;
  35909. }
  35910. return this;
  35911. }
  35912. /**
  35913. * Sets the loop start value which defines where in the audio buffer the replay should
  35914. * start, in seconds.
  35915. *
  35916. * @param {number} value - The loop start value.
  35917. * @return {Audio} A reference to this instance.
  35918. */
  35919. setLoopStart( value ) {
  35920. this.loopStart = value;
  35921. return this;
  35922. }
  35923. /**
  35924. * Sets the loop end value which defines where in the audio buffer the replay should
  35925. * stop, in seconds.
  35926. *
  35927. * @param {number} value - The loop end value.
  35928. * @return {Audio} A reference to this instance.
  35929. */
  35930. setLoopEnd( value ) {
  35931. this.loopEnd = value;
  35932. return this;
  35933. }
  35934. /**
  35935. * Returns the volume.
  35936. *
  35937. * @return {number} The volume.
  35938. */
  35939. getVolume() {
  35940. return this.gain.gain.value;
  35941. }
  35942. /**
  35943. * Sets the volume.
  35944. *
  35945. * @param {number} value - The volume to set.
  35946. * @return {Audio} A reference to this instance.
  35947. */
  35948. setVolume( value ) {
  35949. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  35950. return this;
  35951. }
  35952. copy( source, recursive ) {
  35953. super.copy( source, recursive );
  35954. if ( source.sourceType !== 'buffer' ) {
  35955. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  35956. return this;
  35957. }
  35958. this.autoplay = source.autoplay;
  35959. this.buffer = source.buffer;
  35960. this.detune = source.detune;
  35961. this.loop = source.loop;
  35962. this.loopStart = source.loopStart;
  35963. this.loopEnd = source.loopEnd;
  35964. this.offset = source.offset;
  35965. this.duration = source.duration;
  35966. this.playbackRate = source.playbackRate;
  35967. this.hasPlaybackControl = source.hasPlaybackControl;
  35968. this.sourceType = source.sourceType;
  35969. this.filters = source.filters.slice();
  35970. return this;
  35971. }
  35972. clone( recursive ) {
  35973. return new this.constructor( this.listener ).copy( this, recursive );
  35974. }
  35975. }
  35976. const _position = /*@__PURE__*/ new Vector3();
  35977. const _quaternion = /*@__PURE__*/ new Quaternion();
  35978. const _scale = /*@__PURE__*/ new Vector3();
  35979. const _orientation = /*@__PURE__*/ new Vector3();
  35980. /**
  35981. * Represents a positional audio object.
  35982. *
  35983. * ```js
  35984. * // create an AudioListener and add it to the camera
  35985. * const listener = new THREE.AudioListener();
  35986. * camera.add( listener );
  35987. *
  35988. * // create the PositionalAudio object (passing in the listener)
  35989. * const sound = new THREE.PositionalAudio( listener );
  35990. *
  35991. * // load a sound and set it as the PositionalAudio object's buffer
  35992. * const audioLoader = new THREE.AudioLoader();
  35993. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  35994. * sound.setBuffer( buffer );
  35995. * sound.setRefDistance( 20 );
  35996. * sound.play();
  35997. * });
  35998. *
  35999. * // create an object for the sound to play from
  36000. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36001. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36002. * const mesh = new THREE.Mesh( sphere, material );
  36003. * scene.add( mesh );
  36004. *
  36005. * // finally add the sound to the mesh
  36006. * mesh.add( sound );
  36007. *
  36008. * @augments Audio
  36009. */
  36010. class PositionalAudio extends Audio {
  36011. /**
  36012. * Constructs a positional audio.
  36013. *
  36014. * @param {AudioListener} listener - The global audio listener.
  36015. */
  36016. constructor( listener ) {
  36017. super( listener );
  36018. /**
  36019. * The panner node represents the location, direction, and behavior of an audio
  36020. * source in 3D space.
  36021. *
  36022. * @type {PannerNode}
  36023. * @readonly
  36024. */
  36025. this.panner = this.context.createPanner();
  36026. this.panner.panningModel = 'HRTF';
  36027. this.panner.connect( this.gain );
  36028. }
  36029. connect() {
  36030. super.connect();
  36031. this.panner.connect( this.gain );
  36032. return this;
  36033. }
  36034. disconnect() {
  36035. super.disconnect();
  36036. this.panner.disconnect( this.gain );
  36037. return this;
  36038. }
  36039. getOutput() {
  36040. return this.panner;
  36041. }
  36042. /**
  36043. * Returns the current reference distance.
  36044. *
  36045. * @return {number} The reference distance.
  36046. */
  36047. getRefDistance() {
  36048. return this.panner.refDistance;
  36049. }
  36050. /**
  36051. * Defines the reference distance for reducing volume as the audio source moves
  36052. * further from the listener – i.e. the distance at which the volume reduction
  36053. * starts taking effect.
  36054. *
  36055. * @param {number} value - The reference distance to set.
  36056. * @return {PositionalAudio} A reference to this instance.
  36057. */
  36058. setRefDistance( value ) {
  36059. this.panner.refDistance = value;
  36060. return this;
  36061. }
  36062. /**
  36063. * Returns the current rolloff factor.
  36064. *
  36065. * @return {number} The rolloff factor.
  36066. */
  36067. getRolloffFactor() {
  36068. return this.panner.rolloffFactor;
  36069. }
  36070. /**
  36071. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36072. *
  36073. * @param {number} value - The rolloff factor.
  36074. * @return {PositionalAudio} A reference to this instance.
  36075. */
  36076. setRolloffFactor( value ) {
  36077. this.panner.rolloffFactor = value;
  36078. return this;
  36079. }
  36080. /**
  36081. * Returns the current distance model.
  36082. *
  36083. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36084. */
  36085. getDistanceModel() {
  36086. return this.panner.distanceModel;
  36087. }
  36088. /**
  36089. * Defines which algorithm to use to reduce the volume of the audio source
  36090. * as it moves away from the listener.
  36091. *
  36092. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36093. * for more details.
  36094. *
  36095. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36096. * @return {PositionalAudio} A reference to this instance.
  36097. */
  36098. setDistanceModel( value ) {
  36099. this.panner.distanceModel = value;
  36100. return this;
  36101. }
  36102. /**
  36103. * Returns the current max distance.
  36104. *
  36105. * @return {number} The max distance.
  36106. */
  36107. getMaxDistance() {
  36108. return this.panner.maxDistance;
  36109. }
  36110. /**
  36111. * Defines the maximum distance between the audio source and the listener,
  36112. * after which the volume is not reduced any further.
  36113. *
  36114. * This value is used only by the `linear` distance model.
  36115. *
  36116. * @param {number} value - The max distance.
  36117. * @return {PositionalAudio} A reference to this instance.
  36118. */
  36119. setMaxDistance( value ) {
  36120. this.panner.maxDistance = value;
  36121. return this;
  36122. }
  36123. /**
  36124. * Sets the directional cone in which the audio can be listened.
  36125. *
  36126. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36127. * @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.
  36128. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36129. * @return {PositionalAudio} A reference to this instance.
  36130. */
  36131. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36132. this.panner.coneInnerAngle = coneInnerAngle;
  36133. this.panner.coneOuterAngle = coneOuterAngle;
  36134. this.panner.coneOuterGain = coneOuterGain;
  36135. return this;
  36136. }
  36137. updateMatrixWorld( force ) {
  36138. super.updateMatrixWorld( force );
  36139. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36140. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36141. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36142. const panner = this.panner;
  36143. if ( panner.positionX ) {
  36144. // code path for Chrome and Firefox (see #14393)
  36145. const endTime = this.context.currentTime + this.listener.timeDelta;
  36146. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36147. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36148. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36149. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36150. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36151. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36152. } else {
  36153. panner.setPosition( _position.x, _position.y, _position.z );
  36154. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36155. }
  36156. }
  36157. }
  36158. /**
  36159. * This class can be used to analyse audio data.
  36160. *
  36161. * ```js
  36162. * // create an AudioListener and add it to the camera
  36163. * const listener = new THREE.AudioListener();
  36164. * camera.add( listener );
  36165. *
  36166. * // create an Audio source
  36167. * const sound = new THREE.Audio( listener );
  36168. *
  36169. * // load a sound and set it as the Audio object's buffer
  36170. * const audioLoader = new THREE.AudioLoader();
  36171. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36172. * sound.setBuffer( buffer );
  36173. * sound.setLoop(true);
  36174. * sound.setVolume(0.5);
  36175. * sound.play();
  36176. * });
  36177. *
  36178. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36179. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36180. *
  36181. * // get the average frequency of the sound
  36182. * const data = analyser.getAverageFrequency();
  36183. * ```
  36184. */
  36185. class AudioAnalyser {
  36186. /**
  36187. * Constructs a new audio analyzer.
  36188. *
  36189. * @param {Audio} audio - The audio to analyze.
  36190. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36191. */
  36192. constructor( audio, fftSize = 2048 ) {
  36193. /**
  36194. * The global audio listener.
  36195. *
  36196. * @type {AnalyserNode}
  36197. */
  36198. this.analyser = audio.context.createAnalyser();
  36199. this.analyser.fftSize = fftSize;
  36200. /**
  36201. * Holds the analyzed data.
  36202. *
  36203. * @type {Uint8Array}
  36204. */
  36205. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36206. audio.getOutput().connect( this.analyser );
  36207. }
  36208. /**
  36209. * Returns an array with frequency data of the audio.
  36210. *
  36211. * Each item in the array represents the decibel value for a specific frequency.
  36212. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36213. * For example, for 48000 sample rate, the last item of the array will represent
  36214. * the decibel value for 24000 Hz.
  36215. *
  36216. * @return {Uint8Array} The frequency data.
  36217. */
  36218. getFrequencyData() {
  36219. this.analyser.getByteFrequencyData( this.data );
  36220. return this.data;
  36221. }
  36222. /**
  36223. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36224. *
  36225. * @return {number} The average frequency.
  36226. */
  36227. getAverageFrequency() {
  36228. let value = 0;
  36229. const data = this.getFrequencyData();
  36230. for ( let i = 0; i < data.length; i ++ ) {
  36231. value += data[ i ];
  36232. }
  36233. return value / data.length;
  36234. }
  36235. }
  36236. /**
  36237. * Buffered scene graph property that allows weighted accumulation; used internally.
  36238. */
  36239. class PropertyMixer {
  36240. /**
  36241. * Constructs a new property mixer.
  36242. *
  36243. * @param {PropertyBinding} binding - The property binding.
  36244. * @param {string} typeName - The keyframe track type name.
  36245. * @param {number} valueSize - The keyframe track value size.
  36246. */
  36247. constructor( binding, typeName, valueSize ) {
  36248. /**
  36249. * The property binding.
  36250. *
  36251. * @type {PropertyBinding}
  36252. */
  36253. this.binding = binding;
  36254. /**
  36255. * The keyframe track value size.
  36256. *
  36257. * @type {number}
  36258. */
  36259. this.valueSize = valueSize;
  36260. let mixFunction,
  36261. mixFunctionAdditive,
  36262. setIdentity;
  36263. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36264. //
  36265. // interpolators can use .buffer as their .result
  36266. // the data then goes to 'incoming'
  36267. //
  36268. // 'accu0' and 'accu1' are used frame-interleaved for
  36269. // the cumulative result and are compared to detect
  36270. // changes
  36271. //
  36272. // 'orig' stores the original state of the property
  36273. //
  36274. // 'add' is used for additive cumulative results
  36275. //
  36276. // 'work' is optional and is only present for quaternion types. It is used
  36277. // to store intermediate quaternion multiplication results
  36278. switch ( typeName ) {
  36279. case 'quaternion':
  36280. mixFunction = this._slerp;
  36281. mixFunctionAdditive = this._slerpAdditive;
  36282. setIdentity = this._setAdditiveIdentityQuaternion;
  36283. this.buffer = new Float64Array( valueSize * 6 );
  36284. this._workIndex = 5;
  36285. break;
  36286. case 'string':
  36287. case 'bool':
  36288. mixFunction = this._select;
  36289. // Use the regular mix function and for additive on these types,
  36290. // additive is not relevant for non-numeric types
  36291. mixFunctionAdditive = this._select;
  36292. setIdentity = this._setAdditiveIdentityOther;
  36293. this.buffer = new Array( valueSize * 5 );
  36294. break;
  36295. default:
  36296. mixFunction = this._lerp;
  36297. mixFunctionAdditive = this._lerpAdditive;
  36298. setIdentity = this._setAdditiveIdentityNumeric;
  36299. this.buffer = new Float64Array( valueSize * 5 );
  36300. }
  36301. this._mixBufferRegion = mixFunction;
  36302. this._mixBufferRegionAdditive = mixFunctionAdditive;
  36303. this._setIdentity = setIdentity;
  36304. this._origIndex = 3;
  36305. this._addIndex = 4;
  36306. /**
  36307. * TODO
  36308. *
  36309. * @type {number}
  36310. * @default 0
  36311. */
  36312. this.cumulativeWeight = 0;
  36313. /**
  36314. * TODO
  36315. *
  36316. * @type {number}
  36317. * @default 0
  36318. */
  36319. this.cumulativeWeightAdditive = 0;
  36320. /**
  36321. * TODO
  36322. *
  36323. * @type {number}
  36324. * @default 0
  36325. */
  36326. this.useCount = 0;
  36327. /**
  36328. * TODO
  36329. *
  36330. * @type {number}
  36331. * @default 0
  36332. */
  36333. this.referenceCount = 0;
  36334. }
  36335. /**
  36336. * Accumulates data in the `incoming` region into `accu<i>`.
  36337. *
  36338. * @param {number} accuIndex - The accumulation index.
  36339. * @param {number} weight - The weight.
  36340. */
  36341. accumulate( accuIndex, weight ) {
  36342. // note: happily accumulating nothing when weight = 0, the caller knows
  36343. // the weight and shouldn't have made the call in the first place
  36344. const buffer = this.buffer,
  36345. stride = this.valueSize,
  36346. offset = accuIndex * stride + stride;
  36347. let currentWeight = this.cumulativeWeight;
  36348. if ( currentWeight === 0 ) {
  36349. // accuN := incoming * weight
  36350. for ( let i = 0; i !== stride; ++ i ) {
  36351. buffer[ offset + i ] = buffer[ i ];
  36352. }
  36353. currentWeight = weight;
  36354. } else {
  36355. // accuN := accuN + incoming * weight
  36356. currentWeight += weight;
  36357. const mix = weight / currentWeight;
  36358. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  36359. }
  36360. this.cumulativeWeight = currentWeight;
  36361. }
  36362. /**
  36363. * Accumulates data in the `incoming` region into `add`.
  36364. *
  36365. * @param {number} weight - The weight.
  36366. */
  36367. accumulateAdditive( weight ) {
  36368. const buffer = this.buffer,
  36369. stride = this.valueSize,
  36370. offset = stride * this._addIndex;
  36371. if ( this.cumulativeWeightAdditive === 0 ) {
  36372. // add = identity
  36373. this._setIdentity();
  36374. }
  36375. // add := add + incoming * weight
  36376. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  36377. this.cumulativeWeightAdditive += weight;
  36378. }
  36379. /**
  36380. * Applies the state of `accu<i>` to the binding when accus differ.
  36381. *
  36382. * @param {number} accuIndex - The accumulation index.
  36383. */
  36384. apply( accuIndex ) {
  36385. const stride = this.valueSize,
  36386. buffer = this.buffer,
  36387. offset = accuIndex * stride + stride,
  36388. weight = this.cumulativeWeight,
  36389. weightAdditive = this.cumulativeWeightAdditive,
  36390. binding = this.binding;
  36391. this.cumulativeWeight = 0;
  36392. this.cumulativeWeightAdditive = 0;
  36393. if ( weight < 1 ) {
  36394. // accuN := accuN + original * ( 1 - cumulativeWeight )
  36395. const originalValueOffset = stride * this._origIndex;
  36396. this._mixBufferRegion(
  36397. buffer, offset, originalValueOffset, 1 - weight, stride );
  36398. }
  36399. if ( weightAdditive > 0 ) {
  36400. // accuN := accuN + additive accuN
  36401. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  36402. }
  36403. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  36404. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  36405. // value has changed -> update scene graph
  36406. binding.setValue( buffer, offset );
  36407. break;
  36408. }
  36409. }
  36410. }
  36411. /**
  36412. * Remembers the state of the bound property and copy it to both accus.
  36413. */
  36414. saveOriginalState() {
  36415. const binding = this.binding;
  36416. const buffer = this.buffer,
  36417. stride = this.valueSize,
  36418. originalValueOffset = stride * this._origIndex;
  36419. binding.getValue( buffer, originalValueOffset );
  36420. // accu[0..1] := orig -- initially detect changes against the original
  36421. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  36422. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  36423. }
  36424. // Add to identity for additive
  36425. this._setIdentity();
  36426. this.cumulativeWeight = 0;
  36427. this.cumulativeWeightAdditive = 0;
  36428. }
  36429. /**
  36430. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  36431. */
  36432. restoreOriginalState() {
  36433. const originalValueOffset = this.valueSize * 3;
  36434. this.binding.setValue( this.buffer, originalValueOffset );
  36435. }
  36436. // internals
  36437. _setAdditiveIdentityNumeric() {
  36438. const startIndex = this._addIndex * this.valueSize;
  36439. const endIndex = startIndex + this.valueSize;
  36440. for ( let i = startIndex; i < endIndex; i ++ ) {
  36441. this.buffer[ i ] = 0;
  36442. }
  36443. }
  36444. _setAdditiveIdentityQuaternion() {
  36445. this._setAdditiveIdentityNumeric();
  36446. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  36447. }
  36448. _setAdditiveIdentityOther() {
  36449. const startIndex = this._origIndex * this.valueSize;
  36450. const targetIndex = this._addIndex * this.valueSize;
  36451. for ( let i = 0; i < this.valueSize; i ++ ) {
  36452. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  36453. }
  36454. }
  36455. // mix functions
  36456. _select( buffer, dstOffset, srcOffset, t, stride ) {
  36457. if ( t >= 0.5 ) {
  36458. for ( let i = 0; i !== stride; ++ i ) {
  36459. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  36460. }
  36461. }
  36462. }
  36463. _slerp( buffer, dstOffset, srcOffset, t ) {
  36464. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  36465. }
  36466. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  36467. const workOffset = this._workIndex * stride;
  36468. // Store result in intermediate buffer offset
  36469. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  36470. // Slerp to the intermediate result
  36471. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  36472. }
  36473. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  36474. const s = 1 - t;
  36475. for ( let i = 0; i !== stride; ++ i ) {
  36476. const j = dstOffset + i;
  36477. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  36478. }
  36479. }
  36480. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  36481. for ( let i = 0; i !== stride; ++ i ) {
  36482. const j = dstOffset + i;
  36483. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  36484. }
  36485. }
  36486. }
  36487. // Characters [].:/ are reserved for track binding syntax.
  36488. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  36489. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  36490. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  36491. // only latin characters, and the unicode \p{L} is not yet supported. So
  36492. // instead, we exclude reserved characters and match everything else.
  36493. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  36494. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  36495. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  36496. // be matched to parse the rest of the track name.
  36497. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  36498. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  36499. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  36500. // Object on target node, and accessor. May not contain reserved
  36501. // characters. Accessor may contain any character except closing bracket.
  36502. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  36503. // Property and accessor. May not contain reserved characters. Accessor may
  36504. // contain any non-bracket characters.
  36505. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  36506. const _trackRe = new RegExp( ''
  36507. + '^'
  36508. + _directoryRe
  36509. + _nodeRe
  36510. + _objectRe
  36511. + _propertyRe
  36512. + '$'
  36513. );
  36514. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  36515. class Composite {
  36516. constructor( targetGroup, path, optionalParsedPath ) {
  36517. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  36518. this._targetGroup = targetGroup;
  36519. this._bindings = targetGroup.subscribe_( path, parsedPath );
  36520. }
  36521. getValue( array, offset ) {
  36522. this.bind(); // bind all binding
  36523. const firstValidIndex = this._targetGroup.nCachedObjects_,
  36524. binding = this._bindings[ firstValidIndex ];
  36525. // and only call .getValue on the first
  36526. if ( binding !== undefined ) binding.getValue( array, offset );
  36527. }
  36528. setValue( array, offset ) {
  36529. const bindings = this._bindings;
  36530. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  36531. bindings[ i ].setValue( array, offset );
  36532. }
  36533. }
  36534. bind() {
  36535. const bindings = this._bindings;
  36536. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  36537. bindings[ i ].bind();
  36538. }
  36539. }
  36540. unbind() {
  36541. const bindings = this._bindings;
  36542. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  36543. bindings[ i ].unbind();
  36544. }
  36545. }
  36546. }
  36547. // Note: This class uses a State pattern on a per-method basis:
  36548. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  36549. // prototype version of these methods with one that represents
  36550. // the bound state. When the property is not found, the methods
  36551. // become no-ops.
  36552. /**
  36553. * This holds a reference to a real property in the scene graph; used internally.
  36554. */
  36555. class PropertyBinding {
  36556. /**
  36557. * Constructs a new property binding.
  36558. *
  36559. * @param {Object} rootNode - The root node.
  36560. * @param {string} path - The path.
  36561. * @param {?Object} [parsedPath] - The parsed path.
  36562. */
  36563. constructor( rootNode, path, parsedPath ) {
  36564. /**
  36565. * The object path to the animated property.
  36566. *
  36567. * @type {string}
  36568. */
  36569. this.path = path;
  36570. /**
  36571. * An object holding information about the path.
  36572. *
  36573. * @type {Object}
  36574. */
  36575. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  36576. /**
  36577. * The object owns the animated property.
  36578. *
  36579. * @type {?Object}
  36580. */
  36581. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  36582. /**
  36583. * The root node.
  36584. *
  36585. * @type {Object3D|Skeleton}
  36586. */
  36587. this.rootNode = rootNode;
  36588. // initial state of these methods that calls 'bind'
  36589. this.getValue = this._getValue_unbound;
  36590. this.setValue = this._setValue_unbound;
  36591. }
  36592. /**
  36593. * Factory method for creating a property binding from the given parameters.
  36594. *
  36595. * @static
  36596. * @param {Object} root - The root node.
  36597. * @param {string} path - The path.
  36598. * @param {?Object} [parsedPath] - The parsed path.
  36599. * @return {PropertyBinding|Composite} The created property binding or composite.
  36600. */
  36601. static create( root, path, parsedPath ) {
  36602. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  36603. return new PropertyBinding( root, path, parsedPath );
  36604. } else {
  36605. return new PropertyBinding.Composite( root, path, parsedPath );
  36606. }
  36607. }
  36608. /**
  36609. * Replaces spaces with underscores and removes unsupported characters from
  36610. * node names, to ensure compatibility with parseTrackName().
  36611. *
  36612. * @param {string} name - Node name to be sanitized.
  36613. * @return {string} The sanitized node name.
  36614. */
  36615. static sanitizeNodeName( name ) {
  36616. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  36617. }
  36618. /**
  36619. * Parses the given track name (an object path to an animated property) and
  36620. * returns an object with information about the path. Matches strings in the following forms:
  36621. *
  36622. * - nodeName.property
  36623. * - nodeName.property[accessor]
  36624. * - nodeName.material.property[accessor]
  36625. * - uuid.property[accessor]
  36626. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  36627. * - parentName/nodeName.property
  36628. * - parentName/parentName/nodeName.property[index]
  36629. * - .bone[Armature.DEF_cog].position
  36630. * - scene:helium_balloon_model:helium_balloon_model.position
  36631. *
  36632. * @static
  36633. * @param {string} trackName - The track name to parse.
  36634. * @return {Object} The parsed track name as an object.
  36635. */
  36636. static parseTrackName( trackName ) {
  36637. const matches = _trackRe.exec( trackName );
  36638. if ( matches === null ) {
  36639. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  36640. }
  36641. const results = {
  36642. // directoryName: matches[ 1 ], // (tschw) currently unused
  36643. nodeName: matches[ 2 ],
  36644. objectName: matches[ 3 ],
  36645. objectIndex: matches[ 4 ],
  36646. propertyName: matches[ 5 ], // required
  36647. propertyIndex: matches[ 6 ]
  36648. };
  36649. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  36650. if ( lastDot !== undefined && lastDot !== - 1 ) {
  36651. const objectName = results.nodeName.substring( lastDot + 1 );
  36652. // Object names must be checked against an allowlist. Otherwise, there
  36653. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  36654. // 'bar' could be the objectName, or part of a nodeName (which can
  36655. // include '.' characters).
  36656. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  36657. results.nodeName = results.nodeName.substring( 0, lastDot );
  36658. results.objectName = objectName;
  36659. }
  36660. }
  36661. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  36662. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  36663. }
  36664. return results;
  36665. }
  36666. /**
  36667. * Searches for a node in the hierarchy of the given root object by the given
  36668. * node name.
  36669. *
  36670. * @static
  36671. * @param {Object} root - The root object.
  36672. * @param {string|number} nodeName - The name of the node.
  36673. * @return {?Object} The found node. Returns `null` if no object was found.
  36674. */
  36675. static findNode( root, nodeName ) {
  36676. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  36677. return root;
  36678. }
  36679. // search into skeleton bones.
  36680. if ( root.skeleton ) {
  36681. const bone = root.skeleton.getBoneByName( nodeName );
  36682. if ( bone !== undefined ) {
  36683. return bone;
  36684. }
  36685. }
  36686. // search into node subtree.
  36687. if ( root.children ) {
  36688. const searchNodeSubtree = function ( children ) {
  36689. for ( let i = 0; i < children.length; i ++ ) {
  36690. const childNode = children[ i ];
  36691. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  36692. return childNode;
  36693. }
  36694. const result = searchNodeSubtree( childNode.children );
  36695. if ( result ) return result;
  36696. }
  36697. return null;
  36698. };
  36699. const subTreeNode = searchNodeSubtree( root.children );
  36700. if ( subTreeNode ) {
  36701. return subTreeNode;
  36702. }
  36703. }
  36704. return null;
  36705. }
  36706. // these are used to "bind" a nonexistent property
  36707. _getValue_unavailable() {}
  36708. _setValue_unavailable() {}
  36709. // Getters
  36710. _getValue_direct( buffer, offset ) {
  36711. buffer[ offset ] = this.targetObject[ this.propertyName ];
  36712. }
  36713. _getValue_array( buffer, offset ) {
  36714. const source = this.resolvedProperty;
  36715. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  36716. buffer[ offset ++ ] = source[ i ];
  36717. }
  36718. }
  36719. _getValue_arrayElement( buffer, offset ) {
  36720. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  36721. }
  36722. _getValue_toArray( buffer, offset ) {
  36723. this.resolvedProperty.toArray( buffer, offset );
  36724. }
  36725. // Direct
  36726. _setValue_direct( buffer, offset ) {
  36727. this.targetObject[ this.propertyName ] = buffer[ offset ];
  36728. }
  36729. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  36730. this.targetObject[ this.propertyName ] = buffer[ offset ];
  36731. this.targetObject.needsUpdate = true;
  36732. }
  36733. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36734. this.targetObject[ this.propertyName ] = buffer[ offset ];
  36735. this.targetObject.matrixWorldNeedsUpdate = true;
  36736. }
  36737. // EntireArray
  36738. _setValue_array( buffer, offset ) {
  36739. const dest = this.resolvedProperty;
  36740. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  36741. dest[ i ] = buffer[ offset ++ ];
  36742. }
  36743. }
  36744. _setValue_array_setNeedsUpdate( buffer, offset ) {
  36745. const dest = this.resolvedProperty;
  36746. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  36747. dest[ i ] = buffer[ offset ++ ];
  36748. }
  36749. this.targetObject.needsUpdate = true;
  36750. }
  36751. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36752. const dest = this.resolvedProperty;
  36753. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  36754. dest[ i ] = buffer[ offset ++ ];
  36755. }
  36756. this.targetObject.matrixWorldNeedsUpdate = true;
  36757. }
  36758. // ArrayElement
  36759. _setValue_arrayElement( buffer, offset ) {
  36760. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  36761. }
  36762. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  36763. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  36764. this.targetObject.needsUpdate = true;
  36765. }
  36766. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36767. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  36768. this.targetObject.matrixWorldNeedsUpdate = true;
  36769. }
  36770. // HasToFromArray
  36771. _setValue_fromArray( buffer, offset ) {
  36772. this.resolvedProperty.fromArray( buffer, offset );
  36773. }
  36774. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  36775. this.resolvedProperty.fromArray( buffer, offset );
  36776. this.targetObject.needsUpdate = true;
  36777. }
  36778. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  36779. this.resolvedProperty.fromArray( buffer, offset );
  36780. this.targetObject.matrixWorldNeedsUpdate = true;
  36781. }
  36782. _getValue_unbound( targetArray, offset ) {
  36783. this.bind();
  36784. this.getValue( targetArray, offset );
  36785. }
  36786. _setValue_unbound( sourceArray, offset ) {
  36787. this.bind();
  36788. this.setValue( sourceArray, offset );
  36789. }
  36790. /**
  36791. * Creates a getter / setter pair for the property tracked by this binding.
  36792. */
  36793. bind() {
  36794. let targetObject = this.node;
  36795. const parsedPath = this.parsedPath;
  36796. const objectName = parsedPath.objectName;
  36797. const propertyName = parsedPath.propertyName;
  36798. let propertyIndex = parsedPath.propertyIndex;
  36799. if ( ! targetObject ) {
  36800. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  36801. this.node = targetObject;
  36802. }
  36803. // set fail state so we can just 'return' on error
  36804. this.getValue = this._getValue_unavailable;
  36805. this.setValue = this._setValue_unavailable;
  36806. // ensure there is a value node
  36807. if ( ! targetObject ) {
  36808. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  36809. return;
  36810. }
  36811. if ( objectName ) {
  36812. let objectIndex = parsedPath.objectIndex;
  36813. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  36814. switch ( objectName ) {
  36815. case 'materials':
  36816. if ( ! targetObject.material ) {
  36817. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  36818. return;
  36819. }
  36820. if ( ! targetObject.material.materials ) {
  36821. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  36822. return;
  36823. }
  36824. targetObject = targetObject.material.materials;
  36825. break;
  36826. case 'bones':
  36827. if ( ! targetObject.skeleton ) {
  36828. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  36829. return;
  36830. }
  36831. // potential future optimization: skip this if propertyIndex is already an integer
  36832. // and convert the integer string to a true integer.
  36833. targetObject = targetObject.skeleton.bones;
  36834. // support resolving morphTarget names into indices.
  36835. for ( let i = 0; i < targetObject.length; i ++ ) {
  36836. if ( targetObject[ i ].name === objectIndex ) {
  36837. objectIndex = i;
  36838. break;
  36839. }
  36840. }
  36841. break;
  36842. case 'map':
  36843. if ( 'map' in targetObject ) {
  36844. targetObject = targetObject.map;
  36845. break;
  36846. }
  36847. if ( ! targetObject.material ) {
  36848. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  36849. return;
  36850. }
  36851. if ( ! targetObject.material.map ) {
  36852. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  36853. return;
  36854. }
  36855. targetObject = targetObject.material.map;
  36856. break;
  36857. default:
  36858. if ( targetObject[ objectName ] === undefined ) {
  36859. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  36860. return;
  36861. }
  36862. targetObject = targetObject[ objectName ];
  36863. }
  36864. if ( objectIndex !== undefined ) {
  36865. if ( targetObject[ objectIndex ] === undefined ) {
  36866. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  36867. return;
  36868. }
  36869. targetObject = targetObject[ objectIndex ];
  36870. }
  36871. }
  36872. // resolve property
  36873. const nodeProperty = targetObject[ propertyName ];
  36874. if ( nodeProperty === undefined ) {
  36875. const nodeName = parsedPath.nodeName;
  36876. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  36877. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  36878. return;
  36879. }
  36880. // determine versioning scheme
  36881. let versioning = this.Versioning.None;
  36882. this.targetObject = targetObject;
  36883. if ( targetObject.isMaterial === true ) {
  36884. versioning = this.Versioning.NeedsUpdate;
  36885. } else if ( targetObject.isObject3D === true ) {
  36886. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  36887. }
  36888. // determine how the property gets bound
  36889. let bindingType = this.BindingType.Direct;
  36890. if ( propertyIndex !== undefined ) {
  36891. // access a sub element of the property array (only primitives are supported right now)
  36892. if ( propertyName === 'morphTargetInfluences' ) {
  36893. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  36894. // support resolving morphTarget names into indices.
  36895. if ( ! targetObject.geometry ) {
  36896. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  36897. return;
  36898. }
  36899. if ( ! targetObject.geometry.morphAttributes ) {
  36900. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  36901. return;
  36902. }
  36903. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  36904. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  36905. }
  36906. }
  36907. bindingType = this.BindingType.ArrayElement;
  36908. this.resolvedProperty = nodeProperty;
  36909. this.propertyIndex = propertyIndex;
  36910. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  36911. // must use copy for Object3D.Euler/Quaternion
  36912. bindingType = this.BindingType.HasFromToArray;
  36913. this.resolvedProperty = nodeProperty;
  36914. } else if ( Array.isArray( nodeProperty ) ) {
  36915. bindingType = this.BindingType.EntireArray;
  36916. this.resolvedProperty = nodeProperty;
  36917. } else {
  36918. this.propertyName = propertyName;
  36919. }
  36920. // select getter / setter
  36921. this.getValue = this.GetterByBindingType[ bindingType ];
  36922. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  36923. }
  36924. /**
  36925. * Unbinds the property.
  36926. */
  36927. unbind() {
  36928. this.node = null;
  36929. // back to the prototype version of getValue / setValue
  36930. // note: avoiding to mutate the shape of 'this' via 'delete'
  36931. this.getValue = this._getValue_unbound;
  36932. this.setValue = this._setValue_unbound;
  36933. }
  36934. }
  36935. PropertyBinding.Composite = Composite;
  36936. PropertyBinding.prototype.BindingType = {
  36937. Direct: 0,
  36938. EntireArray: 1,
  36939. ArrayElement: 2,
  36940. HasFromToArray: 3
  36941. };
  36942. PropertyBinding.prototype.Versioning = {
  36943. None: 0,
  36944. NeedsUpdate: 1,
  36945. MatrixWorldNeedsUpdate: 2
  36946. };
  36947. PropertyBinding.prototype.GetterByBindingType = [
  36948. PropertyBinding.prototype._getValue_direct,
  36949. PropertyBinding.prototype._getValue_array,
  36950. PropertyBinding.prototype._getValue_arrayElement,
  36951. PropertyBinding.prototype._getValue_toArray,
  36952. ];
  36953. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  36954. [
  36955. // Direct
  36956. PropertyBinding.prototype._setValue_direct,
  36957. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  36958. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  36959. ], [
  36960. // EntireArray
  36961. PropertyBinding.prototype._setValue_array,
  36962. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  36963. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  36964. ], [
  36965. // ArrayElement
  36966. PropertyBinding.prototype._setValue_arrayElement,
  36967. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  36968. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  36969. ], [
  36970. // HasToFromArray
  36971. PropertyBinding.prototype._setValue_fromArray,
  36972. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  36973. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  36974. ]
  36975. ];
  36976. /**
  36977. * A group of objects that receives a shared animation state.
  36978. *
  36979. * Usage:
  36980. *
  36981. * - Add objects you would otherwise pass as 'root' to the
  36982. * constructor or the .clipAction method of AnimationMixer.
  36983. * - Instead pass this object as 'root'.
  36984. * - You can also add and remove objects later when the mixer is running.
  36985. *
  36986. * Note:
  36987. *
  36988. * - Objects of this class appear as one object to the mixer,
  36989. * so cache control of the individual objects must be done on the group.
  36990. *
  36991. * Limitation:
  36992. *
  36993. * - The animated properties must be compatible among the all objects in the group.
  36994. * - A single property can either be controlled through a target group or directly, but not both.
  36995. */
  36996. class AnimationObjectGroup {
  36997. /**
  36998. * Constructs a new animation group.
  36999. *
  37000. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37001. */
  37002. constructor() {
  37003. /**
  37004. * This flag can be used for type testing.
  37005. *
  37006. * @type {boolean}
  37007. * @readonly
  37008. * @default true
  37009. */
  37010. this.isAnimationObjectGroup = true;
  37011. /**
  37012. * The UUID of the 3D object.
  37013. *
  37014. * @type {string}
  37015. * @readonly
  37016. */
  37017. this.uuid = generateUUID();
  37018. // cached objects followed by the active ones
  37019. this._objects = Array.prototype.slice.call( arguments );
  37020. this.nCachedObjects_ = 0; // threshold
  37021. // note: read by PropertyBinding.Composite
  37022. const indices = {};
  37023. this._indicesByUUID = indices; // for bookkeeping
  37024. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37025. indices[ arguments[ i ].uuid ] = i;
  37026. }
  37027. this._paths = []; // inside: string
  37028. this._parsedPaths = []; // inside: { we don't care, here }
  37029. this._bindings = []; // inside: Array< PropertyBinding >
  37030. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37031. const scope = this;
  37032. this.stats = {
  37033. objects: {
  37034. get total() {
  37035. return scope._objects.length;
  37036. },
  37037. get inUse() {
  37038. return this.total - scope.nCachedObjects_;
  37039. }
  37040. },
  37041. get bindingsPerObject() {
  37042. return scope._bindings.length;
  37043. }
  37044. };
  37045. }
  37046. /**
  37047. * Adds an arbitrary number of objects to this animation group.
  37048. *
  37049. * @param {...Object3D} arguments - The 3D objects to add.
  37050. */
  37051. add() {
  37052. const objects = this._objects,
  37053. indicesByUUID = this._indicesByUUID,
  37054. paths = this._paths,
  37055. parsedPaths = this._parsedPaths,
  37056. bindings = this._bindings,
  37057. nBindings = bindings.length;
  37058. let knownObject = undefined,
  37059. nObjects = objects.length,
  37060. nCachedObjects = this.nCachedObjects_;
  37061. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37062. const object = arguments[ i ],
  37063. uuid = object.uuid;
  37064. let index = indicesByUUID[ uuid ];
  37065. if ( index === undefined ) {
  37066. // unknown object -> add it to the ACTIVE region
  37067. index = nObjects ++;
  37068. indicesByUUID[ uuid ] = index;
  37069. objects.push( object );
  37070. // accounting is done, now do the same for all bindings
  37071. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37072. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37073. }
  37074. } else if ( index < nCachedObjects ) {
  37075. knownObject = objects[ index ];
  37076. // move existing object to the ACTIVE region
  37077. const firstActiveIndex = -- nCachedObjects,
  37078. lastCachedObject = objects[ firstActiveIndex ];
  37079. indicesByUUID[ lastCachedObject.uuid ] = index;
  37080. objects[ index ] = lastCachedObject;
  37081. indicesByUUID[ uuid ] = firstActiveIndex;
  37082. objects[ firstActiveIndex ] = object;
  37083. // accounting is done, now do the same for all bindings
  37084. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37085. const bindingsForPath = bindings[ j ],
  37086. lastCached = bindingsForPath[ firstActiveIndex ];
  37087. let binding = bindingsForPath[ index ];
  37088. bindingsForPath[ index ] = lastCached;
  37089. if ( binding === undefined ) {
  37090. // since we do not bother to create new bindings
  37091. // for objects that are cached, the binding may
  37092. // or may not exist
  37093. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37094. }
  37095. bindingsForPath[ firstActiveIndex ] = binding;
  37096. }
  37097. } else if ( objects[ index ] !== knownObject ) {
  37098. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37099. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37100. } // else the object is already where we want it to be
  37101. } // for arguments
  37102. this.nCachedObjects_ = nCachedObjects;
  37103. }
  37104. /**
  37105. * Removes an arbitrary number of objects to this animation group
  37106. *
  37107. * @param {...Object3D} arguments - The 3D objects to remove.
  37108. */
  37109. remove() {
  37110. const objects = this._objects,
  37111. indicesByUUID = this._indicesByUUID,
  37112. bindings = this._bindings,
  37113. nBindings = bindings.length;
  37114. let nCachedObjects = this.nCachedObjects_;
  37115. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37116. const object = arguments[ i ],
  37117. uuid = object.uuid,
  37118. index = indicesByUUID[ uuid ];
  37119. if ( index !== undefined && index >= nCachedObjects ) {
  37120. // move existing object into the CACHED region
  37121. const lastCachedIndex = nCachedObjects ++,
  37122. firstActiveObject = objects[ lastCachedIndex ];
  37123. indicesByUUID[ firstActiveObject.uuid ] = index;
  37124. objects[ index ] = firstActiveObject;
  37125. indicesByUUID[ uuid ] = lastCachedIndex;
  37126. objects[ lastCachedIndex ] = object;
  37127. // accounting is done, now do the same for all bindings
  37128. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37129. const bindingsForPath = bindings[ j ],
  37130. firstActive = bindingsForPath[ lastCachedIndex ],
  37131. binding = bindingsForPath[ index ];
  37132. bindingsForPath[ index ] = firstActive;
  37133. bindingsForPath[ lastCachedIndex ] = binding;
  37134. }
  37135. }
  37136. } // for arguments
  37137. this.nCachedObjects_ = nCachedObjects;
  37138. }
  37139. /**
  37140. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37141. *
  37142. * @param {...Object3D} arguments - The 3D objects to uncache.
  37143. */
  37144. uncache() {
  37145. const objects = this._objects,
  37146. indicesByUUID = this._indicesByUUID,
  37147. bindings = this._bindings,
  37148. nBindings = bindings.length;
  37149. let nCachedObjects = this.nCachedObjects_,
  37150. nObjects = objects.length;
  37151. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37152. const object = arguments[ i ],
  37153. uuid = object.uuid,
  37154. index = indicesByUUID[ uuid ];
  37155. if ( index !== undefined ) {
  37156. delete indicesByUUID[ uuid ];
  37157. if ( index < nCachedObjects ) {
  37158. // object is cached, shrink the CACHED region
  37159. const firstActiveIndex = -- nCachedObjects,
  37160. lastCachedObject = objects[ firstActiveIndex ],
  37161. lastIndex = -- nObjects,
  37162. lastObject = objects[ lastIndex ];
  37163. // last cached object takes this object's place
  37164. indicesByUUID[ lastCachedObject.uuid ] = index;
  37165. objects[ index ] = lastCachedObject;
  37166. // last object goes to the activated slot and pop
  37167. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37168. objects[ firstActiveIndex ] = lastObject;
  37169. objects.pop();
  37170. // accounting is done, now do the same for all bindings
  37171. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37172. const bindingsForPath = bindings[ j ],
  37173. lastCached = bindingsForPath[ firstActiveIndex ],
  37174. last = bindingsForPath[ lastIndex ];
  37175. bindingsForPath[ index ] = lastCached;
  37176. bindingsForPath[ firstActiveIndex ] = last;
  37177. bindingsForPath.pop();
  37178. }
  37179. } else {
  37180. // object is active, just swap with the last and pop
  37181. const lastIndex = -- nObjects,
  37182. lastObject = objects[ lastIndex ];
  37183. if ( lastIndex > 0 ) {
  37184. indicesByUUID[ lastObject.uuid ] = index;
  37185. }
  37186. objects[ index ] = lastObject;
  37187. objects.pop();
  37188. // accounting is done, now do the same for all bindings
  37189. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37190. const bindingsForPath = bindings[ j ];
  37191. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37192. bindingsForPath.pop();
  37193. }
  37194. } // cached or active
  37195. } // if object is known
  37196. } // for arguments
  37197. this.nCachedObjects_ = nCachedObjects;
  37198. }
  37199. // Internal interface used by befriended PropertyBinding.Composite:
  37200. subscribe_( path, parsedPath ) {
  37201. // returns an array of bindings for the given path that is changed
  37202. // according to the contained objects in the group
  37203. const indicesByPath = this._bindingsIndicesByPath;
  37204. let index = indicesByPath[ path ];
  37205. const bindings = this._bindings;
  37206. if ( index !== undefined ) return bindings[ index ];
  37207. const paths = this._paths,
  37208. parsedPaths = this._parsedPaths,
  37209. objects = this._objects,
  37210. nObjects = objects.length,
  37211. nCachedObjects = this.nCachedObjects_,
  37212. bindingsForPath = new Array( nObjects );
  37213. index = bindings.length;
  37214. indicesByPath[ path ] = index;
  37215. paths.push( path );
  37216. parsedPaths.push( parsedPath );
  37217. bindings.push( bindingsForPath );
  37218. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37219. const object = objects[ i ];
  37220. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37221. }
  37222. return bindingsForPath;
  37223. }
  37224. unsubscribe_( path ) {
  37225. // tells the group to forget about a property path and no longer
  37226. // update the array previously obtained with 'subscribe_'
  37227. const indicesByPath = this._bindingsIndicesByPath,
  37228. index = indicesByPath[ path ];
  37229. if ( index !== undefined ) {
  37230. const paths = this._paths,
  37231. parsedPaths = this._parsedPaths,
  37232. bindings = this._bindings,
  37233. lastBindingsIndex = bindings.length - 1,
  37234. lastBindings = bindings[ lastBindingsIndex ],
  37235. lastBindingsPath = path[ lastBindingsIndex ];
  37236. indicesByPath[ lastBindingsPath ] = index;
  37237. bindings[ index ] = lastBindings;
  37238. bindings.pop();
  37239. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37240. parsedPaths.pop();
  37241. paths[ index ] = paths[ lastBindingsIndex ];
  37242. paths.pop();
  37243. }
  37244. }
  37245. }
  37246. /**
  37247. * An instance of `AnimationAction` schedules the playback of an animation which is
  37248. * stored in {@link AnimationClip}.
  37249. */
  37250. class AnimationAction {
  37251. /**
  37252. * Constructs a new animation action.
  37253. *
  37254. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37255. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37256. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37257. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37258. */
  37259. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37260. this._mixer = mixer;
  37261. this._clip = clip;
  37262. this._localRoot = localRoot;
  37263. /**
  37264. * Defines how the animation is blended/combined when two or more animations
  37265. * are simultaneously played.
  37266. *
  37267. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37268. */
  37269. this.blendMode = blendMode;
  37270. const tracks = clip.tracks,
  37271. nTracks = tracks.length,
  37272. interpolants = new Array( nTracks );
  37273. const interpolantSettings = {
  37274. endingStart: ZeroCurvatureEnding,
  37275. endingEnd: ZeroCurvatureEnding
  37276. };
  37277. for ( let i = 0; i !== nTracks; ++ i ) {
  37278. const interpolant = tracks[ i ].createInterpolant( null );
  37279. interpolants[ i ] = interpolant;
  37280. interpolant.settings = interpolantSettings;
  37281. }
  37282. this._interpolantSettings = interpolantSettings;
  37283. this._interpolants = interpolants; // bound by the mixer
  37284. // inside: PropertyMixer (managed by the mixer)
  37285. this._propertyBindings = new Array( nTracks );
  37286. this._cacheIndex = null; // for the memory manager
  37287. this._byClipCacheIndex = null; // for the memory manager
  37288. this._timeScaleInterpolant = null;
  37289. this._weightInterpolant = null;
  37290. /**
  37291. * The loop mode, set via {@link AnimationAction#setLoop}.
  37292. *
  37293. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  37294. * @default LoopRepeat
  37295. */
  37296. this.loop = LoopRepeat;
  37297. this._loopCount = - 1;
  37298. // global mixer time when the action is to be started
  37299. // it's set back to 'null' upon start of the action
  37300. this._startTime = null;
  37301. /**
  37302. * The local time of this action (in seconds, starting with `0`).
  37303. *
  37304. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  37305. * loop state).
  37306. *
  37307. * @type {number}
  37308. * @default Infinity
  37309. */
  37310. this.time = 0;
  37311. /**
  37312. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  37313. * animation to pause. Negative values cause the animation to play backwards.
  37314. *
  37315. * @type {number}
  37316. * @default 1
  37317. */
  37318. this.timeScale = 1;
  37319. this._effectiveTimeScale = 1;
  37320. /**
  37321. * The degree of influence of this action (in the interval `[0, 1]`). Values
  37322. * between `0` (no impact) and `1` (full impact) can be used to blend between
  37323. * several actions.
  37324. *
  37325. * @type {number}
  37326. * @default 1
  37327. */
  37328. this.weight = 1;
  37329. this._effectiveWeight = 1;
  37330. /**
  37331. * The number of repetitions of the performed clip over the course of this action.
  37332. * Can be set via {@link AnimationAction#setLoop}.
  37333. *
  37334. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  37335. * `THREE:LoopOnce`.
  37336. *
  37337. * @type {number}
  37338. * @default Infinity
  37339. */
  37340. this.repetitions = Infinity;
  37341. /**
  37342. * If set to `true`, the playback of the action is paused.
  37343. *
  37344. * @type {boolean}
  37345. * @default false
  37346. */
  37347. this.paused = false;
  37348. /**
  37349. * If set to `false`, the action is disabled so it has no impact.
  37350. *
  37351. * When the action is re-enabled, the animation continues from its current
  37352. * time (setting `enabled` to `false` doesn't reset the action).
  37353. *
  37354. * @type {boolean}
  37355. * @default true
  37356. */
  37357. this.enabled = true;
  37358. /**
  37359. * If set to true the animation will automatically be paused on its last frame.
  37360. *
  37361. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  37362. * to `false` when the last loop of the action has finished, so that this action has
  37363. * no further impact.
  37364. *
  37365. * Note: This member has no impact if the action is interrupted (it
  37366. * has only an effect if its last loop has really finished).
  37367. *
  37368. * @type {boolean}
  37369. * @default false
  37370. */
  37371. this.clampWhenFinished = false;
  37372. /**
  37373. * Enables smooth interpolation without separate clips for start, loop and end.
  37374. *
  37375. * @type {boolean}
  37376. * @default true
  37377. */
  37378. this.zeroSlopeAtStart = true;
  37379. /**
  37380. * Enables smooth interpolation without separate clips for start, loop and end.
  37381. *
  37382. * @type {boolean}
  37383. * @default true
  37384. */
  37385. this.zeroSlopeAtEnd = true;
  37386. }
  37387. /**
  37388. * Starts the playback of the animation.
  37389. *
  37390. * @return {AnimationAction} A reference to this animation action.
  37391. */
  37392. play() {
  37393. this._mixer._activateAction( this );
  37394. return this;
  37395. }
  37396. /**
  37397. * Stops the playback of the animation.
  37398. *
  37399. * @return {AnimationAction} A reference to this animation action.
  37400. */
  37401. stop() {
  37402. this._mixer._deactivateAction( this );
  37403. return this.reset();
  37404. }
  37405. /**
  37406. * Resets the playback of the animation.
  37407. *
  37408. * @return {AnimationAction} A reference to this animation action.
  37409. */
  37410. reset() {
  37411. this.paused = false;
  37412. this.enabled = true;
  37413. this.time = 0; // restart clip
  37414. this._loopCount = - 1;// forget previous loops
  37415. this._startTime = null;// forget scheduling
  37416. return this.stopFading().stopWarping();
  37417. }
  37418. /**
  37419. * Returns `true` if the animation is running.
  37420. *
  37421. * @return {boolean} Whether the animation is running or not.
  37422. */
  37423. isRunning() {
  37424. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  37425. this._startTime === null && this._mixer._isActiveAction( this );
  37426. }
  37427. /**
  37428. * Returns `true` when {@link AnimationAction#play} has been called.
  37429. *
  37430. * @return {boolean} Whether the animation is scheduled or not.
  37431. */
  37432. isScheduled() {
  37433. return this._mixer._isActiveAction( this );
  37434. }
  37435. /**
  37436. * Defines the time when the animation should start.
  37437. *
  37438. * @param {number} time - The start time in seconds.
  37439. * @return {AnimationAction} A reference to this animation action.
  37440. */
  37441. startAt( time ) {
  37442. this._startTime = time;
  37443. return this;
  37444. }
  37445. /**
  37446. * Configures the loop settings for this action.
  37447. *
  37448. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  37449. * @param {number} repetitions - The number of repetitions.
  37450. * @return {AnimationAction} A reference to this animation action.
  37451. */
  37452. setLoop( mode, repetitions ) {
  37453. this.loop = mode;
  37454. this.repetitions = repetitions;
  37455. return this;
  37456. }
  37457. /**
  37458. * Sets the effective weight of this action.
  37459. *
  37460. * An action has no effect and thus an effective weight of zero when the
  37461. * action is disabled.
  37462. *
  37463. * @param {number} weight - The weight to set.
  37464. * @return {AnimationAction} A reference to this animation action.
  37465. */
  37466. setEffectiveWeight( weight ) {
  37467. this.weight = weight;
  37468. // note: same logic as when updated at runtime
  37469. this._effectiveWeight = this.enabled ? weight : 0;
  37470. return this.stopFading();
  37471. }
  37472. /**
  37473. * Returns the effective weight of this action.
  37474. *
  37475. * @return {number} The effective weight.
  37476. */
  37477. getEffectiveWeight() {
  37478. return this._effectiveWeight;
  37479. }
  37480. /**
  37481. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  37482. * within the passed time interval.
  37483. *
  37484. * @param {number} duration - The duration of the fade.
  37485. * @return {AnimationAction} A reference to this animation action.
  37486. */
  37487. fadeIn( duration ) {
  37488. return this._scheduleFading( duration, 0, 1 );
  37489. }
  37490. /**
  37491. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  37492. * within the passed time interval.
  37493. *
  37494. * @param {number} duration - The duration of the fade.
  37495. * @return {AnimationAction} A reference to this animation action.
  37496. */
  37497. fadeOut( duration ) {
  37498. return this._scheduleFading( duration, 1, 0 );
  37499. }
  37500. /**
  37501. * Causes this action to fade in and the given action to fade out,
  37502. * within the passed time interval.
  37503. *
  37504. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  37505. * @param {number} duration - The duration of the fade.
  37506. * @param {boolean} [warp=false] - Whether warping should be used or not.
  37507. * @return {AnimationAction} A reference to this animation action.
  37508. */
  37509. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  37510. fadeOutAction.fadeOut( duration );
  37511. this.fadeIn( duration );
  37512. if ( warp === true ) {
  37513. const fadeInDuration = this._clip.duration,
  37514. fadeOutDuration = fadeOutAction._clip.duration,
  37515. startEndRatio = fadeOutDuration / fadeInDuration,
  37516. endStartRatio = fadeInDuration / fadeOutDuration;
  37517. fadeOutAction.warp( 1.0, startEndRatio, duration );
  37518. this.warp( endStartRatio, 1.0, duration );
  37519. }
  37520. return this;
  37521. }
  37522. /**
  37523. * Causes this action to fade out and the given action to fade in,
  37524. * within the passed time interval.
  37525. *
  37526. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  37527. * @param {number} duration - The duration of the fade.
  37528. * @param {boolean} [warp=false] - Whether warping should be used or not.
  37529. * @return {AnimationAction} A reference to this animation action.
  37530. */
  37531. crossFadeTo( fadeInAction, duration, warp = false ) {
  37532. return fadeInAction.crossFadeFrom( this, duration, warp );
  37533. }
  37534. /**
  37535. * Stops any fading which is applied to this action.
  37536. *
  37537. * @return {AnimationAction} A reference to this animation action.
  37538. */
  37539. stopFading() {
  37540. const weightInterpolant = this._weightInterpolant;
  37541. if ( weightInterpolant !== null ) {
  37542. this._weightInterpolant = null;
  37543. this._mixer._takeBackControlInterpolant( weightInterpolant );
  37544. }
  37545. return this;
  37546. }
  37547. /**
  37548. * Sets the effective time scale of this action.
  37549. *
  37550. * An action has no effect and thus an effective time scale of zero when the
  37551. * action is paused.
  37552. *
  37553. * @param {number} timeScale - The time scale to set.
  37554. * @return {AnimationAction} A reference to this animation action.
  37555. */
  37556. setEffectiveTimeScale( timeScale ) {
  37557. this.timeScale = timeScale;
  37558. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  37559. return this.stopWarping();
  37560. }
  37561. /**
  37562. * Returns the effective time scale of this action.
  37563. *
  37564. * @return {number} The effective time scale.
  37565. */
  37566. getEffectiveTimeScale() {
  37567. return this._effectiveTimeScale;
  37568. }
  37569. /**
  37570. * Sets the duration for a single loop of this action.
  37571. *
  37572. * @param {number} duration - The duration to set.
  37573. * @return {AnimationAction} A reference to this animation action.
  37574. */
  37575. setDuration( duration ) {
  37576. this.timeScale = this._clip.duration / duration;
  37577. return this.stopWarping();
  37578. }
  37579. /**
  37580. * Synchronizes this action with the passed other action.
  37581. *
  37582. * @param {AnimationAction} action - The action to sync with.
  37583. * @return {AnimationAction} A reference to this animation action.
  37584. */
  37585. syncWith( action ) {
  37586. this.time = action.time;
  37587. this.timeScale = action.timeScale;
  37588. return this.stopWarping();
  37589. }
  37590. /**
  37591. * Decelerates this animation's speed to `0` within the passed time interval.
  37592. *
  37593. * @param {number} duration - The duration.
  37594. * @return {AnimationAction} A reference to this animation action.
  37595. */
  37596. halt( duration ) {
  37597. return this.warp( this._effectiveTimeScale, 0, duration );
  37598. }
  37599. /**
  37600. * Changes the playback speed, within the passed time interval, by modifying
  37601. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  37602. * `endTimeScale`.
  37603. *
  37604. * @param {number} startTimeScale - The start time scale.
  37605. * @param {number} endTimeScale - The end time scale.
  37606. * @param {number} duration - The duration.
  37607. * @return {AnimationAction} A reference to this animation action.
  37608. */
  37609. warp( startTimeScale, endTimeScale, duration ) {
  37610. const mixer = this._mixer,
  37611. now = mixer.time,
  37612. timeScale = this.timeScale;
  37613. let interpolant = this._timeScaleInterpolant;
  37614. if ( interpolant === null ) {
  37615. interpolant = mixer._lendControlInterpolant();
  37616. this._timeScaleInterpolant = interpolant;
  37617. }
  37618. const times = interpolant.parameterPositions,
  37619. values = interpolant.sampleValues;
  37620. times[ 0 ] = now;
  37621. times[ 1 ] = now + duration;
  37622. values[ 0 ] = startTimeScale / timeScale;
  37623. values[ 1 ] = endTimeScale / timeScale;
  37624. return this;
  37625. }
  37626. /**
  37627. * Stops any scheduled warping which is applied to this action.
  37628. *
  37629. * @return {AnimationAction} A reference to this animation action.
  37630. */
  37631. stopWarping() {
  37632. const timeScaleInterpolant = this._timeScaleInterpolant;
  37633. if ( timeScaleInterpolant !== null ) {
  37634. this._timeScaleInterpolant = null;
  37635. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  37636. }
  37637. return this;
  37638. }
  37639. /**
  37640. * Returns the animation mixer of this animation action.
  37641. *
  37642. * @return {AnimationMixer} The animation mixer.
  37643. */
  37644. getMixer() {
  37645. return this._mixer;
  37646. }
  37647. /**
  37648. * Returns the animation clip of this animation action.
  37649. *
  37650. * @return {AnimationClip} The animation clip.
  37651. */
  37652. getClip() {
  37653. return this._clip;
  37654. }
  37655. /**
  37656. * Returns the root object of this animation action.
  37657. *
  37658. * @return {Object3D} The root object.
  37659. */
  37660. getRoot() {
  37661. return this._localRoot || this._mixer._root;
  37662. }
  37663. // Interna
  37664. _update( time, deltaTime, timeDirection, accuIndex ) {
  37665. // called by the mixer
  37666. if ( ! this.enabled ) {
  37667. // call ._updateWeight() to update ._effectiveWeight
  37668. this._updateWeight( time );
  37669. return;
  37670. }
  37671. const startTime = this._startTime;
  37672. if ( startTime !== null ) {
  37673. // check for scheduled start of action
  37674. const timeRunning = ( time - startTime ) * timeDirection;
  37675. if ( timeRunning < 0 || timeDirection === 0 ) {
  37676. deltaTime = 0;
  37677. } else {
  37678. this._startTime = null; // unschedule
  37679. deltaTime = timeDirection * timeRunning;
  37680. }
  37681. }
  37682. // apply time scale and advance time
  37683. deltaTime *= this._updateTimeScale( time );
  37684. const clipTime = this._updateTime( deltaTime );
  37685. // note: _updateTime may disable the action resulting in
  37686. // an effective weight of 0
  37687. const weight = this._updateWeight( time );
  37688. if ( weight > 0 ) {
  37689. const interpolants = this._interpolants;
  37690. const propertyMixers = this._propertyBindings;
  37691. switch ( this.blendMode ) {
  37692. case AdditiveAnimationBlendMode:
  37693. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  37694. interpolants[ j ].evaluate( clipTime );
  37695. propertyMixers[ j ].accumulateAdditive( weight );
  37696. }
  37697. break;
  37698. case NormalAnimationBlendMode:
  37699. default:
  37700. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  37701. interpolants[ j ].evaluate( clipTime );
  37702. propertyMixers[ j ].accumulate( accuIndex, weight );
  37703. }
  37704. }
  37705. }
  37706. }
  37707. _updateWeight( time ) {
  37708. let weight = 0;
  37709. if ( this.enabled ) {
  37710. weight = this.weight;
  37711. const interpolant = this._weightInterpolant;
  37712. if ( interpolant !== null ) {
  37713. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  37714. weight *= interpolantValue;
  37715. if ( time > interpolant.parameterPositions[ 1 ] ) {
  37716. this.stopFading();
  37717. if ( interpolantValue === 0 ) {
  37718. // faded out, disable
  37719. this.enabled = false;
  37720. }
  37721. }
  37722. }
  37723. }
  37724. this._effectiveWeight = weight;
  37725. return weight;
  37726. }
  37727. _updateTimeScale( time ) {
  37728. let timeScale = 0;
  37729. if ( ! this.paused ) {
  37730. timeScale = this.timeScale;
  37731. const interpolant = this._timeScaleInterpolant;
  37732. if ( interpolant !== null ) {
  37733. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  37734. timeScale *= interpolantValue;
  37735. if ( time > interpolant.parameterPositions[ 1 ] ) {
  37736. this.stopWarping();
  37737. if ( timeScale === 0 ) {
  37738. // motion has halted, pause
  37739. this.paused = true;
  37740. } else {
  37741. // warp done - apply final time scale
  37742. this.timeScale = timeScale;
  37743. }
  37744. }
  37745. }
  37746. }
  37747. this._effectiveTimeScale = timeScale;
  37748. return timeScale;
  37749. }
  37750. _updateTime( deltaTime ) {
  37751. const duration = this._clip.duration;
  37752. const loop = this.loop;
  37753. let time = this.time + deltaTime;
  37754. let loopCount = this._loopCount;
  37755. const pingPong = ( loop === LoopPingPong );
  37756. if ( deltaTime === 0 ) {
  37757. if ( loopCount === - 1 ) return time;
  37758. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  37759. }
  37760. if ( loop === LoopOnce ) {
  37761. if ( loopCount === - 1 ) {
  37762. // just started
  37763. this._loopCount = 0;
  37764. this._setEndings( true, true, false );
  37765. }
  37766. handle_stop: {
  37767. if ( time >= duration ) {
  37768. time = duration;
  37769. } else if ( time < 0 ) {
  37770. time = 0;
  37771. } else {
  37772. this.time = time;
  37773. break handle_stop;
  37774. }
  37775. if ( this.clampWhenFinished ) this.paused = true;
  37776. else this.enabled = false;
  37777. this.time = time;
  37778. this._mixer.dispatchEvent( {
  37779. type: 'finished', action: this,
  37780. direction: deltaTime < 0 ? - 1 : 1
  37781. } );
  37782. }
  37783. } else { // repetitive Repeat or PingPong
  37784. if ( loopCount === - 1 ) {
  37785. // just started
  37786. if ( deltaTime >= 0 ) {
  37787. loopCount = 0;
  37788. this._setEndings( true, this.repetitions === 0, pingPong );
  37789. } else {
  37790. // when looping in reverse direction, the initial
  37791. // transition through zero counts as a repetition,
  37792. // so leave loopCount at -1
  37793. this._setEndings( this.repetitions === 0, true, pingPong );
  37794. }
  37795. }
  37796. if ( time >= duration || time < 0 ) {
  37797. // wrap around
  37798. const loopDelta = Math.floor( time / duration ); // signed
  37799. time -= duration * loopDelta;
  37800. loopCount += Math.abs( loopDelta );
  37801. const pending = this.repetitions - loopCount;
  37802. if ( pending <= 0 ) {
  37803. // have to stop (switch state, clamp time, fire event)
  37804. if ( this.clampWhenFinished ) this.paused = true;
  37805. else this.enabled = false;
  37806. time = deltaTime > 0 ? duration : 0;
  37807. this.time = time;
  37808. this._mixer.dispatchEvent( {
  37809. type: 'finished', action: this,
  37810. direction: deltaTime > 0 ? 1 : - 1
  37811. } );
  37812. } else {
  37813. // keep running
  37814. if ( pending === 1 ) {
  37815. // entering the last round
  37816. const atStart = deltaTime < 0;
  37817. this._setEndings( atStart, ! atStart, pingPong );
  37818. } else {
  37819. this._setEndings( false, false, pingPong );
  37820. }
  37821. this._loopCount = loopCount;
  37822. this.time = time;
  37823. this._mixer.dispatchEvent( {
  37824. type: 'loop', action: this, loopDelta: loopDelta
  37825. } );
  37826. }
  37827. } else {
  37828. this.time = time;
  37829. }
  37830. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  37831. // invert time for the "pong round"
  37832. return duration - time;
  37833. }
  37834. }
  37835. return time;
  37836. }
  37837. _setEndings( atStart, atEnd, pingPong ) {
  37838. const settings = this._interpolantSettings;
  37839. if ( pingPong ) {
  37840. settings.endingStart = ZeroSlopeEnding;
  37841. settings.endingEnd = ZeroSlopeEnding;
  37842. } else {
  37843. // assuming for LoopOnce atStart == atEnd == true
  37844. if ( atStart ) {
  37845. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  37846. } else {
  37847. settings.endingStart = WrapAroundEnding;
  37848. }
  37849. if ( atEnd ) {
  37850. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  37851. } else {
  37852. settings.endingEnd = WrapAroundEnding;
  37853. }
  37854. }
  37855. }
  37856. _scheduleFading( duration, weightNow, weightThen ) {
  37857. const mixer = this._mixer, now = mixer.time;
  37858. let interpolant = this._weightInterpolant;
  37859. if ( interpolant === null ) {
  37860. interpolant = mixer._lendControlInterpolant();
  37861. this._weightInterpolant = interpolant;
  37862. }
  37863. const times = interpolant.parameterPositions,
  37864. values = interpolant.sampleValues;
  37865. times[ 0 ] = now;
  37866. values[ 0 ] = weightNow;
  37867. times[ 1 ] = now + duration;
  37868. values[ 1 ] = weightThen;
  37869. return this;
  37870. }
  37871. }
  37872. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  37873. /**
  37874. * `AnimationMixer` is a player for animations on a particular object in
  37875. * the scene. When multiple objects in the scene are animated independently,
  37876. * one `AnimationMixer` may be used for each object.
  37877. */
  37878. class AnimationMixer extends EventDispatcher {
  37879. /**
  37880. * Constructs a new animation mixer.
  37881. *
  37882. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  37883. */
  37884. constructor( root ) {
  37885. super();
  37886. this._root = root;
  37887. this._initMemoryManager();
  37888. this._accuIndex = 0;
  37889. /**
  37890. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  37891. *
  37892. * @type {number}
  37893. * @default 0
  37894. */
  37895. this.time = 0;
  37896. /**
  37897. * A scaling factor for the global time.
  37898. *
  37899. * Note: Setting this member to `0` and later back to `1` is a
  37900. * possibility to pause/unpause all actions that are controlled by this
  37901. * mixer.
  37902. *
  37903. * @type {number}
  37904. * @default 1
  37905. */
  37906. this.timeScale = 1.0;
  37907. }
  37908. _bindAction( action, prototypeAction ) {
  37909. const root = action._localRoot || this._root,
  37910. tracks = action._clip.tracks,
  37911. nTracks = tracks.length,
  37912. bindings = action._propertyBindings,
  37913. interpolants = action._interpolants,
  37914. rootUuid = root.uuid,
  37915. bindingsByRoot = this._bindingsByRootAndName;
  37916. let bindingsByName = bindingsByRoot[ rootUuid ];
  37917. if ( bindingsByName === undefined ) {
  37918. bindingsByName = {};
  37919. bindingsByRoot[ rootUuid ] = bindingsByName;
  37920. }
  37921. for ( let i = 0; i !== nTracks; ++ i ) {
  37922. const track = tracks[ i ],
  37923. trackName = track.name;
  37924. let binding = bindingsByName[ trackName ];
  37925. if ( binding !== undefined ) {
  37926. ++ binding.referenceCount;
  37927. bindings[ i ] = binding;
  37928. } else {
  37929. binding = bindings[ i ];
  37930. if ( binding !== undefined ) {
  37931. // existing binding, make sure the cache knows
  37932. if ( binding._cacheIndex === null ) {
  37933. ++ binding.referenceCount;
  37934. this._addInactiveBinding( binding, rootUuid, trackName );
  37935. }
  37936. continue;
  37937. }
  37938. const path = prototypeAction && prototypeAction.
  37939. _propertyBindings[ i ].binding.parsedPath;
  37940. binding = new PropertyMixer(
  37941. PropertyBinding.create( root, trackName, path ),
  37942. track.ValueTypeName, track.getValueSize() );
  37943. ++ binding.referenceCount;
  37944. this._addInactiveBinding( binding, rootUuid, trackName );
  37945. bindings[ i ] = binding;
  37946. }
  37947. interpolants[ i ].resultBuffer = binding.buffer;
  37948. }
  37949. }
  37950. _activateAction( action ) {
  37951. if ( ! this._isActiveAction( action ) ) {
  37952. if ( action._cacheIndex === null ) {
  37953. // this action has been forgotten by the cache, but the user
  37954. // appears to be still using it -> rebind
  37955. const rootUuid = ( action._localRoot || this._root ).uuid,
  37956. clipUuid = action._clip.uuid,
  37957. actionsForClip = this._actionsByClip[ clipUuid ];
  37958. this._bindAction( action,
  37959. actionsForClip && actionsForClip.knownActions[ 0 ] );
  37960. this._addInactiveAction( action, clipUuid, rootUuid );
  37961. }
  37962. const bindings = action._propertyBindings;
  37963. // increment reference counts / sort out state
  37964. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  37965. const binding = bindings[ i ];
  37966. if ( binding.useCount ++ === 0 ) {
  37967. this._lendBinding( binding );
  37968. binding.saveOriginalState();
  37969. }
  37970. }
  37971. this._lendAction( action );
  37972. }
  37973. }
  37974. _deactivateAction( action ) {
  37975. if ( this._isActiveAction( action ) ) {
  37976. const bindings = action._propertyBindings;
  37977. // decrement reference counts / sort out state
  37978. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  37979. const binding = bindings[ i ];
  37980. if ( -- binding.useCount === 0 ) {
  37981. binding.restoreOriginalState();
  37982. this._takeBackBinding( binding );
  37983. }
  37984. }
  37985. this._takeBackAction( action );
  37986. }
  37987. }
  37988. // Memory manager
  37989. _initMemoryManager() {
  37990. this._actions = []; // 'nActiveActions' followed by inactive ones
  37991. this._nActiveActions = 0;
  37992. this._actionsByClip = {};
  37993. // inside:
  37994. // {
  37995. // knownActions: Array< AnimationAction > - used as prototypes
  37996. // actionByRoot: AnimationAction - lookup
  37997. // }
  37998. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  37999. this._nActiveBindings = 0;
  38000. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38001. this._controlInterpolants = []; // same game as above
  38002. this._nActiveControlInterpolants = 0;
  38003. const scope = this;
  38004. this.stats = {
  38005. actions: {
  38006. get total() {
  38007. return scope._actions.length;
  38008. },
  38009. get inUse() {
  38010. return scope._nActiveActions;
  38011. }
  38012. },
  38013. bindings: {
  38014. get total() {
  38015. return scope._bindings.length;
  38016. },
  38017. get inUse() {
  38018. return scope._nActiveBindings;
  38019. }
  38020. },
  38021. controlInterpolants: {
  38022. get total() {
  38023. return scope._controlInterpolants.length;
  38024. },
  38025. get inUse() {
  38026. return scope._nActiveControlInterpolants;
  38027. }
  38028. }
  38029. };
  38030. }
  38031. // Memory management for AnimationAction objects
  38032. _isActiveAction( action ) {
  38033. const index = action._cacheIndex;
  38034. return index !== null && index < this._nActiveActions;
  38035. }
  38036. _addInactiveAction( action, clipUuid, rootUuid ) {
  38037. const actions = this._actions,
  38038. actionsByClip = this._actionsByClip;
  38039. let actionsForClip = actionsByClip[ clipUuid ];
  38040. if ( actionsForClip === undefined ) {
  38041. actionsForClip = {
  38042. knownActions: [ action ],
  38043. actionByRoot: {}
  38044. };
  38045. action._byClipCacheIndex = 0;
  38046. actionsByClip[ clipUuid ] = actionsForClip;
  38047. } else {
  38048. const knownActions = actionsForClip.knownActions;
  38049. action._byClipCacheIndex = knownActions.length;
  38050. knownActions.push( action );
  38051. }
  38052. action._cacheIndex = actions.length;
  38053. actions.push( action );
  38054. actionsForClip.actionByRoot[ rootUuid ] = action;
  38055. }
  38056. _removeInactiveAction( action ) {
  38057. const actions = this._actions,
  38058. lastInactiveAction = actions[ actions.length - 1 ],
  38059. cacheIndex = action._cacheIndex;
  38060. lastInactiveAction._cacheIndex = cacheIndex;
  38061. actions[ cacheIndex ] = lastInactiveAction;
  38062. actions.pop();
  38063. action._cacheIndex = null;
  38064. const clipUuid = action._clip.uuid,
  38065. actionsByClip = this._actionsByClip,
  38066. actionsForClip = actionsByClip[ clipUuid ],
  38067. knownActionsForClip = actionsForClip.knownActions,
  38068. lastKnownAction =
  38069. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38070. byClipCacheIndex = action._byClipCacheIndex;
  38071. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38072. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38073. knownActionsForClip.pop();
  38074. action._byClipCacheIndex = null;
  38075. const actionByRoot = actionsForClip.actionByRoot,
  38076. rootUuid = ( action._localRoot || this._root ).uuid;
  38077. delete actionByRoot[ rootUuid ];
  38078. if ( knownActionsForClip.length === 0 ) {
  38079. delete actionsByClip[ clipUuid ];
  38080. }
  38081. this._removeInactiveBindingsForAction( action );
  38082. }
  38083. _removeInactiveBindingsForAction( action ) {
  38084. const bindings = action._propertyBindings;
  38085. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38086. const binding = bindings[ i ];
  38087. if ( -- binding.referenceCount === 0 ) {
  38088. this._removeInactiveBinding( binding );
  38089. }
  38090. }
  38091. }
  38092. _lendAction( action ) {
  38093. // [ active actions | inactive actions ]
  38094. // [ active actions >| inactive actions ]
  38095. // s a
  38096. // <-swap->
  38097. // a s
  38098. const actions = this._actions,
  38099. prevIndex = action._cacheIndex,
  38100. lastActiveIndex = this._nActiveActions ++,
  38101. firstInactiveAction = actions[ lastActiveIndex ];
  38102. action._cacheIndex = lastActiveIndex;
  38103. actions[ lastActiveIndex ] = action;
  38104. firstInactiveAction._cacheIndex = prevIndex;
  38105. actions[ prevIndex ] = firstInactiveAction;
  38106. }
  38107. _takeBackAction( action ) {
  38108. // [ active actions | inactive actions ]
  38109. // [ active actions |< inactive actions ]
  38110. // a s
  38111. // <-swap->
  38112. // s a
  38113. const actions = this._actions,
  38114. prevIndex = action._cacheIndex,
  38115. firstInactiveIndex = -- this._nActiveActions,
  38116. lastActiveAction = actions[ firstInactiveIndex ];
  38117. action._cacheIndex = firstInactiveIndex;
  38118. actions[ firstInactiveIndex ] = action;
  38119. lastActiveAction._cacheIndex = prevIndex;
  38120. actions[ prevIndex ] = lastActiveAction;
  38121. }
  38122. // Memory management for PropertyMixer objects
  38123. _addInactiveBinding( binding, rootUuid, trackName ) {
  38124. const bindingsByRoot = this._bindingsByRootAndName,
  38125. bindings = this._bindings;
  38126. let bindingByName = bindingsByRoot[ rootUuid ];
  38127. if ( bindingByName === undefined ) {
  38128. bindingByName = {};
  38129. bindingsByRoot[ rootUuid ] = bindingByName;
  38130. }
  38131. bindingByName[ trackName ] = binding;
  38132. binding._cacheIndex = bindings.length;
  38133. bindings.push( binding );
  38134. }
  38135. _removeInactiveBinding( binding ) {
  38136. const bindings = this._bindings,
  38137. propBinding = binding.binding,
  38138. rootUuid = propBinding.rootNode.uuid,
  38139. trackName = propBinding.path,
  38140. bindingsByRoot = this._bindingsByRootAndName,
  38141. bindingByName = bindingsByRoot[ rootUuid ],
  38142. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38143. cacheIndex = binding._cacheIndex;
  38144. lastInactiveBinding._cacheIndex = cacheIndex;
  38145. bindings[ cacheIndex ] = lastInactiveBinding;
  38146. bindings.pop();
  38147. delete bindingByName[ trackName ];
  38148. if ( Object.keys( bindingByName ).length === 0 ) {
  38149. delete bindingsByRoot[ rootUuid ];
  38150. }
  38151. }
  38152. _lendBinding( binding ) {
  38153. const bindings = this._bindings,
  38154. prevIndex = binding._cacheIndex,
  38155. lastActiveIndex = this._nActiveBindings ++,
  38156. firstInactiveBinding = bindings[ lastActiveIndex ];
  38157. binding._cacheIndex = lastActiveIndex;
  38158. bindings[ lastActiveIndex ] = binding;
  38159. firstInactiveBinding._cacheIndex = prevIndex;
  38160. bindings[ prevIndex ] = firstInactiveBinding;
  38161. }
  38162. _takeBackBinding( binding ) {
  38163. const bindings = this._bindings,
  38164. prevIndex = binding._cacheIndex,
  38165. firstInactiveIndex = -- this._nActiveBindings,
  38166. lastActiveBinding = bindings[ firstInactiveIndex ];
  38167. binding._cacheIndex = firstInactiveIndex;
  38168. bindings[ firstInactiveIndex ] = binding;
  38169. lastActiveBinding._cacheIndex = prevIndex;
  38170. bindings[ prevIndex ] = lastActiveBinding;
  38171. }
  38172. // Memory management of Interpolants for weight and time scale
  38173. _lendControlInterpolant() {
  38174. const interpolants = this._controlInterpolants,
  38175. lastActiveIndex = this._nActiveControlInterpolants ++;
  38176. let interpolant = interpolants[ lastActiveIndex ];
  38177. if ( interpolant === undefined ) {
  38178. interpolant = new LinearInterpolant(
  38179. new Float32Array( 2 ), new Float32Array( 2 ),
  38180. 1, _controlInterpolantsResultBuffer );
  38181. interpolant.__cacheIndex = lastActiveIndex;
  38182. interpolants[ lastActiveIndex ] = interpolant;
  38183. }
  38184. return interpolant;
  38185. }
  38186. _takeBackControlInterpolant( interpolant ) {
  38187. const interpolants = this._controlInterpolants,
  38188. prevIndex = interpolant.__cacheIndex,
  38189. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38190. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38191. interpolant.__cacheIndex = firstInactiveIndex;
  38192. interpolants[ firstInactiveIndex ] = interpolant;
  38193. lastActiveInterpolant.__cacheIndex = prevIndex;
  38194. interpolants[ prevIndex ] = lastActiveInterpolant;
  38195. }
  38196. /**
  38197. * Returns an instance of {@link AnimationAction} for the passed clip.
  38198. *
  38199. * If an action fitting the clip and root parameters doesn't yet exist, it
  38200. * will be created by this method. Calling this method several times with the
  38201. * same clip and root parameters always returns the same action.
  38202. *
  38203. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38204. * @param {Object3D} [optionalRoot] - An alternative root object.
  38205. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38206. * @return {?AnimationAction} The animation action.
  38207. */
  38208. clipAction( clip, optionalRoot, blendMode ) {
  38209. const root = optionalRoot || this._root,
  38210. rootUuid = root.uuid;
  38211. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38212. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38213. const actionsForClip = this._actionsByClip[ clipUuid ];
  38214. let prototypeAction = null;
  38215. if ( blendMode === undefined ) {
  38216. if ( clipObject !== null ) {
  38217. blendMode = clipObject.blendMode;
  38218. } else {
  38219. blendMode = NormalAnimationBlendMode;
  38220. }
  38221. }
  38222. if ( actionsForClip !== undefined ) {
  38223. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38224. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38225. return existingAction;
  38226. }
  38227. // we know the clip, so we don't have to parse all
  38228. // the bindings again but can just copy
  38229. prototypeAction = actionsForClip.knownActions[ 0 ];
  38230. // also, take the clip from the prototype action
  38231. if ( clipObject === null )
  38232. clipObject = prototypeAction._clip;
  38233. }
  38234. // clip must be known when specified via string
  38235. if ( clipObject === null ) return null;
  38236. // allocate all resources required to run it
  38237. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38238. this._bindAction( newAction, prototypeAction );
  38239. // and make the action known to the memory manager
  38240. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38241. return newAction;
  38242. }
  38243. /**
  38244. * Returns an existing animation action for the passed clip.
  38245. *
  38246. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38247. * @param {Object3D} [optionalRoot] - An alternative root object.
  38248. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38249. */
  38250. existingAction( clip, optionalRoot ) {
  38251. const root = optionalRoot || this._root,
  38252. rootUuid = root.uuid,
  38253. clipObject = typeof clip === 'string' ?
  38254. AnimationClip.findByName( root, clip ) : clip,
  38255. clipUuid = clipObject ? clipObject.uuid : clip,
  38256. actionsForClip = this._actionsByClip[ clipUuid ];
  38257. if ( actionsForClip !== undefined ) {
  38258. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38259. }
  38260. return null;
  38261. }
  38262. /**
  38263. * Deactivates all previously scheduled actions on this mixer.
  38264. *
  38265. * @return {AnimationMixer} A reference to thi animation mixer.
  38266. */
  38267. stopAllAction() {
  38268. const actions = this._actions,
  38269. nActions = this._nActiveActions;
  38270. for ( let i = nActions - 1; i >= 0; -- i ) {
  38271. actions[ i ].stop();
  38272. }
  38273. return this;
  38274. }
  38275. /**
  38276. * Advances the global mixer time and updates the animation.
  38277. *
  38278. * This is usually done in the render loop by passing the delta
  38279. * time from {@link Clock} or {@link Timer}.
  38280. *
  38281. * @param {number} deltaTime - The delta time in seconds.
  38282. * @return {AnimationMixer} A reference to thi animation mixer.
  38283. */
  38284. update( deltaTime ) {
  38285. deltaTime *= this.timeScale;
  38286. const actions = this._actions,
  38287. nActions = this._nActiveActions,
  38288. time = this.time += deltaTime,
  38289. timeDirection = Math.sign( deltaTime ),
  38290. accuIndex = this._accuIndex ^= 1;
  38291. // run active actions
  38292. for ( let i = 0; i !== nActions; ++ i ) {
  38293. const action = actions[ i ];
  38294. action._update( time, deltaTime, timeDirection, accuIndex );
  38295. }
  38296. // update scene graph
  38297. const bindings = this._bindings,
  38298. nBindings = this._nActiveBindings;
  38299. for ( let i = 0; i !== nBindings; ++ i ) {
  38300. bindings[ i ].apply( accuIndex );
  38301. }
  38302. return this;
  38303. }
  38304. /**
  38305. * Sets the global mixer to a specific time and updates the animation accordingly.
  38306. *
  38307. * This is useful when you need to jump to an exact time in an animation. The
  38308. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  38309. *
  38310. * @param {number} time - The time to set in seconds.
  38311. * @return {AnimationMixer} A reference to thi animation mixer.
  38312. */
  38313. setTime( time ) {
  38314. this.time = 0; // Zero out time attribute for AnimationMixer object;
  38315. for ( let i = 0; i < this._actions.length; i ++ ) {
  38316. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  38317. }
  38318. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  38319. }
  38320. /**
  38321. * Returns this mixer's root object.
  38322. *
  38323. * @return {Object3D} The mixer's root object.
  38324. */
  38325. getRoot() {
  38326. return this._root;
  38327. }
  38328. /**
  38329. * Deallocates all memory resources for a clip. Before using this method make
  38330. * sure to call {@link AnimationAction#stop} for all related actions.
  38331. *
  38332. * @param {AnimationClip} clip - The clip to uncache.
  38333. */
  38334. uncacheClip( clip ) {
  38335. const actions = this._actions,
  38336. clipUuid = clip.uuid,
  38337. actionsByClip = this._actionsByClip,
  38338. actionsForClip = actionsByClip[ clipUuid ];
  38339. if ( actionsForClip !== undefined ) {
  38340. // note: just calling _removeInactiveAction would mess up the
  38341. // iteration state and also require updating the state we can
  38342. // just throw away
  38343. const actionsToRemove = actionsForClip.knownActions;
  38344. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  38345. const action = actionsToRemove[ i ];
  38346. this._deactivateAction( action );
  38347. const cacheIndex = action._cacheIndex,
  38348. lastInactiveAction = actions[ actions.length - 1 ];
  38349. action._cacheIndex = null;
  38350. action._byClipCacheIndex = null;
  38351. lastInactiveAction._cacheIndex = cacheIndex;
  38352. actions[ cacheIndex ] = lastInactiveAction;
  38353. actions.pop();
  38354. this._removeInactiveBindingsForAction( action );
  38355. }
  38356. delete actionsByClip[ clipUuid ];
  38357. }
  38358. }
  38359. /**
  38360. * Deallocates all memory resources for a root object. Before using this
  38361. * method make sure to call {@link AnimationAction#stop} for all related
  38362. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  38363. * mixer operates on a single root.
  38364. *
  38365. * @param {Object3D} root - The root object to uncache.
  38366. */
  38367. uncacheRoot( root ) {
  38368. const rootUuid = root.uuid,
  38369. actionsByClip = this._actionsByClip;
  38370. for ( const clipUuid in actionsByClip ) {
  38371. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  38372. action = actionByRoot[ rootUuid ];
  38373. if ( action !== undefined ) {
  38374. this._deactivateAction( action );
  38375. this._removeInactiveAction( action );
  38376. }
  38377. }
  38378. const bindingsByRoot = this._bindingsByRootAndName,
  38379. bindingByName = bindingsByRoot[ rootUuid ];
  38380. if ( bindingByName !== undefined ) {
  38381. for ( const trackName in bindingByName ) {
  38382. const binding = bindingByName[ trackName ];
  38383. binding.restoreOriginalState();
  38384. this._removeInactiveBinding( binding );
  38385. }
  38386. }
  38387. }
  38388. /**
  38389. * Deallocates all memory resources for an action. The action is identified by the
  38390. * given clip and an optional root object. Before using this method make
  38391. * sure to call {@link AnimationAction#stop} to deactivate the action.
  38392. *
  38393. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38394. * @param {Object3D} [optionalRoot] - An alternative root object.
  38395. */
  38396. uncacheAction( clip, optionalRoot ) {
  38397. const action = this.existingAction( clip, optionalRoot );
  38398. if ( action !== null ) {
  38399. this._deactivateAction( action );
  38400. this._removeInactiveAction( action );
  38401. }
  38402. }
  38403. }
  38404. /**
  38405. * Represents a 3D render target.
  38406. *
  38407. * @augments RenderTarget
  38408. */
  38409. class RenderTarget3D extends RenderTarget {
  38410. /**
  38411. * Constructs a new 3D render target.
  38412. *
  38413. * @param {number} [width=1] - The width of the render target.
  38414. * @param {number} [height=1] - The height of the render target.
  38415. * @param {number} [depth=1] - The height of the render target.
  38416. * @param {RenderTarget~Options} [options] - The configuration object.
  38417. */
  38418. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38419. super( width, height, options );
  38420. /**
  38421. * This flag can be used for type testing.
  38422. *
  38423. * @type {boolean}
  38424. * @readonly
  38425. * @default true
  38426. */
  38427. this.isRenderTarget3D = true;
  38428. this.depth = depth;
  38429. /**
  38430. * Overwritten with a different texture type.
  38431. *
  38432. * @type {Data3DTexture}
  38433. */
  38434. this.texture = new Data3DTexture( null, width, height, depth );
  38435. this.texture.isRenderTargetTexture = true;
  38436. }
  38437. }
  38438. /**
  38439. * Represents an array render target.
  38440. *
  38441. * @augments RenderTarget
  38442. */
  38443. class RenderTargetArray extends RenderTarget {
  38444. /**
  38445. * Constructs a new 3D render target.
  38446. *
  38447. * @param {number} [width=1] - The width of the render target.
  38448. * @param {number} [height=1] - The height of the render target.
  38449. * @param {number} [depth=1] - The height of the render target.
  38450. * @param {RenderTarget~Options} [options] - The configuration object.
  38451. */
  38452. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  38453. super( width, height, options );
  38454. this.isRenderTargetArray = true;
  38455. this.depth = depth;
  38456. /**
  38457. * Overwritten with a different texture type.
  38458. *
  38459. * @type {DataArrayTexture}
  38460. */
  38461. this.texture = new DataArrayTexture( null, width, height, depth );
  38462. this.texture.isRenderTargetTexture = true;
  38463. }
  38464. }
  38465. /**
  38466. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  38467. *
  38468. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  38469. * ```js
  38470. * uniforms: {
  38471. * time: { value: 1.0 },
  38472. * resolution: new Uniform( new Vector2() )
  38473. * };
  38474. * ```
  38475. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  38476. * in {@link WebGLRenderer}.
  38477. */
  38478. class Uniform {
  38479. /**
  38480. * Constructs a new uniform.
  38481. *
  38482. * @param {any} value - The uniform value.
  38483. */
  38484. constructor( value ) {
  38485. /**
  38486. * The uniform value.
  38487. *
  38488. * @type {any}
  38489. */
  38490. this.value = value;
  38491. }
  38492. /**
  38493. * Returns a new uniform with copied values from this instance.
  38494. * If the value has a `clone()` method, the value is cloned as well.
  38495. *
  38496. * @return {Uniform} A clone of this instance.
  38497. */
  38498. clone() {
  38499. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  38500. }
  38501. }
  38502. let _id$1 = 0;
  38503. /**
  38504. * A class for managing multiple uniforms in a single group. The renderer will process
  38505. * such a definition as a single UBO.
  38506. *
  38507. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  38508. * in {@link WebGLRenderer}.
  38509. *
  38510. * @augments EventDispatcher
  38511. */
  38512. class UniformsGroup extends EventDispatcher {
  38513. /**
  38514. * Constructs a new uniforms group.
  38515. */
  38516. constructor() {
  38517. super();
  38518. /**
  38519. * This flag can be used for type testing.
  38520. *
  38521. * @type {boolean}
  38522. * @readonly
  38523. * @default true
  38524. */
  38525. this.isUniformsGroup = true;
  38526. /**
  38527. * The ID of the 3D object.
  38528. *
  38529. * @name UniformsGroup#id
  38530. * @type {number}
  38531. * @readonly
  38532. */
  38533. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  38534. /**
  38535. * The name of the uniforms group.
  38536. *
  38537. * @type {string}
  38538. */
  38539. this.name = '';
  38540. /**
  38541. * The buffer usage.
  38542. *
  38543. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  38544. * @default StaticDrawUsage
  38545. */
  38546. this.usage = StaticDrawUsage;
  38547. /**
  38548. * An array holding the uniforms.
  38549. *
  38550. * @type {Array<Uniform>}
  38551. */
  38552. this.uniforms = [];
  38553. }
  38554. /**
  38555. * Adds the given uniform to this uniforms group.
  38556. *
  38557. * @param {Uniform} uniform - The uniform to add.
  38558. * @return {UniformsGroup} A reference to this uniforms group.
  38559. */
  38560. add( uniform ) {
  38561. this.uniforms.push( uniform );
  38562. return this;
  38563. }
  38564. /**
  38565. * Removes the given uniform from this uniforms group.
  38566. *
  38567. * @param {Uniform} uniform - The uniform to remove.
  38568. * @return {UniformsGroup} A reference to this uniforms group.
  38569. */
  38570. remove( uniform ) {
  38571. const index = this.uniforms.indexOf( uniform );
  38572. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  38573. return this;
  38574. }
  38575. /**
  38576. * Sets the name of this uniforms group.
  38577. *
  38578. * @param {string} name - The name to set.
  38579. * @return {UniformsGroup} A reference to this uniforms group.
  38580. */
  38581. setName( name ) {
  38582. this.name = name;
  38583. return this;
  38584. }
  38585. /**
  38586. * Sets the usage of this uniforms group.
  38587. *
  38588. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  38589. * @return {UniformsGroup} A reference to this uniforms group.
  38590. */
  38591. setUsage( value ) {
  38592. this.usage = value;
  38593. return this;
  38594. }
  38595. /**
  38596. * Frees the GPU-related resources allocated by this instance. Call this
  38597. * method whenever this instance is no longer used in your app.
  38598. *
  38599. * @fires Texture#dispose
  38600. */
  38601. dispose() {
  38602. this.dispatchEvent( { type: 'dispose' } );
  38603. }
  38604. /**
  38605. * Copies the values of the given uniforms group to this instance.
  38606. *
  38607. * @param {UniformsGroup} source - The uniforms group to copy.
  38608. * @return {UniformsGroup} A reference to this uniforms group.
  38609. */
  38610. copy( source ) {
  38611. this.name = source.name;
  38612. this.usage = source.usage;
  38613. const uniformsSource = source.uniforms;
  38614. this.uniforms.length = 0;
  38615. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  38616. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  38617. for ( let j = 0; j < uniforms.length; j ++ ) {
  38618. this.uniforms.push( uniforms[ j ].clone() );
  38619. }
  38620. }
  38621. return this;
  38622. }
  38623. /**
  38624. * Returns a new uniforms group with copied values from this instance.
  38625. *
  38626. * @return {UniformsGroup} A clone of this instance.
  38627. */
  38628. clone() {
  38629. return new this.constructor().copy( this );
  38630. }
  38631. }
  38632. /**
  38633. * An instanced version of an interleaved buffer.
  38634. *
  38635. * @augments InterleavedBuffer
  38636. */
  38637. class InstancedInterleavedBuffer extends InterleavedBuffer {
  38638. /**
  38639. * Constructs a new instanced interleaved buffer.
  38640. *
  38641. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  38642. * @param {number} stride - The number of typed-array elements per vertex.
  38643. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  38644. */
  38645. constructor( array, stride, meshPerAttribute = 1 ) {
  38646. super( array, stride );
  38647. /**
  38648. * This flag can be used for type testing.
  38649. *
  38650. * @type {boolean}
  38651. * @readonly
  38652. * @default true
  38653. */
  38654. this.isInstancedInterleavedBuffer = true;
  38655. /**
  38656. * Defines how often a value of this buffer attribute should be repeated,
  38657. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  38658. *
  38659. * @type {number}
  38660. * @default 1
  38661. */
  38662. this.meshPerAttribute = meshPerAttribute;
  38663. }
  38664. copy( source ) {
  38665. super.copy( source );
  38666. this.meshPerAttribute = source.meshPerAttribute;
  38667. return this;
  38668. }
  38669. clone( data ) {
  38670. const ib = super.clone( data );
  38671. ib.meshPerAttribute = this.meshPerAttribute;
  38672. return ib;
  38673. }
  38674. toJSON( data ) {
  38675. const json = super.toJSON( data );
  38676. json.isInstancedInterleavedBuffer = true;
  38677. json.meshPerAttribute = this.meshPerAttribute;
  38678. return json;
  38679. }
  38680. }
  38681. /**
  38682. * An alternative version of a buffer attribute with more control over the VBO.
  38683. *
  38684. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  38685. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  38686. *
  38687. * The most common use case for this class is when some kind of GPGPU calculation interferes
  38688. * or even produces the VBOs in question.
  38689. *
  38690. * Notice that this class can only be used with {@link WebGLRenderer}.
  38691. */
  38692. class GLBufferAttribute {
  38693. /**
  38694. * Constructs a new GL buffer attribute.
  38695. *
  38696. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  38697. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  38698. * @param {number} itemSize - The item size.
  38699. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  38700. * @param {number} count - The expected number of vertices in VBO.
  38701. */
  38702. constructor( buffer, type, itemSize, elementSize, count ) {
  38703. /**
  38704. * This flag can be used for type testing.
  38705. *
  38706. * @type {boolean}
  38707. * @readonly
  38708. * @default true
  38709. */
  38710. this.isGLBufferAttribute = true;
  38711. /**
  38712. * The name of the buffer attribute.
  38713. *
  38714. * @type {string}
  38715. */
  38716. this.name = '';
  38717. /**
  38718. * The native WebGL buffer.
  38719. *
  38720. * @type {WebGLBuffer}
  38721. */
  38722. this.buffer = buffer;
  38723. /**
  38724. * The native data type.
  38725. *
  38726. * @type {number}
  38727. */
  38728. this.type = type;
  38729. /**
  38730. * The item size, see {@link BufferAttribute#itemSize}.
  38731. *
  38732. * @type {number}
  38733. */
  38734. this.itemSize = itemSize;
  38735. /**
  38736. * The corresponding size (in bytes) for the given `type` parameter.
  38737. *
  38738. * @type {number}
  38739. */
  38740. this.elementSize = elementSize;
  38741. /**
  38742. * The expected number of vertices in VBO.
  38743. *
  38744. * @type {number}
  38745. */
  38746. this.count = count;
  38747. /**
  38748. * A version number, incremented every time the `needsUpdate` is set to `true`.
  38749. *
  38750. * @type {number}
  38751. */
  38752. this.version = 0;
  38753. }
  38754. /**
  38755. * Flag to indicate that this attribute has changed and should be re-sent to
  38756. * the GPU. Set this to `true` when you modify the value of the array.
  38757. *
  38758. * @type {number}
  38759. * @default false
  38760. * @param {boolean} value
  38761. */
  38762. set needsUpdate( value ) {
  38763. if ( value === true ) this.version ++;
  38764. }
  38765. /**
  38766. * Sets the given native WebGL buffer.
  38767. *
  38768. * @param {WebGLBuffer} buffer - The buffer to set.
  38769. * @return {BufferAttribute} A reference to this instance.
  38770. */
  38771. setBuffer( buffer ) {
  38772. this.buffer = buffer;
  38773. return this;
  38774. }
  38775. /**
  38776. * Sets the given native data type and element size.
  38777. *
  38778. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  38779. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  38780. * @return {BufferAttribute} A reference to this instance.
  38781. */
  38782. setType( type, elementSize ) {
  38783. this.type = type;
  38784. this.elementSize = elementSize;
  38785. return this;
  38786. }
  38787. /**
  38788. * Sets the item size.
  38789. *
  38790. * @param {number} itemSize - The item size.
  38791. * @return {BufferAttribute} A reference to this instance.
  38792. */
  38793. setItemSize( itemSize ) {
  38794. this.itemSize = itemSize;
  38795. return this;
  38796. }
  38797. /**
  38798. * Sets the count (the expected number of vertices in VBO).
  38799. *
  38800. * @param {number} count - The count.
  38801. * @return {BufferAttribute} A reference to this instance.
  38802. */
  38803. setCount( count ) {
  38804. this.count = count;
  38805. return this;
  38806. }
  38807. }
  38808. const _matrix = /*@__PURE__*/ new Matrix4();
  38809. /**
  38810. * This class is designed to assist with raycasting. Raycasting is used for
  38811. * mouse picking (working out what objects in the 3d space the mouse is over)
  38812. * amongst other things.
  38813. */
  38814. class Raycaster {
  38815. /**
  38816. * Constructs a new raycaster.
  38817. *
  38818. * @param {Vector3} origin - The origin vector where the ray casts from.
  38819. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  38820. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  38821. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  38822. */
  38823. constructor( origin, direction, near = 0, far = Infinity ) {
  38824. /**
  38825. * The ray used for raycasting.
  38826. *
  38827. * @type {Ray}
  38828. */
  38829. this.ray = new Ray( origin, direction );
  38830. /**
  38831. * All results returned are further away than near. Near can't be negative.
  38832. *
  38833. * @type {number}
  38834. * @default 0
  38835. */
  38836. this.near = near;
  38837. /**
  38838. * All results returned are further away than near. Near can't be negative.
  38839. *
  38840. * @type {number}
  38841. * @default Infinity
  38842. */
  38843. this.far = far;
  38844. /**
  38845. * The camera to use when raycasting against view-dependent objects such as
  38846. * billboarded objects like sprites. This field can be set manually or
  38847. * is set when calling `setFromCamera()`.
  38848. *
  38849. * @type {?Camera}
  38850. * @default null
  38851. */
  38852. this.camera = null;
  38853. /**
  38854. * Allows to selectively ignore 3D objects when performing intersection tests.
  38855. * The following code example ensures that only 3D objects on layer `1` will be
  38856. * honored by raycaster.
  38857. * ```js
  38858. * raycaster.layers.set( 1 );
  38859. * object.layers.enable( 1 );
  38860. * ```
  38861. *
  38862. * @type {Layers}
  38863. */
  38864. this.layers = new Layers();
  38865. /**
  38866. * A parameter object that configures the raycasting. It has the structure:
  38867. *
  38868. * ```
  38869. * {
  38870. * Mesh: {},
  38871. * Line: { threshold: 1 },
  38872. * LOD: {},
  38873. * Points: { threshold: 1 },
  38874. * Sprite: {}
  38875. * }
  38876. * ```
  38877. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  38878. *
  38879. * @type {Object}
  38880. */
  38881. this.params = {
  38882. Mesh: {},
  38883. Line: { threshold: 1 },
  38884. LOD: {},
  38885. Points: { threshold: 1 },
  38886. Sprite: {}
  38887. };
  38888. }
  38889. /**
  38890. * Updates the ray with a new origin and direction by copying the values from the arguments.
  38891. *
  38892. * @param {Vector3} origin - The origin vector where the ray casts from.
  38893. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  38894. */
  38895. set( origin, direction ) {
  38896. // direction is assumed to be normalized (for accurate distance calculations)
  38897. this.ray.set( origin, direction );
  38898. }
  38899. /**
  38900. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  38901. *
  38902. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  38903. * X and Y components should be between `-1` and `1`.
  38904. * @param {Camera} camera - The camera from which the ray should originate.
  38905. */
  38906. setFromCamera( coords, camera ) {
  38907. if ( camera.isPerspectiveCamera ) {
  38908. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  38909. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  38910. this.camera = camera;
  38911. } else if ( camera.isOrthographicCamera ) {
  38912. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  38913. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  38914. this.camera = camera;
  38915. } else {
  38916. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  38917. }
  38918. }
  38919. /**
  38920. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  38921. *
  38922. * @param {WebXRController} controller - The controller to copy the position and direction from.
  38923. * @return {Raycaster} A reference to this raycaster.
  38924. */
  38925. setFromXRController( controller ) {
  38926. _matrix.identity().extractRotation( controller.matrixWorld );
  38927. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  38928. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  38929. return this;
  38930. }
  38931. /**
  38932. * The intersection point of a raycaster intersection test.
  38933. * @typedef {Object} Raycaster~Intersection
  38934. * @property {number} distance - The distance from the ray's origin to the intersection point.
  38935. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  38936. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  38937. * @property {Vector3} point - The intersection point, in world coordinates.
  38938. * @property {Object} face - The face that has been intersected.
  38939. * @property {number} faceIndex - The face index.
  38940. * @property {Object3D} object - The 3D object that has been intersected.
  38941. * @property {Vector2} uv - U,V coordinates at point of intersection.
  38942. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  38943. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  38944. * @property {number} instanceId - The index number of the instance where the ray
  38945. * intersects the {@link InstancedMesh}.
  38946. */
  38947. /**
  38948. * Checks all intersection between the ray and the object with or without the
  38949. * descendants. Intersections are returned sorted by distance, closest first.
  38950. *
  38951. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  38952. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  38953. * differently to ray casting than lines or points.
  38954. *
  38955. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  38956. * to be detected; intersections of the ray passing through the back of a face will not
  38957. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  38958. * to `THREE.DoubleSide`.
  38959. *
  38960. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  38961. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  38962. * Otherwise it only checks intersection with the object.
  38963. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  38964. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  38965. */
  38966. intersectObject( object, recursive = true, intersects = [] ) {
  38967. intersect( object, this, intersects, recursive );
  38968. intersects.sort( ascSort );
  38969. return intersects;
  38970. }
  38971. /**
  38972. * Checks all intersection between the ray and the objects with or without
  38973. * the descendants. Intersections are returned sorted by distance, closest first.
  38974. *
  38975. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  38976. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  38977. * Otherwise it only checks intersection with the object.
  38978. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  38979. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  38980. */
  38981. intersectObjects( objects, recursive = true, intersects = [] ) {
  38982. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  38983. intersect( objects[ i ], this, intersects, recursive );
  38984. }
  38985. intersects.sort( ascSort );
  38986. return intersects;
  38987. }
  38988. }
  38989. function ascSort( a, b ) {
  38990. return a.distance - b.distance;
  38991. }
  38992. function intersect( object, raycaster, intersects, recursive ) {
  38993. let propagate = true;
  38994. if ( object.layers.test( raycaster.layers ) ) {
  38995. const result = object.raycast( raycaster, intersects );
  38996. if ( result === false ) propagate = false;
  38997. }
  38998. if ( propagate === true && recursive === true ) {
  38999. const children = object.children;
  39000. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39001. intersect( children[ i ], raycaster, intersects, true );
  39002. }
  39003. }
  39004. }
  39005. /**
  39006. * This class can be used to represent points in 3D space as
  39007. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39008. */
  39009. class Spherical {
  39010. /**
  39011. * Constructs a new spherical.
  39012. *
  39013. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39014. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39015. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39016. */
  39017. constructor( radius = 1, phi = 0, theta = 0 ) {
  39018. /**
  39019. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39020. *
  39021. * @type {number}
  39022. * @default 1
  39023. */
  39024. this.radius = radius;
  39025. /**
  39026. * The polar angle in radians from the y (up) axis.
  39027. *
  39028. * @type {number}
  39029. * @default 0
  39030. */
  39031. this.phi = phi;
  39032. /**
  39033. * The equator/azimuthal angle in radians around the y (up) axis.
  39034. *
  39035. * @type {number}
  39036. * @default 0
  39037. */
  39038. this.theta = theta;
  39039. }
  39040. /**
  39041. * Sets the spherical components by copying the given values.
  39042. *
  39043. * @param {number} radius - The radius.
  39044. * @param {number} phi - The polar angle.
  39045. * @param {number} theta - The azimuthal angle.
  39046. * @return {Spherical} A reference to this spherical.
  39047. */
  39048. set( radius, phi, theta ) {
  39049. this.radius = radius;
  39050. this.phi = phi;
  39051. this.theta = theta;
  39052. return this;
  39053. }
  39054. /**
  39055. * Copies the values of the given spherical to this instance.
  39056. *
  39057. * @param {Spherical} other - The spherical to copy.
  39058. * @return {Spherical} A reference to this spherical.
  39059. */
  39060. copy( other ) {
  39061. this.radius = other.radius;
  39062. this.phi = other.phi;
  39063. this.theta = other.theta;
  39064. return this;
  39065. }
  39066. /**
  39067. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39068. * `0.000001`.
  39069. *
  39070. * @return {Spherical} A reference to this spherical.
  39071. */
  39072. makeSafe() {
  39073. const EPS = 0.000001;
  39074. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39075. return this;
  39076. }
  39077. /**
  39078. * Sets the spherical components from the given vector which is assumed to hold
  39079. * Cartesian coordinates.
  39080. *
  39081. * @param {Vector3} v - The vector to set.
  39082. * @return {Spherical} A reference to this spherical.
  39083. */
  39084. setFromVector3( v ) {
  39085. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39086. }
  39087. /**
  39088. * Sets the spherical components from the given Cartesian coordinates.
  39089. *
  39090. * @param {number} x - The x value.
  39091. * @param {number} y - The x value.
  39092. * @param {number} z - The x value.
  39093. * @return {Spherical} A reference to this spherical.
  39094. */
  39095. setFromCartesianCoords( x, y, z ) {
  39096. this.radius = Math.sqrt( x * x + y * y + z * z );
  39097. if ( this.radius === 0 ) {
  39098. this.theta = 0;
  39099. this.phi = 0;
  39100. } else {
  39101. this.theta = Math.atan2( x, z );
  39102. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  39103. }
  39104. return this;
  39105. }
  39106. /**
  39107. * Returns a new spherical with copied values from this instance.
  39108. *
  39109. * @return {Spherical} A clone of this instance.
  39110. */
  39111. clone() {
  39112. return new this.constructor().copy( this );
  39113. }
  39114. }
  39115. /**
  39116. * This class can be used to represent points in 3D space as
  39117. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39118. */
  39119. class Cylindrical {
  39120. /**
  39121. * Constructs a new cylindrical.
  39122. *
  39123. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39124. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39125. * @param {number} [y=0] - The height above the x-z plane.
  39126. */
  39127. constructor( radius = 1, theta = 0, y = 0 ) {
  39128. /**
  39129. * The distance from the origin to a point in the x-z plane.
  39130. *
  39131. * @type {number}
  39132. * @default 1
  39133. */
  39134. this.radius = radius;
  39135. /**
  39136. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39137. *
  39138. * @type {number}
  39139. * @default 0
  39140. */
  39141. this.theta = theta;
  39142. /**
  39143. * The height above the x-z plane.
  39144. *
  39145. * @type {number}
  39146. * @default 0
  39147. */
  39148. this.y = y;
  39149. }
  39150. /**
  39151. * Sets the cylindrical components by copying the given values.
  39152. *
  39153. * @param {number} radius - The radius.
  39154. * @param {number} theta - The theta angle.
  39155. * @param {number} y - The height value.
  39156. * @return {Cylindrical} A reference to this cylindrical.
  39157. */
  39158. set( radius, theta, y ) {
  39159. this.radius = radius;
  39160. this.theta = theta;
  39161. this.y = y;
  39162. return this;
  39163. }
  39164. /**
  39165. * Copies the values of the given cylindrical to this instance.
  39166. *
  39167. * @param {Cylindrical} other - The cylindrical to copy.
  39168. * @return {Cylindrical} A reference to this cylindrical.
  39169. */
  39170. copy( other ) {
  39171. this.radius = other.radius;
  39172. this.theta = other.theta;
  39173. this.y = other.y;
  39174. return this;
  39175. }
  39176. /**
  39177. * Sets the cylindrical components from the given vector which is assumed to hold
  39178. * Cartesian coordinates.
  39179. *
  39180. * @param {Vector3} v - The vector to set.
  39181. * @return {Cylindrical} A reference to this cylindrical.
  39182. */
  39183. setFromVector3( v ) {
  39184. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39185. }
  39186. /**
  39187. * Sets the cylindrical components from the given Cartesian coordinates.
  39188. *
  39189. * @param {number} x - The x value.
  39190. * @param {number} y - The x value.
  39191. * @param {number} z - The x value.
  39192. * @return {Cylindrical} A reference to this cylindrical.
  39193. */
  39194. setFromCartesianCoords( x, y, z ) {
  39195. this.radius = Math.sqrt( x * x + z * z );
  39196. this.theta = Math.atan2( x, z );
  39197. this.y = y;
  39198. return this;
  39199. }
  39200. /**
  39201. * Returns a new cylindrical with copied values from this instance.
  39202. *
  39203. * @return {Cylindrical} A clone of this instance.
  39204. */
  39205. clone() {
  39206. return new this.constructor().copy( this );
  39207. }
  39208. }
  39209. /**
  39210. * Represents a 2x2 matrix.
  39211. *
  39212. * A Note on Row-Major and Column-Major Ordering:
  39213. *
  39214. * The constructor and {@link Matrix2#set} method take arguments in
  39215. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  39216. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  39217. * This means that calling:
  39218. * ```js
  39219. * const m = new THREE.Matrix2();
  39220. * m.set( 11, 12,
  39221. * 21, 22 );
  39222. * ```
  39223. * will result in the elements array containing:
  39224. * ```js
  39225. * m.elements = [ 11, 21,
  39226. * 12, 22 ];
  39227. * ```
  39228. * and internally all calculations are performed using column-major ordering.
  39229. * However, as the actual ordering makes no difference mathematically and
  39230. * most people are used to thinking about matrices in row-major order, the
  39231. * three.js documentation shows matrices in row-major order. Just bear in
  39232. * mind that if you are reading the source code, you'll have to take the
  39233. * transpose of any matrices outlined here to make sense of the calculations.
  39234. */
  39235. class Matrix2 {
  39236. /**
  39237. * Constructs a new 2x2 matrix. The arguments are supposed to be
  39238. * in row-major order. If no arguments are provided, the constructor
  39239. * initializes the matrix as an identity matrix.
  39240. *
  39241. * @param {number} [n11] - 1-1 matrix element.
  39242. * @param {number} [n12] - 1-2 matrix element.
  39243. * @param {number} [n21] - 2-1 matrix element.
  39244. * @param {number} [n22] - 2-2 matrix element.
  39245. */
  39246. constructor( n11, n12, n21, n22 ) {
  39247. /**
  39248. * This flag can be used for type testing.
  39249. *
  39250. * @type {boolean}
  39251. * @readonly
  39252. * @default true
  39253. */
  39254. Matrix2.prototype.isMatrix2 = true;
  39255. /**
  39256. * A column-major list of matrix values.
  39257. *
  39258. * @type {Array<number>}
  39259. */
  39260. this.elements = [
  39261. 1, 0,
  39262. 0, 1,
  39263. ];
  39264. if ( n11 !== undefined ) {
  39265. this.set( n11, n12, n21, n22 );
  39266. }
  39267. }
  39268. /**
  39269. * Sets this matrix to the 2x2 identity matrix.
  39270. *
  39271. * @return {Matrix2} A reference to this matrix.
  39272. */
  39273. identity() {
  39274. this.set(
  39275. 1, 0,
  39276. 0, 1,
  39277. );
  39278. return this;
  39279. }
  39280. /**
  39281. * Sets the elements of the matrix from the given array.
  39282. *
  39283. * @param {Array<number>} array - The matrix elements in column-major order.
  39284. * @param {number} [offset=0] - Index of the first element in the array.
  39285. * @return {Matrix2} A reference to this matrix.
  39286. */
  39287. fromArray( array, offset = 0 ) {
  39288. for ( let i = 0; i < 4; i ++ ) {
  39289. this.elements[ i ] = array[ i + offset ];
  39290. }
  39291. return this;
  39292. }
  39293. /**
  39294. * Sets the elements of the matrix.The arguments are supposed to be
  39295. * in row-major order.
  39296. *
  39297. * @param {number} n11 - 1-1 matrix element.
  39298. * @param {number} n12 - 1-2 matrix element.
  39299. * @param {number} n21 - 2-1 matrix element.
  39300. * @param {number} n22 - 2-2 matrix element.
  39301. * @return {Matrix2} A reference to this matrix.
  39302. */
  39303. set( n11, n12, n21, n22 ) {
  39304. const te = this.elements;
  39305. te[ 0 ] = n11; te[ 2 ] = n12;
  39306. te[ 1 ] = n21; te[ 3 ] = n22;
  39307. return this;
  39308. }
  39309. }
  39310. const _vector$4 = /*@__PURE__*/ new Vector2();
  39311. /**
  39312. * Represents an axis-aligned bounding box (AABB) in 2D space.
  39313. */
  39314. class Box2 {
  39315. /**
  39316. * Constructs a new bounding box.
  39317. *
  39318. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  39319. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  39320. */
  39321. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  39322. /**
  39323. * This flag can be used for type testing.
  39324. *
  39325. * @type {boolean}
  39326. * @readonly
  39327. * @default true
  39328. */
  39329. this.isBox2 = true;
  39330. /**
  39331. * The lower boundary of the box.
  39332. *
  39333. * @type {Vector2}
  39334. */
  39335. this.min = min;
  39336. /**
  39337. * The upper boundary of the box.
  39338. *
  39339. * @type {Vector2}
  39340. */
  39341. this.max = max;
  39342. }
  39343. /**
  39344. * Sets the lower and upper boundaries of this box.
  39345. * Please note that this method only copies the values from the given objects.
  39346. *
  39347. * @param {Vector2} min - The lower boundary of the box.
  39348. * @param {Vector2} max - The upper boundary of the box.
  39349. * @return {Box2} A reference to this bounding box.
  39350. */
  39351. set( min, max ) {
  39352. this.min.copy( min );
  39353. this.max.copy( max );
  39354. return this;
  39355. }
  39356. /**
  39357. * Sets the upper and lower bounds of this box so it encloses the position data
  39358. * in the given array.
  39359. *
  39360. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  39361. * @return {Box2} A reference to this bounding box.
  39362. */
  39363. setFromPoints( points ) {
  39364. this.makeEmpty();
  39365. for ( let i = 0, il = points.length; i < il; i ++ ) {
  39366. this.expandByPoint( points[ i ] );
  39367. }
  39368. return this;
  39369. }
  39370. /**
  39371. * Centers this box on the given center vector and sets this box's width, height and
  39372. * depth to the given size values.
  39373. *
  39374. * @param {Vector2} center - The center of the box.
  39375. * @param {Vector2} size - The x and y dimensions of the box.
  39376. * @return {Box2} A reference to this bounding box.
  39377. */
  39378. setFromCenterAndSize( center, size ) {
  39379. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  39380. this.min.copy( center ).sub( halfSize );
  39381. this.max.copy( center ).add( halfSize );
  39382. return this;
  39383. }
  39384. /**
  39385. * Returns a new box with copied values from this instance.
  39386. *
  39387. * @return {Box2} A clone of this instance.
  39388. */
  39389. clone() {
  39390. return new this.constructor().copy( this );
  39391. }
  39392. /**
  39393. * Copies the values of the given box to this instance.
  39394. *
  39395. * @param {Box2} box - The box to copy.
  39396. * @return {Box2} A reference to this bounding box.
  39397. */
  39398. copy( box ) {
  39399. this.min.copy( box.min );
  39400. this.max.copy( box.max );
  39401. return this;
  39402. }
  39403. /**
  39404. * Makes this box empty which means in encloses a zero space in 2D.
  39405. *
  39406. * @return {Box2} A reference to this bounding box.
  39407. */
  39408. makeEmpty() {
  39409. this.min.x = this.min.y = + Infinity;
  39410. this.max.x = this.max.y = - Infinity;
  39411. return this;
  39412. }
  39413. /**
  39414. * Returns true if this box includes zero points within its bounds.
  39415. * Note that a box with equal lower and upper bounds still includes one
  39416. * point, the one both bounds share.
  39417. *
  39418. * @return {boolean} Whether this box is empty or not.
  39419. */
  39420. isEmpty() {
  39421. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  39422. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  39423. }
  39424. /**
  39425. * Returns the center point of this box.
  39426. *
  39427. * @param {Vector2} target - The target vector that is used to store the method's result.
  39428. * @return {Vector2} The center point.
  39429. */
  39430. getCenter( target ) {
  39431. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  39432. }
  39433. /**
  39434. * Returns the dimensions of this box.
  39435. *
  39436. * @param {Vector2} target - The target vector that is used to store the method's result.
  39437. * @return {Vector2} The size.
  39438. */
  39439. getSize( target ) {
  39440. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  39441. }
  39442. /**
  39443. * Expands the boundaries of this box to include the given point.
  39444. *
  39445. * @param {Vector2} point - The point that should be included by the bounding box.
  39446. * @return {Box2} A reference to this bounding box.
  39447. */
  39448. expandByPoint( point ) {
  39449. this.min.min( point );
  39450. this.max.max( point );
  39451. return this;
  39452. }
  39453. /**
  39454. * Expands this box equilaterally by the given vector. The width of this
  39455. * box will be expanded by the x component of the vector in both
  39456. * directions. The height of this box will be expanded by the y component of
  39457. * the vector in both directions.
  39458. *
  39459. * @param {Vector2} vector - The vector that should expand the bounding box.
  39460. * @return {Box2} A reference to this bounding box.
  39461. */
  39462. expandByVector( vector ) {
  39463. this.min.sub( vector );
  39464. this.max.add( vector );
  39465. return this;
  39466. }
  39467. /**
  39468. * Expands each dimension of the box by the given scalar. If negative, the
  39469. * dimensions of the box will be contracted.
  39470. *
  39471. * @param {number} scalar - The scalar value that should expand the bounding box.
  39472. * @return {Box2} A reference to this bounding box.
  39473. */
  39474. expandByScalar( scalar ) {
  39475. this.min.addScalar( - scalar );
  39476. this.max.addScalar( scalar );
  39477. return this;
  39478. }
  39479. /**
  39480. * Returns `true` if the given point lies within or on the boundaries of this box.
  39481. *
  39482. * @param {Vector2} point - The point to test.
  39483. * @return {boolean} Whether the bounding box contains the given point or not.
  39484. */
  39485. containsPoint( point ) {
  39486. return point.x >= this.min.x && point.x <= this.max.x &&
  39487. point.y >= this.min.y && point.y <= this.max.y;
  39488. }
  39489. /**
  39490. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  39491. * If this box and the given one are identical, this function also returns `true`.
  39492. *
  39493. * @param {Box2} box - The bounding box to test.
  39494. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  39495. */
  39496. containsBox( box ) {
  39497. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  39498. this.min.y <= box.min.y && box.max.y <= this.max.y;
  39499. }
  39500. /**
  39501. * Returns a point as a proportion of this box's width and height.
  39502. *
  39503. * @param {Vector2} point - A point in 2D space.
  39504. * @param {Vector2} target - The target vector that is used to store the method's result.
  39505. * @return {Vector2} A point as a proportion of this box's width and height.
  39506. */
  39507. getParameter( point, target ) {
  39508. // This can potentially have a divide by zero if the box
  39509. // has a size dimension of 0.
  39510. return target.set(
  39511. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  39512. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  39513. );
  39514. }
  39515. /**
  39516. * Returns `true` if the given bounding box intersects with this bounding box.
  39517. *
  39518. * @param {Box2} box - The bounding box to test.
  39519. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  39520. */
  39521. intersectsBox( box ) {
  39522. // using 4 splitting planes to rule out intersections
  39523. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  39524. box.max.y >= this.min.y && box.min.y <= this.max.y;
  39525. }
  39526. /**
  39527. * Clamps the given point within the bounds of this box.
  39528. *
  39529. * @param {Vector2} point - The point to clamp.
  39530. * @param {Vector2} target - The target vector that is used to store the method's result.
  39531. * @return {Vector2} The clamped point.
  39532. */
  39533. clampPoint( point, target ) {
  39534. return target.copy( point ).clamp( this.min, this.max );
  39535. }
  39536. /**
  39537. * Returns the euclidean distance from any edge of this box to the specified point. If
  39538. * the given point lies inside of this box, the distance will be `0`.
  39539. *
  39540. * @param {Vector2} point - The point to compute the distance to.
  39541. * @return {number} The euclidean distance.
  39542. */
  39543. distanceToPoint( point ) {
  39544. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  39545. }
  39546. /**
  39547. * Computes the intersection of this bounding box and the given one, setting the upper
  39548. * bound of this box to the lesser of the two boxes' upper bounds and the
  39549. * lower bound of this box to the greater of the two boxes' lower bounds. If
  39550. * there's no overlap, makes this box empty.
  39551. *
  39552. * @param {Box2} box - The bounding box to intersect with.
  39553. * @return {Box2} A reference to this bounding box.
  39554. */
  39555. intersect( box ) {
  39556. this.min.max( box.min );
  39557. this.max.min( box.max );
  39558. if ( this.isEmpty() ) this.makeEmpty();
  39559. return this;
  39560. }
  39561. /**
  39562. * Computes the union of this box and another and the given one, setting the upper
  39563. * bound of this box to the greater of the two boxes' upper bounds and the
  39564. * lower bound of this box to the lesser of the two boxes' lower bounds.
  39565. *
  39566. * @param {Box2} box - The bounding box that will be unioned with this instance.
  39567. * @return {Box2} A reference to this bounding box.
  39568. */
  39569. union( box ) {
  39570. this.min.min( box.min );
  39571. this.max.max( box.max );
  39572. return this;
  39573. }
  39574. /**
  39575. * Adds the given offset to both the upper and lower bounds of this bounding box,
  39576. * effectively moving it in 2D space.
  39577. *
  39578. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  39579. * @return {Box2} A reference to this bounding box.
  39580. */
  39581. translate( offset ) {
  39582. this.min.add( offset );
  39583. this.max.add( offset );
  39584. return this;
  39585. }
  39586. /**
  39587. * Returns `true` if this bounding box is equal with the given one.
  39588. *
  39589. * @param {Box2} box - The box to test for equality.
  39590. * @return {boolean} Whether this bounding box is equal with the given one.
  39591. */
  39592. equals( box ) {
  39593. return box.min.equals( this.min ) && box.max.equals( this.max );
  39594. }
  39595. }
  39596. const _startP = /*@__PURE__*/ new Vector3();
  39597. const _startEnd = /*@__PURE__*/ new Vector3();
  39598. /**
  39599. * An analytical line segment in 3D space represented by a start and end point.
  39600. */
  39601. class Line3 {
  39602. /**
  39603. * Constructs a new line segment.
  39604. *
  39605. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  39606. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  39607. */
  39608. constructor( start = new Vector3(), end = new Vector3() ) {
  39609. /**
  39610. * Start of the line segment.
  39611. *
  39612. * @type {Vector3}
  39613. */
  39614. this.start = start;
  39615. /**
  39616. * End of the line segment.
  39617. *
  39618. * @type {Vector3}
  39619. */
  39620. this.end = end;
  39621. }
  39622. /**
  39623. * Sets the start and end values by copying the given vectors.
  39624. *
  39625. * @param {Vector3} start - The start point.
  39626. * @param {Vector3} end - The end point.
  39627. * @return {Line3} A reference to this line segment.
  39628. */
  39629. set( start, end ) {
  39630. this.start.copy( start );
  39631. this.end.copy( end );
  39632. return this;
  39633. }
  39634. /**
  39635. * Copies the values of the given line segment to this instance.
  39636. *
  39637. * @param {Line3} line - The line segment to copy.
  39638. * @return {Line3} A reference to this line segment.
  39639. */
  39640. copy( line ) {
  39641. this.start.copy( line.start );
  39642. this.end.copy( line.end );
  39643. return this;
  39644. }
  39645. /**
  39646. * Returns the center of the line segment.
  39647. *
  39648. * @param {Vector3} target - The target vector that is used to store the method's result.
  39649. * @return {Vector3} The center point.
  39650. */
  39651. getCenter( target ) {
  39652. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  39653. }
  39654. /**
  39655. * Returns the delta vector of the line segment's start and end point.
  39656. *
  39657. * @param {Vector3} target - The target vector that is used to store the method's result.
  39658. * @return {Vector3} The delta vector.
  39659. */
  39660. delta( target ) {
  39661. return target.subVectors( this.end, this.start );
  39662. }
  39663. /**
  39664. * Returns the squared Euclidean distance between the line' start and end point.
  39665. *
  39666. * @return {number} The squared Euclidean distance.
  39667. */
  39668. distanceSq() {
  39669. return this.start.distanceToSquared( this.end );
  39670. }
  39671. /**
  39672. * Returns the Euclidean distance between the line' start and end point.
  39673. *
  39674. * @return {number} The Euclidean distance.
  39675. */
  39676. distance() {
  39677. return this.start.distanceTo( this.end );
  39678. }
  39679. /**
  39680. * Returns a vector at a certain position along the line segment.
  39681. *
  39682. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  39683. * @param {Vector3} target - The target vector that is used to store the method's result.
  39684. * @return {Vector3} The delta vector.
  39685. */
  39686. at( t, target ) {
  39687. return this.delta( target ).multiplyScalar( t ).add( this.start );
  39688. }
  39689. /**
  39690. * Returns a point parameter based on the closest point as projected on the line segment.
  39691. *
  39692. * @param {Vector3} point - The point for which to return a point parameter.
  39693. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  39694. * @return {number} The point parameter.
  39695. */
  39696. closestPointToPointParameter( point, clampToLine ) {
  39697. _startP.subVectors( point, this.start );
  39698. _startEnd.subVectors( this.end, this.start );
  39699. const startEnd2 = _startEnd.dot( _startEnd );
  39700. const startEnd_startP = _startEnd.dot( _startP );
  39701. let t = startEnd_startP / startEnd2;
  39702. if ( clampToLine ) {
  39703. t = clamp( t, 0, 1 );
  39704. }
  39705. return t;
  39706. }
  39707. /**
  39708. * Returns the closets point on the line for a given point.
  39709. *
  39710. * @param {Vector3} point - The point to compute the closest point on the line for.
  39711. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  39712. * @param {Vector3} target - The target vector that is used to store the method's result.
  39713. * @return {Vector3} The closest point on the line.
  39714. */
  39715. closestPointToPoint( point, clampToLine, target ) {
  39716. const t = this.closestPointToPointParameter( point, clampToLine );
  39717. return this.delta( target ).multiplyScalar( t ).add( this.start );
  39718. }
  39719. /**
  39720. * Applies a 4x4 transformation matrix to this line segment.
  39721. *
  39722. * @param {Matrix4} matrix - The transformation matrix.
  39723. * @return {Line3} A reference to this line segment.
  39724. */
  39725. applyMatrix4( matrix ) {
  39726. this.start.applyMatrix4( matrix );
  39727. this.end.applyMatrix4( matrix );
  39728. return this;
  39729. }
  39730. /**
  39731. * Returns `true` if this line segment is equal with the given one.
  39732. *
  39733. * @param {Line3} line - The line segment to test for equality.
  39734. * @return {boolean} Whether this line segment is equal with the given one.
  39735. */
  39736. equals( line ) {
  39737. return line.start.equals( this.start ) && line.end.equals( this.end );
  39738. }
  39739. /**
  39740. * Returns a new line segment with copied values from this instance.
  39741. *
  39742. * @return {Line3} A clone of this instance.
  39743. */
  39744. clone() {
  39745. return new this.constructor().copy( this );
  39746. }
  39747. }
  39748. const _vector$3 = /*@__PURE__*/ new Vector3();
  39749. /**
  39750. * This displays a cone shaped helper object for a {@link SpotLight}.
  39751. *
  39752. * ```js
  39753. * const spotLight = new THREE.SpotLight( 0xffffff );
  39754. * spotLight.position.set( 10, 10, 10 );
  39755. * scene.add( spotLight );
  39756. *
  39757. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  39758. * scene.add( spotLightHelper );
  39759. * ```
  39760. *
  39761. * @augments Object3D
  39762. */
  39763. class SpotLightHelper extends Object3D {
  39764. /**
  39765. * Constructs a new spot light helper.
  39766. *
  39767. * @param {HemisphereLight} light - The light to be visualized.
  39768. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  39769. * the color of the light.
  39770. */
  39771. constructor( light, color ) {
  39772. super();
  39773. /**
  39774. * The light being visualized.
  39775. *
  39776. * @type {SpotLight}
  39777. */
  39778. this.light = light;
  39779. this.matrixAutoUpdate = false;
  39780. /**
  39781. * The color parameter passed in the constructor.
  39782. * If not set, the helper will take the color of the light.
  39783. *
  39784. * @type {number|Color|string}
  39785. */
  39786. this.color = color;
  39787. this.type = 'SpotLightHelper';
  39788. const geometry = new BufferGeometry();
  39789. const positions = [
  39790. 0, 0, 0, 0, 0, 1,
  39791. 0, 0, 0, 1, 0, 1,
  39792. 0, 0, 0, - 1, 0, 1,
  39793. 0, 0, 0, 0, 1, 1,
  39794. 0, 0, 0, 0, - 1, 1
  39795. ];
  39796. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  39797. const p1 = ( i / l ) * Math.PI * 2;
  39798. const p2 = ( j / l ) * Math.PI * 2;
  39799. positions.push(
  39800. Math.cos( p1 ), Math.sin( p1 ), 1,
  39801. Math.cos( p2 ), Math.sin( p2 ), 1
  39802. );
  39803. }
  39804. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  39805. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  39806. this.cone = new LineSegments( geometry, material );
  39807. this.add( this.cone );
  39808. this.update();
  39809. }
  39810. /**
  39811. * Frees the GPU-related resources allocated by this instance. Call this
  39812. * method whenever this instance is no longer used in your app.
  39813. */
  39814. dispose() {
  39815. this.cone.geometry.dispose();
  39816. this.cone.material.dispose();
  39817. }
  39818. /**
  39819. * Updates the helper to match the position and direction of the
  39820. * light being visualized.
  39821. */
  39822. update() {
  39823. this.light.updateWorldMatrix( true, false );
  39824. this.light.target.updateWorldMatrix( true, false );
  39825. // update the local matrix based on the parent and light target transforms
  39826. if ( this.parent ) {
  39827. this.parent.updateWorldMatrix( true );
  39828. this.matrix
  39829. .copy( this.parent.matrixWorld )
  39830. .invert()
  39831. .multiply( this.light.matrixWorld );
  39832. } else {
  39833. this.matrix.copy( this.light.matrixWorld );
  39834. }
  39835. this.matrixWorld.copy( this.light.matrixWorld );
  39836. const coneLength = this.light.distance ? this.light.distance : 1000;
  39837. const coneWidth = coneLength * Math.tan( this.light.angle );
  39838. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  39839. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  39840. this.cone.lookAt( _vector$3 );
  39841. if ( this.color !== undefined ) {
  39842. this.cone.material.color.set( this.color );
  39843. } else {
  39844. this.cone.material.color.copy( this.light.color );
  39845. }
  39846. }
  39847. }
  39848. const _vector$2 = /*@__PURE__*/ new Vector3();
  39849. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  39850. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  39851. /**
  39852. * A helper object to assist with visualizing a {@link Skeleton}.
  39853. *
  39854. * ```js
  39855. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  39856. * scene.add( helper );
  39857. * ```
  39858. *
  39859. * @augments LineSegments
  39860. */
  39861. class SkeletonHelper extends LineSegments {
  39862. /**
  39863. * Constructs a new hemisphere light helper.
  39864. *
  39865. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  39866. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  39867. */
  39868. constructor( object ) {
  39869. const bones = getBoneList( object );
  39870. const geometry = new BufferGeometry();
  39871. const vertices = [];
  39872. const colors = [];
  39873. const color1 = new Color( 0, 0, 1 );
  39874. const color2 = new Color( 0, 1, 0 );
  39875. for ( let i = 0; i < bones.length; i ++ ) {
  39876. const bone = bones[ i ];
  39877. if ( bone.parent && bone.parent.isBone ) {
  39878. vertices.push( 0, 0, 0 );
  39879. vertices.push( 0, 0, 0 );
  39880. colors.push( color1.r, color1.g, color1.b );
  39881. colors.push( color2.r, color2.g, color2.b );
  39882. }
  39883. }
  39884. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  39885. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  39886. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  39887. super( geometry, material );
  39888. /**
  39889. * This flag can be used for type testing.
  39890. *
  39891. * @type {boolean}
  39892. * @readonly
  39893. * @default true
  39894. */
  39895. this.isSkeletonHelper = true;
  39896. this.type = 'SkeletonHelper';
  39897. /**
  39898. * The object being visualized.
  39899. *
  39900. * @type {Object3D}
  39901. */
  39902. this.root = object;
  39903. /**
  39904. * he list of bones that the helper visualizes.
  39905. *
  39906. * @type {Array<Bone>}
  39907. */
  39908. this.bones = bones;
  39909. this.matrix = object.matrixWorld;
  39910. this.matrixAutoUpdate = false;
  39911. }
  39912. updateMatrixWorld( force ) {
  39913. const bones = this.bones;
  39914. const geometry = this.geometry;
  39915. const position = geometry.getAttribute( 'position' );
  39916. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  39917. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  39918. const bone = bones[ i ];
  39919. if ( bone.parent && bone.parent.isBone ) {
  39920. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  39921. _vector$2.setFromMatrixPosition( _boneMatrix );
  39922. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  39923. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  39924. _vector$2.setFromMatrixPosition( _boneMatrix );
  39925. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  39926. j += 2;
  39927. }
  39928. }
  39929. geometry.getAttribute( 'position' ).needsUpdate = true;
  39930. super.updateMatrixWorld( force );
  39931. }
  39932. /**
  39933. * Frees the GPU-related resources allocated by this instance. Call this
  39934. * method whenever this instance is no longer used in your app.
  39935. */
  39936. dispose() {
  39937. this.geometry.dispose();
  39938. this.material.dispose();
  39939. }
  39940. }
  39941. function getBoneList( object ) {
  39942. const boneList = [];
  39943. if ( object.isBone === true ) {
  39944. boneList.push( object );
  39945. }
  39946. for ( let i = 0; i < object.children.length; i ++ ) {
  39947. boneList.push( ...getBoneList( object.children[ i ] ) );
  39948. }
  39949. return boneList;
  39950. }
  39951. /**
  39952. * This displays a helper object consisting of a spherical mesh for
  39953. * visualizing an instance of {@link PointLight}.
  39954. *
  39955. * ```js
  39956. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  39957. * pointLight.position.set( 10, 10, 10 );
  39958. * scene.add( pointLight );
  39959. *
  39960. * const sphereSize = 1;
  39961. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  39962. * scene.add( pointLightHelper );
  39963. * ```
  39964. *
  39965. * @augments Mesh
  39966. */
  39967. class PointLightHelper extends Mesh {
  39968. /**
  39969. * Constructs a new point light helper.
  39970. *
  39971. * @param {PointLight} light - The light to be visualized.
  39972. * @param {number} [sphereSize=1] - The size of the sphere helper.
  39973. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  39974. * the color of the light.
  39975. */
  39976. constructor( light, sphereSize, color ) {
  39977. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  39978. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  39979. super( geometry, material );
  39980. /**
  39981. * The light being visualized.
  39982. *
  39983. * @type {HemisphereLight}
  39984. */
  39985. this.light = light;
  39986. /**
  39987. * The color parameter passed in the constructor.
  39988. * If not set, the helper will take the color of the light.
  39989. *
  39990. * @type {number|Color|string}
  39991. */
  39992. this.color = color;
  39993. this.type = 'PointLightHelper';
  39994. this.matrix = this.light.matrixWorld;
  39995. this.matrixAutoUpdate = false;
  39996. this.update();
  39997. /*
  39998. // TODO: delete this comment?
  39999. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40000. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40001. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40002. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40003. const d = light.distance;
  40004. if ( d === 0.0 ) {
  40005. this.lightDistance.visible = false;
  40006. } else {
  40007. this.lightDistance.scale.set( d, d, d );
  40008. }
  40009. this.add( this.lightDistance );
  40010. */
  40011. }
  40012. /**
  40013. * Frees the GPU-related resources allocated by this instance. Call this
  40014. * method whenever this instance is no longer used in your app.
  40015. */
  40016. dispose() {
  40017. this.geometry.dispose();
  40018. this.material.dispose();
  40019. }
  40020. /**
  40021. * Updates the helper to match the position of the
  40022. * light being visualized.
  40023. */
  40024. update() {
  40025. this.light.updateWorldMatrix( true, false );
  40026. if ( this.color !== undefined ) {
  40027. this.material.color.set( this.color );
  40028. } else {
  40029. this.material.color.copy( this.light.color );
  40030. }
  40031. /*
  40032. const d = this.light.distance;
  40033. if ( d === 0.0 ) {
  40034. this.lightDistance.visible = false;
  40035. } else {
  40036. this.lightDistance.visible = true;
  40037. this.lightDistance.scale.set( d, d, d );
  40038. }
  40039. */
  40040. }
  40041. }
  40042. const _vector$1 = /*@__PURE__*/ new Vector3();
  40043. const _color1 = /*@__PURE__*/ new Color();
  40044. const _color2 = /*@__PURE__*/ new Color();
  40045. /**
  40046. * Creates a visual aid consisting of a spherical mesh for a
  40047. * given {@link HemisphereLight}.
  40048. *
  40049. * ```js
  40050. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40051. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40052. * scene.add( helper );
  40053. * ```
  40054. *
  40055. * @augments Object3D
  40056. */
  40057. class HemisphereLightHelper extends Object3D {
  40058. /**
  40059. * Constructs a new hemisphere light helper.
  40060. *
  40061. * @param {HemisphereLight} light - The light to be visualized.
  40062. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40063. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40064. * the color of the light.
  40065. */
  40066. constructor( light, size, color ) {
  40067. super();
  40068. /**
  40069. * The light being visualized.
  40070. *
  40071. * @type {HemisphereLight}
  40072. */
  40073. this.light = light;
  40074. this.matrix = light.matrixWorld;
  40075. this.matrixAutoUpdate = false;
  40076. /**
  40077. * The color parameter passed in the constructor.
  40078. * If not set, the helper will take the color of the light.
  40079. *
  40080. * @type {number|Color|string}
  40081. */
  40082. this.color = color;
  40083. this.type = 'HemisphereLightHelper';
  40084. const geometry = new OctahedronGeometry( size );
  40085. geometry.rotateY( Math.PI * 0.5 );
  40086. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40087. if ( this.color === undefined ) this.material.vertexColors = true;
  40088. const position = geometry.getAttribute( 'position' );
  40089. const colors = new Float32Array( position.count * 3 );
  40090. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  40091. this.add( new Mesh( geometry, this.material ) );
  40092. this.update();
  40093. }
  40094. /**
  40095. * Frees the GPU-related resources allocated by this instance. Call this
  40096. * method whenever this instance is no longer used in your app.
  40097. */
  40098. dispose() {
  40099. this.children[ 0 ].geometry.dispose();
  40100. this.children[ 0 ].material.dispose();
  40101. }
  40102. /**
  40103. * Updates the helper to match the position and direction of the
  40104. * light being visualized.
  40105. */
  40106. update() {
  40107. const mesh = this.children[ 0 ];
  40108. if ( this.color !== undefined ) {
  40109. this.material.color.set( this.color );
  40110. } else {
  40111. const colors = mesh.geometry.getAttribute( 'color' );
  40112. _color1.copy( this.light.color );
  40113. _color2.copy( this.light.groundColor );
  40114. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  40115. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  40116. colors.setXYZ( i, color.r, color.g, color.b );
  40117. }
  40118. colors.needsUpdate = true;
  40119. }
  40120. this.light.updateWorldMatrix( true, false );
  40121. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  40122. }
  40123. }
  40124. /**
  40125. * The helper is an object to define grids. Grids are two-dimensional
  40126. * arrays of lines.
  40127. *
  40128. * ```js
  40129. * const size = 10;
  40130. * const divisions = 10;
  40131. *
  40132. * const gridHelper = new THREE.GridHelper( size, divisions );
  40133. * scene.add( gridHelper );
  40134. * ```
  40135. *
  40136. * @augments LineSegments
  40137. */
  40138. class GridHelper extends LineSegments {
  40139. /**
  40140. * Constructs a new grid helper.
  40141. *
  40142. * @param {number} [size=10] - The size of the grid.
  40143. * @param {number} [divisions=10] - The number of divisions across the grid.
  40144. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  40145. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  40146. */
  40147. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  40148. color1 = new Color( color1 );
  40149. color2 = new Color( color2 );
  40150. const center = divisions / 2;
  40151. const step = size / divisions;
  40152. const halfSize = size / 2;
  40153. const vertices = [], colors = [];
  40154. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  40155. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  40156. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  40157. const color = i === center ? color1 : color2;
  40158. color.toArray( colors, j ); j += 3;
  40159. color.toArray( colors, j ); j += 3;
  40160. color.toArray( colors, j ); j += 3;
  40161. color.toArray( colors, j ); j += 3;
  40162. }
  40163. const geometry = new BufferGeometry();
  40164. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40165. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40166. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40167. super( geometry, material );
  40168. this.type = 'GridHelper';
  40169. }
  40170. /**
  40171. * Frees the GPU-related resources allocated by this instance. Call this
  40172. * method whenever this instance is no longer used in your app.
  40173. */
  40174. dispose() {
  40175. this.geometry.dispose();
  40176. this.material.dispose();
  40177. }
  40178. }
  40179. /**
  40180. * This helper is an object to define polar grids. Grids are
  40181. * two-dimensional arrays of lines.
  40182. *
  40183. * ```js
  40184. * const radius = 10;
  40185. * const sectors = 16;
  40186. * const rings = 8;
  40187. * const divisions = 64;
  40188. *
  40189. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  40190. * scene.add( helper );
  40191. * ```
  40192. *
  40193. * @augments LineSegments
  40194. */
  40195. class PolarGridHelper extends LineSegments {
  40196. /**
  40197. * Constructs a new polar grid helper.
  40198. *
  40199. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  40200. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  40201. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  40202. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  40203. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  40204. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  40205. */
  40206. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  40207. color1 = new Color( color1 );
  40208. color2 = new Color( color2 );
  40209. const vertices = [];
  40210. const colors = [];
  40211. // create the sectors
  40212. if ( sectors > 1 ) {
  40213. for ( let i = 0; i < sectors; i ++ ) {
  40214. const v = ( i / sectors ) * ( Math.PI * 2 );
  40215. const x = Math.sin( v ) * radius;
  40216. const z = Math.cos( v ) * radius;
  40217. vertices.push( 0, 0, 0 );
  40218. vertices.push( x, 0, z );
  40219. const color = ( i & 1 ) ? color1 : color2;
  40220. colors.push( color.r, color.g, color.b );
  40221. colors.push( color.r, color.g, color.b );
  40222. }
  40223. }
  40224. // create the rings
  40225. for ( let i = 0; i < rings; i ++ ) {
  40226. const color = ( i & 1 ) ? color1 : color2;
  40227. const r = radius - ( radius / rings * i );
  40228. for ( let j = 0; j < divisions; j ++ ) {
  40229. // first vertex
  40230. let v = ( j / divisions ) * ( Math.PI * 2 );
  40231. let x = Math.sin( v ) * r;
  40232. let z = Math.cos( v ) * r;
  40233. vertices.push( x, 0, z );
  40234. colors.push( color.r, color.g, color.b );
  40235. // second vertex
  40236. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  40237. x = Math.sin( v ) * r;
  40238. z = Math.cos( v ) * r;
  40239. vertices.push( x, 0, z );
  40240. colors.push( color.r, color.g, color.b );
  40241. }
  40242. }
  40243. const geometry = new BufferGeometry();
  40244. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40245. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40246. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40247. super( geometry, material );
  40248. this.type = 'PolarGridHelper';
  40249. }
  40250. /**
  40251. * Frees the GPU-related resources allocated by this instance. Call this
  40252. * method whenever this instance is no longer used in your app.
  40253. */
  40254. dispose() {
  40255. this.geometry.dispose();
  40256. this.material.dispose();
  40257. }
  40258. }
  40259. const _v1 = /*@__PURE__*/ new Vector3();
  40260. const _v2 = /*@__PURE__*/ new Vector3();
  40261. const _v3 = /*@__PURE__*/ new Vector3();
  40262. /**
  40263. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  40264. * effect on the scene. This consists of plane and a line representing the
  40265. * light's position and direction.
  40266. *
  40267. * ```js
  40268. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  40269. * scene.add( light );
  40270. *
  40271. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  40272. * scene.add( helper );
  40273. * ```
  40274. *
  40275. * @augments Object3D
  40276. */
  40277. class DirectionalLightHelper extends Object3D {
  40278. /**
  40279. * Constructs a new directional light helper.
  40280. *
  40281. * @param {DirectionalLight} light - The light to be visualized.
  40282. * @param {number} [size=1] - The dimensions of the plane.
  40283. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40284. * the color of the light.
  40285. */
  40286. constructor( light, size, color ) {
  40287. super();
  40288. /**
  40289. * The light being visualized.
  40290. *
  40291. * @type {DirectionalLight}
  40292. */
  40293. this.light = light;
  40294. this.matrix = light.matrixWorld;
  40295. this.matrixAutoUpdate = false;
  40296. /**
  40297. * The color parameter passed in the constructor.
  40298. * If not set, the helper will take the color of the light.
  40299. *
  40300. * @type {number|Color|string}
  40301. */
  40302. this.color = color;
  40303. this.type = 'DirectionalLightHelper';
  40304. if ( size === undefined ) size = 1;
  40305. let geometry = new BufferGeometry();
  40306. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  40307. - size, size, 0,
  40308. size, size, 0,
  40309. size, - size, 0,
  40310. - size, - size, 0,
  40311. - size, size, 0
  40312. ], 3 ) );
  40313. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40314. /**
  40315. * Contains the line showing the location of the directional light.
  40316. *
  40317. * @type {Line}
  40318. */
  40319. this.lightPlane = new Line( geometry, material );
  40320. this.add( this.lightPlane );
  40321. geometry = new BufferGeometry();
  40322. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  40323. /**
  40324. * Represents the target line of the directional light.
  40325. *
  40326. * @type {Line}
  40327. */
  40328. this.targetLine = new Line( geometry, material );
  40329. this.add( this.targetLine );
  40330. this.update();
  40331. }
  40332. /**
  40333. * Frees the GPU-related resources allocated by this instance. Call this
  40334. * method whenever this instance is no longer used in your app.
  40335. */
  40336. dispose() {
  40337. this.lightPlane.geometry.dispose();
  40338. this.lightPlane.material.dispose();
  40339. this.targetLine.geometry.dispose();
  40340. this.targetLine.material.dispose();
  40341. }
  40342. /**
  40343. * Updates the helper to match the position and direction of the
  40344. * light being visualized.
  40345. */
  40346. update() {
  40347. this.light.updateWorldMatrix( true, false );
  40348. this.light.target.updateWorldMatrix( true, false );
  40349. _v1.setFromMatrixPosition( this.light.matrixWorld );
  40350. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  40351. _v3.subVectors( _v2, _v1 );
  40352. this.lightPlane.lookAt( _v2 );
  40353. if ( this.color !== undefined ) {
  40354. this.lightPlane.material.color.set( this.color );
  40355. this.targetLine.material.color.set( this.color );
  40356. } else {
  40357. this.lightPlane.material.color.copy( this.light.color );
  40358. this.targetLine.material.color.copy( this.light.color );
  40359. }
  40360. this.targetLine.lookAt( _v2 );
  40361. this.targetLine.scale.z = _v3.length();
  40362. }
  40363. }
  40364. const _vector = /*@__PURE__*/ new Vector3();
  40365. const _camera = /*@__PURE__*/ new Camera();
  40366. /**
  40367. * This helps with visualizing what a camera contains in its frustum. It
  40368. * visualizes the frustum of a camera using a line segments.
  40369. *
  40370. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  40371. *
  40372. * `CameraHelper` must be a child of the scene.
  40373. *
  40374. * ```js
  40375. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  40376. * const helper = new THREE.CameraHelper( camera );
  40377. * scene.add( helper );
  40378. * ```
  40379. *
  40380. * @augments LineSegments
  40381. */
  40382. class CameraHelper extends LineSegments {
  40383. /**
  40384. * Constructs a new arrow helper.
  40385. *
  40386. * @param {Camera} camera - The camera to visualize.
  40387. */
  40388. constructor( camera ) {
  40389. const geometry = new BufferGeometry();
  40390. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  40391. const vertices = [];
  40392. const colors = [];
  40393. const pointMap = {};
  40394. // near
  40395. addLine( 'n1', 'n2' );
  40396. addLine( 'n2', 'n4' );
  40397. addLine( 'n4', 'n3' );
  40398. addLine( 'n3', 'n1' );
  40399. // far
  40400. addLine( 'f1', 'f2' );
  40401. addLine( 'f2', 'f4' );
  40402. addLine( 'f4', 'f3' );
  40403. addLine( 'f3', 'f1' );
  40404. // sides
  40405. addLine( 'n1', 'f1' );
  40406. addLine( 'n2', 'f2' );
  40407. addLine( 'n3', 'f3' );
  40408. addLine( 'n4', 'f4' );
  40409. // cone
  40410. addLine( 'p', 'n1' );
  40411. addLine( 'p', 'n2' );
  40412. addLine( 'p', 'n3' );
  40413. addLine( 'p', 'n4' );
  40414. // up
  40415. addLine( 'u1', 'u2' );
  40416. addLine( 'u2', 'u3' );
  40417. addLine( 'u3', 'u1' );
  40418. // target
  40419. addLine( 'c', 't' );
  40420. addLine( 'p', 'c' );
  40421. // cross
  40422. addLine( 'cn1', 'cn2' );
  40423. addLine( 'cn3', 'cn4' );
  40424. addLine( 'cf1', 'cf2' );
  40425. addLine( 'cf3', 'cf4' );
  40426. function addLine( a, b ) {
  40427. addPoint( a );
  40428. addPoint( b );
  40429. }
  40430. function addPoint( id ) {
  40431. vertices.push( 0, 0, 0 );
  40432. colors.push( 0, 0, 0 );
  40433. if ( pointMap[ id ] === undefined ) {
  40434. pointMap[ id ] = [];
  40435. }
  40436. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  40437. }
  40438. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40439. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40440. super( geometry, material );
  40441. this.type = 'CameraHelper';
  40442. /**
  40443. * The camera being visualized.
  40444. *
  40445. * @type {Camera}
  40446. */
  40447. this.camera = camera;
  40448. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  40449. this.matrix = camera.matrixWorld;
  40450. this.matrixAutoUpdate = false;
  40451. /**
  40452. * This contains the points used to visualize the camera.
  40453. *
  40454. * @type {Object<string,Array<number>>}
  40455. */
  40456. this.pointMap = pointMap;
  40457. this.update();
  40458. // colors
  40459. const colorFrustum = new Color( 0xffaa00 );
  40460. const colorCone = new Color( 0xff0000 );
  40461. const colorUp = new Color( 0x00aaff );
  40462. const colorTarget = new Color( 0xffffff );
  40463. const colorCross = new Color( 0x333333 );
  40464. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  40465. }
  40466. /**
  40467. * Defines the colors of the helper.
  40468. *
  40469. * @param {Color} frustum - The frustum line color.
  40470. * @param {Color} cone - The cone line color.
  40471. * @param {Color} up - The up line color.
  40472. * @param {Color} target - The target line color.
  40473. * @param {Color} cross - The cross line color.
  40474. */
  40475. setColors( frustum, cone, up, target, cross ) {
  40476. const geometry = this.geometry;
  40477. const colorAttribute = geometry.getAttribute( 'color' );
  40478. // near
  40479. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  40480. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  40481. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  40482. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  40483. // far
  40484. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  40485. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  40486. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  40487. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  40488. // sides
  40489. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  40490. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  40491. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  40492. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  40493. // cone
  40494. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  40495. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  40496. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  40497. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  40498. // up
  40499. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  40500. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  40501. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  40502. // target
  40503. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  40504. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  40505. // cross
  40506. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  40507. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  40508. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  40509. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  40510. colorAttribute.needsUpdate = true;
  40511. }
  40512. /**
  40513. * Updates the helper based on the projection matrix of the camera.
  40514. */
  40515. update() {
  40516. const geometry = this.geometry;
  40517. const pointMap = this.pointMap;
  40518. const w = 1, h = 1;
  40519. // we need just camera projection matrix inverse
  40520. // world matrix must be identity
  40521. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  40522. // Adjust z values based on coordinate system
  40523. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? - 1 : 0;
  40524. // center / target
  40525. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  40526. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  40527. // near
  40528. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  40529. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  40530. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  40531. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  40532. // far
  40533. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  40534. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  40535. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  40536. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  40537. // up
  40538. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  40539. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  40540. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  40541. // cross
  40542. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  40543. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  40544. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  40545. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  40546. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  40547. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  40548. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  40549. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  40550. geometry.getAttribute( 'position' ).needsUpdate = true;
  40551. }
  40552. /**
  40553. * Frees the GPU-related resources allocated by this instance. Call this
  40554. * method whenever this instance is no longer used in your app.
  40555. */
  40556. dispose() {
  40557. this.geometry.dispose();
  40558. this.material.dispose();
  40559. }
  40560. }
  40561. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  40562. _vector.set( x, y, z ).unproject( camera );
  40563. const points = pointMap[ point ];
  40564. if ( points !== undefined ) {
  40565. const position = geometry.getAttribute( 'position' );
  40566. for ( let i = 0, l = points.length; i < l; i ++ ) {
  40567. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  40568. }
  40569. }
  40570. }
  40571. const _box = /*@__PURE__*/ new Box3();
  40572. /**
  40573. * Helper object to graphically show the world-axis-aligned bounding box
  40574. * around an object. The actual bounding box is handled with {@link Box3},
  40575. * this is just a visual helper for debugging. It can be automatically
  40576. * resized with {@link BoxHelper#update} when the object it's created from
  40577. * is transformed. Note that the object must have a geometry for this to work,
  40578. * so it won't work with sprites.
  40579. *
  40580. * ```js
  40581. * const sphere = new THREE.SphereGeometry();
  40582. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  40583. * const box = new THREE.BoxHelper( object, 0xffff00 );
  40584. * scene.add( box );
  40585. * ```
  40586. *
  40587. * @augments LineSegments
  40588. */
  40589. class BoxHelper extends LineSegments {
  40590. /**
  40591. * Constructs a new box helper.
  40592. *
  40593. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  40594. * @param {number|Color|string} [color=0xffff00] - The box's color.
  40595. */
  40596. constructor( object, color = 0xffff00 ) {
  40597. 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 ] );
  40598. const positions = new Float32Array( 8 * 3 );
  40599. const geometry = new BufferGeometry();
  40600. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  40601. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  40602. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40603. /**
  40604. * The 3D object being visualized.
  40605. *
  40606. * @type {Object3D}
  40607. */
  40608. this.object = object;
  40609. this.type = 'BoxHelper';
  40610. this.matrixAutoUpdate = false;
  40611. this.update();
  40612. }
  40613. /**
  40614. * Updates the helper's geometry to match the dimensions of the object,
  40615. * including any children.
  40616. */
  40617. update() {
  40618. if ( this.object !== undefined ) {
  40619. _box.setFromObject( this.object );
  40620. }
  40621. if ( _box.isEmpty() ) return;
  40622. const min = _box.min;
  40623. const max = _box.max;
  40624. /*
  40625. 5____4
  40626. 1/___0/|
  40627. | 6__|_7
  40628. 2/___3/
  40629. 0: max.x, max.y, max.z
  40630. 1: min.x, max.y, max.z
  40631. 2: min.x, min.y, max.z
  40632. 3: max.x, min.y, max.z
  40633. 4: max.x, max.y, min.z
  40634. 5: min.x, max.y, min.z
  40635. 6: min.x, min.y, min.z
  40636. 7: max.x, min.y, min.z
  40637. */
  40638. const position = this.geometry.attributes.position;
  40639. const array = position.array;
  40640. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  40641. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  40642. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  40643. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  40644. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  40645. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  40646. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  40647. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  40648. position.needsUpdate = true;
  40649. this.geometry.computeBoundingSphere();
  40650. }
  40651. /**
  40652. * Updates the wireframe box for the passed object.
  40653. *
  40654. * @param {Object3D} object - The 3D object to create the helper for.
  40655. * @return {BoxHelper} A reference to this instance.
  40656. */
  40657. setFromObject( object ) {
  40658. this.object = object;
  40659. this.update();
  40660. return this;
  40661. }
  40662. copy( source, recursive ) {
  40663. super.copy( source, recursive );
  40664. this.object = source.object;
  40665. return this;
  40666. }
  40667. /**
  40668. * Frees the GPU-related resources allocated by this instance. Call this
  40669. * method whenever this instance is no longer used in your app.
  40670. */
  40671. dispose() {
  40672. this.geometry.dispose();
  40673. this.material.dispose();
  40674. }
  40675. }
  40676. /**
  40677. * A helper object to visualize an instance of {@link Box3}.
  40678. *
  40679. * ```js
  40680. * const box = new THREE.Box3();
  40681. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  40682. *
  40683. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  40684. * scene.add( helper )
  40685. * ```
  40686. *
  40687. * @augments LineSegments
  40688. */
  40689. class Box3Helper extends LineSegments {
  40690. /**
  40691. * Constructs a new box3 helper.
  40692. *
  40693. * @param {Box3} box - The box to visualize.
  40694. * @param {number|Color|string} [color=0xffff00] - The box's color.
  40695. */
  40696. constructor( box, color = 0xffff00 ) {
  40697. 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 ] );
  40698. 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 ];
  40699. const geometry = new BufferGeometry();
  40700. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  40701. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40702. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40703. /**
  40704. * The box being visualized.
  40705. *
  40706. * @type {Box3}
  40707. */
  40708. this.box = box;
  40709. this.type = 'Box3Helper';
  40710. this.geometry.computeBoundingSphere();
  40711. }
  40712. updateMatrixWorld( force ) {
  40713. const box = this.box;
  40714. if ( box.isEmpty() ) return;
  40715. box.getCenter( this.position );
  40716. box.getSize( this.scale );
  40717. this.scale.multiplyScalar( 0.5 );
  40718. super.updateMatrixWorld( force );
  40719. }
  40720. /**
  40721. * Frees the GPU-related resources allocated by this instance. Call this
  40722. * method whenever this instance is no longer used in your app.
  40723. */
  40724. dispose() {
  40725. this.geometry.dispose();
  40726. this.material.dispose();
  40727. }
  40728. }
  40729. /**
  40730. * A helper object to visualize an instance of {@link Plane}.
  40731. *
  40732. * ```js
  40733. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  40734. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  40735. * scene.add( helper );
  40736. * ```
  40737. *
  40738. * @augments Line
  40739. */
  40740. class PlaneHelper extends Line {
  40741. /**
  40742. * Constructs a new plane helper.
  40743. *
  40744. * @param {Plane} plane - The plane to be visualized.
  40745. * @param {number} [size=1] - The side length of plane helper.
  40746. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  40747. */
  40748. constructor( plane, size = 1, hex = 0xffff00 ) {
  40749. const color = hex;
  40750. 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 ];
  40751. const geometry = new BufferGeometry();
  40752. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40753. geometry.computeBoundingSphere();
  40754. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40755. this.type = 'PlaneHelper';
  40756. /**
  40757. * The plane being visualized.
  40758. *
  40759. * @type {Plane}
  40760. */
  40761. this.plane = plane;
  40762. /**
  40763. * The side length of plane helper.
  40764. *
  40765. * @type {number}
  40766. * @default 1
  40767. */
  40768. this.size = size;
  40769. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  40770. const geometry2 = new BufferGeometry();
  40771. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  40772. geometry2.computeBoundingSphere();
  40773. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  40774. }
  40775. updateMatrixWorld( force ) {
  40776. this.position.set( 0, 0, 0 );
  40777. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  40778. this.lookAt( this.plane.normal );
  40779. this.translateZ( - this.plane.constant );
  40780. super.updateMatrixWorld( force );
  40781. }
  40782. /**
  40783. * Updates the helper to match the position and direction of the
  40784. * light being visualized.
  40785. */
  40786. dispose() {
  40787. this.geometry.dispose();
  40788. this.material.dispose();
  40789. this.children[ 0 ].geometry.dispose();
  40790. this.children[ 0 ].material.dispose();
  40791. }
  40792. }
  40793. const _axis = /*@__PURE__*/ new Vector3();
  40794. let _lineGeometry, _coneGeometry;
  40795. /**
  40796. * An 3D arrow object for visualizing directions.
  40797. *
  40798. * ```js
  40799. * const dir = new THREE.Vector3( 1, 2, 0 );
  40800. *
  40801. * //normalize the direction vector (convert to vector of length 1)
  40802. * dir.normalize();
  40803. *
  40804. * const origin = new THREE.Vector3( 0, 0, 0 );
  40805. * const length = 1;
  40806. * const hex = 0xffff00;
  40807. *
  40808. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  40809. * scene.add( arrowHelper );
  40810. * ```
  40811. *
  40812. * @augments Object3D
  40813. */
  40814. class ArrowHelper extends Object3D {
  40815. /**
  40816. * Constructs a new arrow helper.
  40817. *
  40818. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  40819. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  40820. * @param {number} [length=1] - Length of the arrow in world units.
  40821. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  40822. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  40823. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  40824. */
  40825. 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 ) {
  40826. super();
  40827. this.type = 'ArrowHelper';
  40828. if ( _lineGeometry === undefined ) {
  40829. _lineGeometry = new BufferGeometry();
  40830. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  40831. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  40832. _coneGeometry.translate( 0, - 0.5, 0 );
  40833. }
  40834. this.position.copy( origin );
  40835. /**
  40836. * The line part of the arrow helper.
  40837. *
  40838. * @type {Line}
  40839. */
  40840. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  40841. this.line.matrixAutoUpdate = false;
  40842. this.add( this.line );
  40843. /**
  40844. * The cone part of the arrow helper.
  40845. *
  40846. * @type {Mesh}
  40847. */
  40848. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  40849. this.cone.matrixAutoUpdate = false;
  40850. this.add( this.cone );
  40851. this.setDirection( dir );
  40852. this.setLength( length, headLength, headWidth );
  40853. }
  40854. /**
  40855. * Sets the direction of the helper.
  40856. *
  40857. * @param {Vector3} dir - The normalized direction vector.
  40858. */
  40859. setDirection( dir ) {
  40860. // dir is assumed to be normalized
  40861. if ( dir.y > 0.99999 ) {
  40862. this.quaternion.set( 0, 0, 0, 1 );
  40863. } else if ( dir.y < - 0.99999 ) {
  40864. this.quaternion.set( 1, 0, 0, 0 );
  40865. } else {
  40866. _axis.set( dir.z, 0, - dir.x ).normalize();
  40867. const radians = Math.acos( dir.y );
  40868. this.quaternion.setFromAxisAngle( _axis, radians );
  40869. }
  40870. }
  40871. /**
  40872. * Sets the length of the helper.
  40873. *
  40874. * @param {number} length - Length of the arrow in world units.
  40875. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  40876. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  40877. */
  40878. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  40879. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  40880. this.line.updateMatrix();
  40881. this.cone.scale.set( headWidth, headLength, headWidth );
  40882. this.cone.position.y = length;
  40883. this.cone.updateMatrix();
  40884. }
  40885. /**
  40886. * Sets the color of the helper.
  40887. *
  40888. * @param {number|Color|string} color - The color to set.
  40889. */
  40890. setColor( color ) {
  40891. this.line.material.color.set( color );
  40892. this.cone.material.color.set( color );
  40893. }
  40894. copy( source ) {
  40895. super.copy( source, false );
  40896. this.line.copy( source.line );
  40897. this.cone.copy( source.cone );
  40898. return this;
  40899. }
  40900. /**
  40901. * Frees the GPU-related resources allocated by this instance. Call this
  40902. * method whenever this instance is no longer used in your app.
  40903. */
  40904. dispose() {
  40905. this.line.geometry.dispose();
  40906. this.line.material.dispose();
  40907. this.cone.geometry.dispose();
  40908. this.cone.material.dispose();
  40909. }
  40910. }
  40911. /**
  40912. * An axis object to visualize the 3 axes in a simple way.
  40913. * The X axis is red. The Y axis is green. The Z axis is blue.
  40914. *
  40915. * ```js
  40916. * const axesHelper = new THREE.AxesHelper( 5 );
  40917. * scene.add( axesHelper );
  40918. * ```
  40919. *
  40920. * @augments LineSegments
  40921. */
  40922. class AxesHelper extends LineSegments {
  40923. /**
  40924. * Constructs a new axes helper.
  40925. *
  40926. * @param {number} [size=1] - Size of the lines representing the axes.
  40927. */
  40928. constructor( size = 1 ) {
  40929. const vertices = [
  40930. 0, 0, 0, size, 0, 0,
  40931. 0, 0, 0, 0, size, 0,
  40932. 0, 0, 0, 0, 0, size
  40933. ];
  40934. const colors = [
  40935. 1, 0, 0, 1, 0.6, 0,
  40936. 0, 1, 0, 0.6, 1, 0,
  40937. 0, 0, 1, 0, 0.6, 1
  40938. ];
  40939. const geometry = new BufferGeometry();
  40940. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40941. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40942. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  40943. super( geometry, material );
  40944. this.type = 'AxesHelper';
  40945. }
  40946. /**
  40947. * Defines the colors of the axes helper.
  40948. *
  40949. * @param {number|Color|string} xAxisColor - The color for the x axis.
  40950. * @param {number|Color|string} yAxisColor - The color for the y axis.
  40951. * @param {number|Color|string} zAxisColor - The color for the z axis.
  40952. * @return {AxesHelper} A reference to this axes helper.
  40953. */
  40954. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  40955. const color = new Color();
  40956. const array = this.geometry.attributes.color.array;
  40957. color.set( xAxisColor );
  40958. color.toArray( array, 0 );
  40959. color.toArray( array, 3 );
  40960. color.set( yAxisColor );
  40961. color.toArray( array, 6 );
  40962. color.toArray( array, 9 );
  40963. color.set( zAxisColor );
  40964. color.toArray( array, 12 );
  40965. color.toArray( array, 15 );
  40966. this.geometry.attributes.color.needsUpdate = true;
  40967. return this;
  40968. }
  40969. /**
  40970. * Frees the GPU-related resources allocated by this instance. Call this
  40971. * method whenever this instance is no longer used in your app.
  40972. */
  40973. dispose() {
  40974. this.geometry.dispose();
  40975. this.material.dispose();
  40976. }
  40977. }
  40978. /**
  40979. * This class is used to convert a series of paths to an array of
  40980. * shapes. It is specifically used in context of fonts and SVG.
  40981. */
  40982. class ShapePath {
  40983. /**
  40984. * Constructs a new shape path.
  40985. */
  40986. constructor() {
  40987. this.type = 'ShapePath';
  40988. /**
  40989. * The color of the shape.
  40990. *
  40991. * @type {Color}
  40992. */
  40993. this.color = new Color();
  40994. /**
  40995. * The paths that have been generated for this shape.
  40996. *
  40997. * @type {Array<Path>}
  40998. * @default null
  40999. */
  41000. this.subPaths = [];
  41001. /**
  41002. * The current path that is being generated.
  41003. *
  41004. * @type {?Path}
  41005. * @default null
  41006. */
  41007. this.currentPath = null;
  41008. }
  41009. /**
  41010. * Creates a new path and moves it current point to the given one.
  41011. *
  41012. * @param {number} x - The x coordinate.
  41013. * @param {number} y - The y coordinate.
  41014. * @return {ShapePath} A reference to this shape path.
  41015. */
  41016. moveTo( x, y ) {
  41017. this.currentPath = new Path();
  41018. this.subPaths.push( this.currentPath );
  41019. this.currentPath.moveTo( x, y );
  41020. return this;
  41021. }
  41022. /**
  41023. * Adds an instance of {@link LineCurve} to the path by connecting
  41024. * the current point with the given one.
  41025. *
  41026. * @param {number} x - The x coordinate of the end point.
  41027. * @param {number} y - The y coordinate of the end point.
  41028. * @return {ShapePath} A reference to this shape path.
  41029. */
  41030. lineTo( x, y ) {
  41031. this.currentPath.lineTo( x, y );
  41032. return this;
  41033. }
  41034. /**
  41035. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41036. * the current point with the given one.
  41037. *
  41038. * @param {number} aCPx - The x coordinate of the control point.
  41039. * @param {number} aCPy - The y coordinate of the control point.
  41040. * @param {number} aX - The x coordinate of the end point.
  41041. * @param {number} aY - The y coordinate of the end point.
  41042. * @return {ShapePath} A reference to this shape path.
  41043. */
  41044. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41045. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41046. return this;
  41047. }
  41048. /**
  41049. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41050. * the current point with the given one.
  41051. *
  41052. * @param {number} aCP1x - The x coordinate of the first control point.
  41053. * @param {number} aCP1y - The y coordinate of the first control point.
  41054. * @param {number} aCP2x - The x coordinate of the second control point.
  41055. * @param {number} aCP2y - The y coordinate of the second control point.
  41056. * @param {number} aX - The x coordinate of the end point.
  41057. * @param {number} aY - The y coordinate of the end point.
  41058. * @return {ShapePath} A reference to this shape path.
  41059. */
  41060. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  41061. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  41062. return this;
  41063. }
  41064. /**
  41065. * Adds an instance of {@link SplineCurve} to the path by connecting
  41066. * the current point with the given list of points.
  41067. *
  41068. * @param {Array<Vector2>} pts - An array of points in 2D space.
  41069. * @return {ShapePath} A reference to this shape path.
  41070. */
  41071. splineThru( pts ) {
  41072. this.currentPath.splineThru( pts );
  41073. return this;
  41074. }
  41075. /**
  41076. * Converts the paths into an array of shapes.
  41077. *
  41078. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  41079. * If this flag is set to `true`, then those are flipped.
  41080. * @return {Array<Shape>} An array of shapes.
  41081. */
  41082. toShapes( isCCW ) {
  41083. function toShapesNoHoles( inSubpaths ) {
  41084. const shapes = [];
  41085. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  41086. const tmpPath = inSubpaths[ i ];
  41087. const tmpShape = new Shape();
  41088. tmpShape.curves = tmpPath.curves;
  41089. shapes.push( tmpShape );
  41090. }
  41091. return shapes;
  41092. }
  41093. function isPointInsidePolygon( inPt, inPolygon ) {
  41094. const polyLen = inPolygon.length;
  41095. // inPt on polygon contour => immediate success or
  41096. // toggling of inside/outside at every single! intersection point of an edge
  41097. // with the horizontal line through inPt, left of inPt
  41098. // not counting lowerY endpoints of edges and whole edges on that line
  41099. let inside = false;
  41100. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  41101. let edgeLowPt = inPolygon[ p ];
  41102. let edgeHighPt = inPolygon[ q ];
  41103. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  41104. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  41105. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  41106. // not parallel
  41107. if ( edgeDy < 0 ) {
  41108. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  41109. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  41110. }
  41111. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  41112. if ( inPt.y === edgeLowPt.y ) {
  41113. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  41114. // continue; // no intersection or edgeLowPt => doesn't count !!!
  41115. } else {
  41116. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  41117. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  41118. if ( perpEdge < 0 ) continue;
  41119. inside = ! inside; // true intersection left of inPt
  41120. }
  41121. } else {
  41122. // parallel or collinear
  41123. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  41124. // edge lies on the same horizontal line as inPt
  41125. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  41126. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  41127. // continue;
  41128. }
  41129. }
  41130. return inside;
  41131. }
  41132. const isClockWise = ShapeUtils.isClockWise;
  41133. const subPaths = this.subPaths;
  41134. if ( subPaths.length === 0 ) return [];
  41135. let solid, tmpPath, tmpShape;
  41136. const shapes = [];
  41137. if ( subPaths.length === 1 ) {
  41138. tmpPath = subPaths[ 0 ];
  41139. tmpShape = new Shape();
  41140. tmpShape.curves = tmpPath.curves;
  41141. shapes.push( tmpShape );
  41142. return shapes;
  41143. }
  41144. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  41145. holesFirst = isCCW ? ! holesFirst : holesFirst;
  41146. // console.log("Holes first", holesFirst);
  41147. const betterShapeHoles = [];
  41148. const newShapes = [];
  41149. let newShapeHoles = [];
  41150. let mainIdx = 0;
  41151. let tmpPoints;
  41152. newShapes[ mainIdx ] = undefined;
  41153. newShapeHoles[ mainIdx ] = [];
  41154. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  41155. tmpPath = subPaths[ i ];
  41156. tmpPoints = tmpPath.getPoints();
  41157. solid = isClockWise( tmpPoints );
  41158. solid = isCCW ? ! solid : solid;
  41159. if ( solid ) {
  41160. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  41161. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  41162. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  41163. if ( holesFirst ) mainIdx ++;
  41164. newShapeHoles[ mainIdx ] = [];
  41165. //console.log('cw', i);
  41166. } else {
  41167. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  41168. //console.log('ccw', i);
  41169. }
  41170. }
  41171. // only Holes? -> probably all Shapes with wrong orientation
  41172. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  41173. if ( newShapes.length > 1 ) {
  41174. let ambiguous = false;
  41175. let toChange = 0;
  41176. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41177. betterShapeHoles[ sIdx ] = [];
  41178. }
  41179. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  41180. const sho = newShapeHoles[ sIdx ];
  41181. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  41182. const ho = sho[ hIdx ];
  41183. let hole_unassigned = true;
  41184. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  41185. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  41186. if ( sIdx !== s2Idx ) toChange ++;
  41187. if ( hole_unassigned ) {
  41188. hole_unassigned = false;
  41189. betterShapeHoles[ s2Idx ].push( ho );
  41190. } else {
  41191. ambiguous = true;
  41192. }
  41193. }
  41194. }
  41195. if ( hole_unassigned ) {
  41196. betterShapeHoles[ sIdx ].push( ho );
  41197. }
  41198. }
  41199. }
  41200. if ( toChange > 0 && ambiguous === false ) {
  41201. newShapeHoles = betterShapeHoles;
  41202. }
  41203. }
  41204. let tmpHoles;
  41205. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  41206. tmpShape = newShapes[ i ].s;
  41207. shapes.push( tmpShape );
  41208. tmpHoles = newShapeHoles[ i ];
  41209. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  41210. tmpShape.holes.push( tmpHoles[ j ].h );
  41211. }
  41212. }
  41213. //console.log("shape", shapes);
  41214. return shapes;
  41215. }
  41216. }
  41217. /**
  41218. * Abstract base class for controls.
  41219. *
  41220. * @abstract
  41221. * @augments EventDispatcher
  41222. */
  41223. class Controls extends EventDispatcher {
  41224. /**
  41225. * Constructs a new controls instance.
  41226. *
  41227. * @param {Object3D} object - The object that is managed by the controls.
  41228. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  41229. */
  41230. constructor( object, domElement = null ) {
  41231. super();
  41232. /**
  41233. * The object that is managed by the controls.
  41234. *
  41235. * @type {Object3D}
  41236. */
  41237. this.object = object;
  41238. /**
  41239. * The HTML element used for event listeners.
  41240. *
  41241. * @type {?HTMLDOMElement}
  41242. * @default null
  41243. */
  41244. this.domElement = domElement;
  41245. /**
  41246. * Whether the controls responds to user input or not.
  41247. *
  41248. * @type {boolean}
  41249. * @default true
  41250. */
  41251. this.enabled = true;
  41252. /**
  41253. * The internal state of the controls.
  41254. *
  41255. * @type {number}
  41256. * @default -1
  41257. */
  41258. this.state = - 1;
  41259. /**
  41260. * This object defines the keyboard input of the controls.
  41261. *
  41262. * @type {Object}
  41263. */
  41264. this.keys = {};
  41265. /**
  41266. * This object defines what type of actions are assigned to the available mouse buttons.
  41267. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  41268. *
  41269. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  41270. */
  41271. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  41272. /**
  41273. * This object defines what type of actions are assigned to what kind of touch interaction.
  41274. * It depends on the control implementation what kind of touch interaction and actions are supported.
  41275. *
  41276. * @type {{ONE: ?number, TWO: ?number}}
  41277. */
  41278. this.touches = { ONE: null, TWO: null };
  41279. }
  41280. /**
  41281. * Connects the controls to the DOM. This method has so called "side effects" since
  41282. * it adds the module's event listeners to the DOM.
  41283. *
  41284. * @param {HTMLDOMElement} element - The DOM element to connect to.
  41285. */
  41286. connect( element ) {
  41287. if ( element === undefined ) {
  41288. console.warn( 'THREE.Controls: connect() now requires an element.' );
  41289. return;
  41290. }
  41291. if ( this.domElement !== null ) this.disconnect();
  41292. this.domElement = element;
  41293. }
  41294. /**
  41295. * Disconnects the controls from the DOM.
  41296. */
  41297. disconnect() {}
  41298. /**
  41299. * Call this method if you no longer want use to the controls. It frees all internal
  41300. * resources and removes all event listeners.
  41301. */
  41302. dispose() {}
  41303. /**
  41304. * Controls should implement this method if they have to update their internal state
  41305. * per simulation step.
  41306. *
  41307. * @param {number} [delta] - The time delta in seconds.
  41308. */
  41309. update( /* delta */ ) {}
  41310. }
  41311. /**
  41312. * Scales the texture as large as possible within its surface without cropping
  41313. * or stretching the texture. The method preserves the original aspect ratio of
  41314. * the texture. Akin to CSS `object-fit: contain`
  41315. *
  41316. * @param {Texture} texture - The texture.
  41317. * @param {number} aspect - The texture's aspect ratio.
  41318. * @return {Texture} The updated texture.
  41319. */
  41320. function contain( texture, aspect ) {
  41321. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41322. if ( imageAspect > aspect ) {
  41323. texture.repeat.x = 1;
  41324. texture.repeat.y = imageAspect / aspect;
  41325. texture.offset.x = 0;
  41326. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41327. } else {
  41328. texture.repeat.x = aspect / imageAspect;
  41329. texture.repeat.y = 1;
  41330. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41331. texture.offset.y = 0;
  41332. }
  41333. return texture;
  41334. }
  41335. /**
  41336. * Scales the texture to the smallest possible size to fill the surface, leaving
  41337. * no empty space. The method preserves the original aspect ratio of the texture.
  41338. * Akin to CSS `object-fit: cover`.
  41339. *
  41340. * @param {Texture} texture - The texture.
  41341. * @param {number} aspect - The texture's aspect ratio.
  41342. * @return {Texture} The updated texture.
  41343. */
  41344. function cover( texture, aspect ) {
  41345. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  41346. if ( imageAspect > aspect ) {
  41347. texture.repeat.x = aspect / imageAspect;
  41348. texture.repeat.y = 1;
  41349. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  41350. texture.offset.y = 0;
  41351. } else {
  41352. texture.repeat.x = 1;
  41353. texture.repeat.y = imageAspect / aspect;
  41354. texture.offset.x = 0;
  41355. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  41356. }
  41357. return texture;
  41358. }
  41359. /**
  41360. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  41361. *
  41362. * @param {Texture} texture - The texture.
  41363. * @return {Texture} The updated texture.
  41364. */
  41365. function fill( texture ) {
  41366. texture.repeat.x = 1;
  41367. texture.repeat.y = 1;
  41368. texture.offset.x = 0;
  41369. texture.offset.y = 0;
  41370. return texture;
  41371. }
  41372. /**
  41373. * Determines how many bytes must be used to represent the texture.
  41374. *
  41375. * @param {number} width - The width of the texture.
  41376. * @param {number} height - The height of the texture.
  41377. * @param {number} format - The texture's format.
  41378. * @param {number} type - The texture's type.
  41379. * @return {number} The byte length.
  41380. */
  41381. function getByteLength( width, height, format, type ) {
  41382. const typeByteLength = getTextureTypeByteLength( type );
  41383. switch ( format ) {
  41384. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  41385. case AlphaFormat:
  41386. return width * height;
  41387. case LuminanceFormat:
  41388. return width * height;
  41389. case LuminanceAlphaFormat:
  41390. return width * height * 2;
  41391. case RedFormat:
  41392. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41393. case RedIntegerFormat:
  41394. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  41395. case RGFormat:
  41396. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41397. case RGIntegerFormat:
  41398. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41399. case RGBFormat:
  41400. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41401. case RGBAFormat:
  41402. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41403. case RGBAIntegerFormat:
  41404. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  41405. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  41406. case RGB_S3TC_DXT1_Format:
  41407. case RGBA_S3TC_DXT1_Format:
  41408. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41409. case RGBA_S3TC_DXT3_Format:
  41410. case RGBA_S3TC_DXT5_Format:
  41411. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41412. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  41413. case RGB_PVRTC_2BPPV1_Format:
  41414. case RGBA_PVRTC_2BPPV1_Format:
  41415. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  41416. case RGB_PVRTC_4BPPV1_Format:
  41417. case RGBA_PVRTC_4BPPV1_Format:
  41418. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  41419. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  41420. case RGB_ETC1_Format:
  41421. case RGB_ETC2_Format:
  41422. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  41423. case RGBA_ETC2_EAC_Format:
  41424. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41425. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  41426. case RGBA_ASTC_4x4_Format:
  41427. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41428. case RGBA_ASTC_5x4_Format:
  41429. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  41430. case RGBA_ASTC_5x5_Format:
  41431. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41432. case RGBA_ASTC_6x5_Format:
  41433. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41434. case RGBA_ASTC_6x6_Format:
  41435. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41436. case RGBA_ASTC_8x5_Format:
  41437. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41438. case RGBA_ASTC_8x6_Format:
  41439. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41440. case RGBA_ASTC_8x8_Format:
  41441. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41442. case RGBA_ASTC_10x5_Format:
  41443. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  41444. case RGBA_ASTC_10x6_Format:
  41445. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  41446. case RGBA_ASTC_10x8_Format:
  41447. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  41448. case RGBA_ASTC_10x10_Format:
  41449. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41450. case RGBA_ASTC_12x10_Format:
  41451. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  41452. case RGBA_ASTC_12x12_Format:
  41453. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  41454. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  41455. case RGBA_BPTC_Format:
  41456. case RGB_BPTC_SIGNED_Format:
  41457. case RGB_BPTC_UNSIGNED_Format:
  41458. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41459. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  41460. case RED_RGTC1_Format:
  41461. case SIGNED_RED_RGTC1_Format:
  41462. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  41463. case RED_GREEN_RGTC2_Format:
  41464. case SIGNED_RED_GREEN_RGTC2_Format:
  41465. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  41466. }
  41467. throw new Error(
  41468. `Unable to determine texture byte length for ${format} format.`,
  41469. );
  41470. }
  41471. function getTextureTypeByteLength( type ) {
  41472. switch ( type ) {
  41473. case UnsignedByteType:
  41474. case ByteType:
  41475. return { byteLength: 1, components: 1 };
  41476. case UnsignedShortType:
  41477. case ShortType:
  41478. case HalfFloatType:
  41479. return { byteLength: 2, components: 1 };
  41480. case UnsignedShort4444Type:
  41481. case UnsignedShort5551Type:
  41482. return { byteLength: 2, components: 4 };
  41483. case UnsignedIntType:
  41484. case IntType:
  41485. case FloatType:
  41486. return { byteLength: 4, components: 1 };
  41487. case UnsignedInt5999Type:
  41488. return { byteLength: 4, components: 3 };
  41489. }
  41490. throw new Error( `Unknown texture type ${type}.` );
  41491. }
  41492. /**
  41493. * A class containing utility functions for textures.
  41494. *
  41495. * @hideconstructor
  41496. */
  41497. class TextureUtils {
  41498. /**
  41499. * Scales the texture as large as possible within its surface without cropping
  41500. * or stretching the texture. The method preserves the original aspect ratio of
  41501. * the texture. Akin to CSS `object-fit: contain`
  41502. *
  41503. * @param {Texture} texture - The texture.
  41504. * @param {number} aspect - The texture's aspect ratio.
  41505. * @return {Texture} The updated texture.
  41506. */
  41507. static contain( texture, aspect ) {
  41508. return contain( texture, aspect );
  41509. }
  41510. /**
  41511. * Scales the texture to the smallest possible size to fill the surface, leaving
  41512. * no empty space. The method preserves the original aspect ratio of the texture.
  41513. * Akin to CSS `object-fit: cover`.
  41514. *
  41515. * @param {Texture} texture - The texture.
  41516. * @param {number} aspect - The texture's aspect ratio.
  41517. * @return {Texture} The updated texture.
  41518. */
  41519. static cover( texture, aspect ) {
  41520. return cover( texture, aspect );
  41521. }
  41522. /**
  41523. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  41524. *
  41525. * @param {Texture} texture - The texture.
  41526. * @return {Texture} The updated texture.
  41527. */
  41528. static fill( texture ) {
  41529. return fill( texture );
  41530. }
  41531. /**
  41532. * Determines how many bytes must be used to represent the texture.
  41533. *
  41534. * @param {number} width - The width of the texture.
  41535. * @param {number} height - The height of the texture.
  41536. * @param {number} format - The texture's format.
  41537. * @param {number} type - The texture's type.
  41538. * @return {number} The byte length.
  41539. */
  41540. static getByteLength( width, height, format, type ) {
  41541. return getByteLength( width, height, format, type );
  41542. }
  41543. }
  41544. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  41545. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  41546. revision: REVISION,
  41547. } } ) );
  41548. }
  41549. if ( typeof window !== 'undefined' ) {
  41550. if ( window.__THREE__ ) {
  41551. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  41552. } else {
  41553. window.__THREE__ = REVISION;
  41554. }
  41555. }
  41556. function WebGLAnimation() {
  41557. let context = null;
  41558. let isAnimating = false;
  41559. let animationLoop = null;
  41560. let requestId = null;
  41561. function onAnimationFrame( time, frame ) {
  41562. animationLoop( time, frame );
  41563. requestId = context.requestAnimationFrame( onAnimationFrame );
  41564. }
  41565. return {
  41566. start: function () {
  41567. if ( isAnimating === true ) return;
  41568. if ( animationLoop === null ) return;
  41569. requestId = context.requestAnimationFrame( onAnimationFrame );
  41570. isAnimating = true;
  41571. },
  41572. stop: function () {
  41573. context.cancelAnimationFrame( requestId );
  41574. isAnimating = false;
  41575. },
  41576. setAnimationLoop: function ( callback ) {
  41577. animationLoop = callback;
  41578. },
  41579. setContext: function ( value ) {
  41580. context = value;
  41581. }
  41582. };
  41583. }
  41584. function WebGLAttributes( gl ) {
  41585. const buffers = new WeakMap();
  41586. function createBuffer( attribute, bufferType ) {
  41587. const array = attribute.array;
  41588. const usage = attribute.usage;
  41589. const size = array.byteLength;
  41590. const buffer = gl.createBuffer();
  41591. gl.bindBuffer( bufferType, buffer );
  41592. gl.bufferData( bufferType, array, usage );
  41593. attribute.onUploadCallback();
  41594. let type;
  41595. if ( array instanceof Float32Array ) {
  41596. type = gl.FLOAT;
  41597. } else if ( array instanceof Uint16Array ) {
  41598. if ( attribute.isFloat16BufferAttribute ) {
  41599. type = gl.HALF_FLOAT;
  41600. } else {
  41601. type = gl.UNSIGNED_SHORT;
  41602. }
  41603. } else if ( array instanceof Int16Array ) {
  41604. type = gl.SHORT;
  41605. } else if ( array instanceof Uint32Array ) {
  41606. type = gl.UNSIGNED_INT;
  41607. } else if ( array instanceof Int32Array ) {
  41608. type = gl.INT;
  41609. } else if ( array instanceof Int8Array ) {
  41610. type = gl.BYTE;
  41611. } else if ( array instanceof Uint8Array ) {
  41612. type = gl.UNSIGNED_BYTE;
  41613. } else if ( array instanceof Uint8ClampedArray ) {
  41614. type = gl.UNSIGNED_BYTE;
  41615. } else {
  41616. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  41617. }
  41618. return {
  41619. buffer: buffer,
  41620. type: type,
  41621. bytesPerElement: array.BYTES_PER_ELEMENT,
  41622. version: attribute.version,
  41623. size: size
  41624. };
  41625. }
  41626. function updateBuffer( buffer, attribute, bufferType ) {
  41627. const array = attribute.array;
  41628. const updateRanges = attribute.updateRanges;
  41629. gl.bindBuffer( bufferType, buffer );
  41630. if ( updateRanges.length === 0 ) {
  41631. // Not using update ranges
  41632. gl.bufferSubData( bufferType, 0, array );
  41633. } else {
  41634. // Before applying update ranges, we merge any adjacent / overlapping
  41635. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  41636. // to performance improvements for applications which make heavy use of
  41637. // update ranges. Likely due to GPU command overhead.
  41638. //
  41639. // Note that to reduce garbage collection between frames, we merge the
  41640. // update ranges in-place. This is safe because this method will clear the
  41641. // update ranges once updated.
  41642. updateRanges.sort( ( a, b ) => a.start - b.start );
  41643. // To merge the update ranges in-place, we work from left to right in the
  41644. // existing updateRanges array, merging ranges. This may result in a final
  41645. // array which is smaller than the original. This index tracks the last
  41646. // index representing a merged range, any data after this index can be
  41647. // trimmed once the merge algorithm is completed.
  41648. let mergeIndex = 0;
  41649. for ( let i = 1; i < updateRanges.length; i ++ ) {
  41650. const previousRange = updateRanges[ mergeIndex ];
  41651. const range = updateRanges[ i ];
  41652. // We add one here to merge adjacent ranges. This is safe because ranges
  41653. // operate over positive integers.
  41654. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  41655. previousRange.count = Math.max(
  41656. previousRange.count,
  41657. range.start + range.count - previousRange.start
  41658. );
  41659. } else {
  41660. ++ mergeIndex;
  41661. updateRanges[ mergeIndex ] = range;
  41662. }
  41663. }
  41664. // Trim the array to only contain the merged ranges.
  41665. updateRanges.length = mergeIndex + 1;
  41666. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41667. const range = updateRanges[ i ];
  41668. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  41669. array, range.start, range.count );
  41670. }
  41671. attribute.clearUpdateRanges();
  41672. }
  41673. attribute.onUploadCallback();
  41674. }
  41675. //
  41676. function get( attribute ) {
  41677. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41678. return buffers.get( attribute );
  41679. }
  41680. function remove( attribute ) {
  41681. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41682. const data = buffers.get( attribute );
  41683. if ( data ) {
  41684. gl.deleteBuffer( data.buffer );
  41685. buffers.delete( attribute );
  41686. }
  41687. }
  41688. function update( attribute, bufferType ) {
  41689. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  41690. if ( attribute.isGLBufferAttribute ) {
  41691. const cached = buffers.get( attribute );
  41692. if ( ! cached || cached.version < attribute.version ) {
  41693. buffers.set( attribute, {
  41694. buffer: attribute.buffer,
  41695. type: attribute.type,
  41696. bytesPerElement: attribute.elementSize,
  41697. version: attribute.version
  41698. } );
  41699. }
  41700. return;
  41701. }
  41702. const data = buffers.get( attribute );
  41703. if ( data === undefined ) {
  41704. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  41705. } else if ( data.version < attribute.version ) {
  41706. if ( data.size !== attribute.array.byteLength ) {
  41707. 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.' );
  41708. }
  41709. updateBuffer( data.buffer, attribute, bufferType );
  41710. data.version = attribute.version;
  41711. }
  41712. }
  41713. return {
  41714. get: get,
  41715. remove: remove,
  41716. update: update
  41717. };
  41718. }
  41719. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  41720. 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";
  41721. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  41722. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  41723. 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";
  41724. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  41725. 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";
  41726. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  41727. 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";
  41728. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  41729. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  41730. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  41731. 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";
  41732. 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";
  41733. 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";
  41734. 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";
  41735. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  41736. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  41737. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  41738. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  41739. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  41740. 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";
  41741. 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";
  41742. 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}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\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";
  41743. 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";
  41744. 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";
  41745. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  41746. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  41747. 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";
  41748. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  41749. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  41750. 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}";
  41751. 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";
  41752. 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\t\n#endif";
  41753. 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";
  41754. 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";
  41755. 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";
  41756. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  41757. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  41758. 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";
  41759. 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";
  41760. 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}";
  41761. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  41762. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  41763. 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";
  41764. 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";
  41765. 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, roughness * 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";
  41766. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  41767. 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";
  41768. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  41769. 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";
  41770. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - 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 = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), 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.07, 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";
  41771. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\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#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 saturate(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.specularColor;\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 * transposeMat3( 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 a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\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}\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.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * 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\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\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 );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\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}";
  41772. 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.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\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 )\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";
  41773. 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";
  41774. 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";
  41775. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  41776. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  41777. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  41778. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  41779. 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";
  41780. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  41781. 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";
  41782. 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";
  41783. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  41784. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  41785. 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";
  41786. 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";
  41787. 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";
  41788. 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";
  41789. 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";
  41790. 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;";
  41791. 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";
  41792. 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";
  41793. 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";
  41794. 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";
  41795. 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";
  41796. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  41797. 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";
  41798. 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";
  41799. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  41800. 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 );";
  41801. 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}";
  41802. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  41803. 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;";
  41804. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  41805. 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";
  41806. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  41807. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  41808. 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\tuniform sampler2D directionalShadowMap[ 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\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\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 sampler2D pointShadowMap[ 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\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D 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\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif";
  41809. 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";
  41810. 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";
  41811. 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\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}";
  41812. 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";
  41813. 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";
  41814. 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";
  41815. 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";
  41816. 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";
  41817. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  41818. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  41819. 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; }";
  41820. 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.diffuseColor, material.specularColor, 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";
  41821. 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";
  41822. 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";
  41823. 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";
  41824. 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";
  41825. 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";
  41826. 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}";
  41827. 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}";
  41828. 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}";
  41829. 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}";
  41830. 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}";
  41831. 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}";
  41832. 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}";
  41833. 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\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\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}";
  41834. 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}";
  41835. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\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 <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 = packDepthToRGBA( dist );\n}";
  41836. 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}";
  41837. 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}";
  41838. 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}";
  41839. 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}";
  41840. 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}";
  41841. 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}";
  41842. 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}";
  41843. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\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}";
  41844. 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}";
  41845. 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}";
  41846. 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}";
  41847. 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 <packing>\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( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  41848. 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}";
  41849. 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 <packing>\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}";
  41850. 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}";
  41851. 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 <packing>\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\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\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}";
  41852. 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}";
  41853. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\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}";
  41854. 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}";
  41855. 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}";
  41856. 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}";
  41857. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\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}";
  41858. 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}";
  41859. 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}";
  41860. const ShaderChunk = {
  41861. alphahash_fragment: alphahash_fragment,
  41862. alphahash_pars_fragment: alphahash_pars_fragment,
  41863. alphamap_fragment: alphamap_fragment,
  41864. alphamap_pars_fragment: alphamap_pars_fragment,
  41865. alphatest_fragment: alphatest_fragment,
  41866. alphatest_pars_fragment: alphatest_pars_fragment,
  41867. aomap_fragment: aomap_fragment,
  41868. aomap_pars_fragment: aomap_pars_fragment,
  41869. batching_pars_vertex: batching_pars_vertex,
  41870. batching_vertex: batching_vertex,
  41871. begin_vertex: begin_vertex,
  41872. beginnormal_vertex: beginnormal_vertex,
  41873. bsdfs: bsdfs,
  41874. iridescence_fragment: iridescence_fragment,
  41875. bumpmap_pars_fragment: bumpmap_pars_fragment,
  41876. clipping_planes_fragment: clipping_planes_fragment,
  41877. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  41878. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  41879. clipping_planes_vertex: clipping_planes_vertex,
  41880. color_fragment: color_fragment,
  41881. color_pars_fragment: color_pars_fragment,
  41882. color_pars_vertex: color_pars_vertex,
  41883. color_vertex: color_vertex,
  41884. common: common,
  41885. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  41886. defaultnormal_vertex: defaultnormal_vertex,
  41887. displacementmap_pars_vertex: displacementmap_pars_vertex,
  41888. displacementmap_vertex: displacementmap_vertex,
  41889. emissivemap_fragment: emissivemap_fragment,
  41890. emissivemap_pars_fragment: emissivemap_pars_fragment,
  41891. colorspace_fragment: colorspace_fragment,
  41892. colorspace_pars_fragment: colorspace_pars_fragment,
  41893. envmap_fragment: envmap_fragment,
  41894. envmap_common_pars_fragment: envmap_common_pars_fragment,
  41895. envmap_pars_fragment: envmap_pars_fragment,
  41896. envmap_pars_vertex: envmap_pars_vertex,
  41897. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  41898. envmap_vertex: envmap_vertex,
  41899. fog_vertex: fog_vertex,
  41900. fog_pars_vertex: fog_pars_vertex,
  41901. fog_fragment: fog_fragment,
  41902. fog_pars_fragment: fog_pars_fragment,
  41903. gradientmap_pars_fragment: gradientmap_pars_fragment,
  41904. lightmap_pars_fragment: lightmap_pars_fragment,
  41905. lights_lambert_fragment: lights_lambert_fragment,
  41906. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  41907. lights_pars_begin: lights_pars_begin,
  41908. lights_toon_fragment: lights_toon_fragment,
  41909. lights_toon_pars_fragment: lights_toon_pars_fragment,
  41910. lights_phong_fragment: lights_phong_fragment,
  41911. lights_phong_pars_fragment: lights_phong_pars_fragment,
  41912. lights_physical_fragment: lights_physical_fragment,
  41913. lights_physical_pars_fragment: lights_physical_pars_fragment,
  41914. lights_fragment_begin: lights_fragment_begin,
  41915. lights_fragment_maps: lights_fragment_maps,
  41916. lights_fragment_end: lights_fragment_end,
  41917. logdepthbuf_fragment: logdepthbuf_fragment,
  41918. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  41919. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  41920. logdepthbuf_vertex: logdepthbuf_vertex,
  41921. map_fragment: map_fragment,
  41922. map_pars_fragment: map_pars_fragment,
  41923. map_particle_fragment: map_particle_fragment,
  41924. map_particle_pars_fragment: map_particle_pars_fragment,
  41925. metalnessmap_fragment: metalnessmap_fragment,
  41926. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  41927. morphinstance_vertex: morphinstance_vertex,
  41928. morphcolor_vertex: morphcolor_vertex,
  41929. morphnormal_vertex: morphnormal_vertex,
  41930. morphtarget_pars_vertex: morphtarget_pars_vertex,
  41931. morphtarget_vertex: morphtarget_vertex,
  41932. normal_fragment_begin: normal_fragment_begin,
  41933. normal_fragment_maps: normal_fragment_maps,
  41934. normal_pars_fragment: normal_pars_fragment,
  41935. normal_pars_vertex: normal_pars_vertex,
  41936. normal_vertex: normal_vertex,
  41937. normalmap_pars_fragment: normalmap_pars_fragment,
  41938. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  41939. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  41940. clearcoat_pars_fragment: clearcoat_pars_fragment,
  41941. iridescence_pars_fragment: iridescence_pars_fragment,
  41942. opaque_fragment: opaque_fragment,
  41943. packing: packing,
  41944. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  41945. project_vertex: project_vertex,
  41946. dithering_fragment: dithering_fragment,
  41947. dithering_pars_fragment: dithering_pars_fragment,
  41948. roughnessmap_fragment: roughnessmap_fragment,
  41949. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  41950. shadowmap_pars_fragment: shadowmap_pars_fragment,
  41951. shadowmap_pars_vertex: shadowmap_pars_vertex,
  41952. shadowmap_vertex: shadowmap_vertex,
  41953. shadowmask_pars_fragment: shadowmask_pars_fragment,
  41954. skinbase_vertex: skinbase_vertex,
  41955. skinning_pars_vertex: skinning_pars_vertex,
  41956. skinning_vertex: skinning_vertex,
  41957. skinnormal_vertex: skinnormal_vertex,
  41958. specularmap_fragment: specularmap_fragment,
  41959. specularmap_pars_fragment: specularmap_pars_fragment,
  41960. tonemapping_fragment: tonemapping_fragment,
  41961. tonemapping_pars_fragment: tonemapping_pars_fragment,
  41962. transmission_fragment: transmission_fragment,
  41963. transmission_pars_fragment: transmission_pars_fragment,
  41964. uv_pars_fragment: uv_pars_fragment,
  41965. uv_pars_vertex: uv_pars_vertex,
  41966. uv_vertex: uv_vertex,
  41967. worldpos_vertex: worldpos_vertex,
  41968. background_vert: vertex$h,
  41969. background_frag: fragment$h,
  41970. backgroundCube_vert: vertex$g,
  41971. backgroundCube_frag: fragment$g,
  41972. cube_vert: vertex$f,
  41973. cube_frag: fragment$f,
  41974. depth_vert: vertex$e,
  41975. depth_frag: fragment$e,
  41976. distanceRGBA_vert: vertex$d,
  41977. distanceRGBA_frag: fragment$d,
  41978. equirect_vert: vertex$c,
  41979. equirect_frag: fragment$c,
  41980. linedashed_vert: vertex$b,
  41981. linedashed_frag: fragment$b,
  41982. meshbasic_vert: vertex$a,
  41983. meshbasic_frag: fragment$a,
  41984. meshlambert_vert: vertex$9,
  41985. meshlambert_frag: fragment$9,
  41986. meshmatcap_vert: vertex$8,
  41987. meshmatcap_frag: fragment$8,
  41988. meshnormal_vert: vertex$7,
  41989. meshnormal_frag: fragment$7,
  41990. meshphong_vert: vertex$6,
  41991. meshphong_frag: fragment$6,
  41992. meshphysical_vert: vertex$5,
  41993. meshphysical_frag: fragment$5,
  41994. meshtoon_vert: vertex$4,
  41995. meshtoon_frag: fragment$4,
  41996. points_vert: vertex$3,
  41997. points_frag: fragment$3,
  41998. shadow_vert: vertex$2,
  41999. shadow_frag: fragment$2,
  42000. sprite_vert: vertex$1,
  42001. sprite_frag: fragment$1
  42002. };
  42003. // Uniforms library for shared webgl shaders
  42004. const UniformsLib = {
  42005. common: {
  42006. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42007. opacity: { value: 1.0 },
  42008. map: { value: null },
  42009. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42010. alphaMap: { value: null },
  42011. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42012. alphaTest: { value: 0 }
  42013. },
  42014. specularmap: {
  42015. specularMap: { value: null },
  42016. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42017. },
  42018. envmap: {
  42019. envMap: { value: null },
  42020. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  42021. flipEnvMap: { value: - 1 },
  42022. reflectivity: { value: 1.0 }, // basic, lambert, phong
  42023. ior: { value: 1.5 }, // physical
  42024. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  42025. },
  42026. aomap: {
  42027. aoMap: { value: null },
  42028. aoMapIntensity: { value: 1 },
  42029. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42030. },
  42031. lightmap: {
  42032. lightMap: { value: null },
  42033. lightMapIntensity: { value: 1 },
  42034. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42035. },
  42036. bumpmap: {
  42037. bumpMap: { value: null },
  42038. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42039. bumpScale: { value: 1 }
  42040. },
  42041. normalmap: {
  42042. normalMap: { value: null },
  42043. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42044. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  42045. },
  42046. displacementmap: {
  42047. displacementMap: { value: null },
  42048. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42049. displacementScale: { value: 1 },
  42050. displacementBias: { value: 0 }
  42051. },
  42052. emissivemap: {
  42053. emissiveMap: { value: null },
  42054. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42055. },
  42056. metalnessmap: {
  42057. metalnessMap: { value: null },
  42058. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42059. },
  42060. roughnessmap: {
  42061. roughnessMap: { value: null },
  42062. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  42063. },
  42064. gradientmap: {
  42065. gradientMap: { value: null }
  42066. },
  42067. fog: {
  42068. fogDensity: { value: 0.00025 },
  42069. fogNear: { value: 1 },
  42070. fogFar: { value: 2000 },
  42071. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  42072. },
  42073. lights: {
  42074. ambientLightColor: { value: [] },
  42075. lightProbe: { value: [] },
  42076. directionalLights: { value: [], properties: {
  42077. direction: {},
  42078. color: {}
  42079. } },
  42080. directionalLightShadows: { value: [], properties: {
  42081. shadowIntensity: 1,
  42082. shadowBias: {},
  42083. shadowNormalBias: {},
  42084. shadowRadius: {},
  42085. shadowMapSize: {}
  42086. } },
  42087. directionalShadowMap: { value: [] },
  42088. directionalShadowMatrix: { value: [] },
  42089. spotLights: { value: [], properties: {
  42090. color: {},
  42091. position: {},
  42092. direction: {},
  42093. distance: {},
  42094. coneCos: {},
  42095. penumbraCos: {},
  42096. decay: {}
  42097. } },
  42098. spotLightShadows: { value: [], properties: {
  42099. shadowIntensity: 1,
  42100. shadowBias: {},
  42101. shadowNormalBias: {},
  42102. shadowRadius: {},
  42103. shadowMapSize: {}
  42104. } },
  42105. spotLightMap: { value: [] },
  42106. spotShadowMap: { value: [] },
  42107. spotLightMatrix: { value: [] },
  42108. pointLights: { value: [], properties: {
  42109. color: {},
  42110. position: {},
  42111. decay: {},
  42112. distance: {}
  42113. } },
  42114. pointLightShadows: { value: [], properties: {
  42115. shadowIntensity: 1,
  42116. shadowBias: {},
  42117. shadowNormalBias: {},
  42118. shadowRadius: {},
  42119. shadowMapSize: {},
  42120. shadowCameraNear: {},
  42121. shadowCameraFar: {}
  42122. } },
  42123. pointShadowMap: { value: [] },
  42124. pointShadowMatrix: { value: [] },
  42125. hemisphereLights: { value: [], properties: {
  42126. direction: {},
  42127. skyColor: {},
  42128. groundColor: {}
  42129. } },
  42130. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  42131. rectAreaLights: { value: [], properties: {
  42132. color: {},
  42133. position: {},
  42134. width: {},
  42135. height: {}
  42136. } },
  42137. ltc_1: { value: null },
  42138. ltc_2: { value: null }
  42139. },
  42140. points: {
  42141. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42142. opacity: { value: 1.0 },
  42143. size: { value: 1.0 },
  42144. scale: { value: 1.0 },
  42145. map: { value: null },
  42146. alphaMap: { value: null },
  42147. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42148. alphaTest: { value: 0 },
  42149. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  42150. },
  42151. sprite: {
  42152. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  42153. opacity: { value: 1.0 },
  42154. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  42155. rotation: { value: 0.0 },
  42156. map: { value: null },
  42157. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42158. alphaMap: { value: null },
  42159. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42160. alphaTest: { value: 0 }
  42161. }
  42162. };
  42163. const ShaderLib = {
  42164. basic: {
  42165. uniforms: /*@__PURE__*/ mergeUniforms( [
  42166. UniformsLib.common,
  42167. UniformsLib.specularmap,
  42168. UniformsLib.envmap,
  42169. UniformsLib.aomap,
  42170. UniformsLib.lightmap,
  42171. UniformsLib.fog
  42172. ] ),
  42173. vertexShader: ShaderChunk.meshbasic_vert,
  42174. fragmentShader: ShaderChunk.meshbasic_frag
  42175. },
  42176. lambert: {
  42177. uniforms: /*@__PURE__*/ mergeUniforms( [
  42178. UniformsLib.common,
  42179. UniformsLib.specularmap,
  42180. UniformsLib.envmap,
  42181. UniformsLib.aomap,
  42182. UniformsLib.lightmap,
  42183. UniformsLib.emissivemap,
  42184. UniformsLib.bumpmap,
  42185. UniformsLib.normalmap,
  42186. UniformsLib.displacementmap,
  42187. UniformsLib.fog,
  42188. UniformsLib.lights,
  42189. {
  42190. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  42191. }
  42192. ] ),
  42193. vertexShader: ShaderChunk.meshlambert_vert,
  42194. fragmentShader: ShaderChunk.meshlambert_frag
  42195. },
  42196. phong: {
  42197. uniforms: /*@__PURE__*/ mergeUniforms( [
  42198. UniformsLib.common,
  42199. UniformsLib.specularmap,
  42200. UniformsLib.envmap,
  42201. UniformsLib.aomap,
  42202. UniformsLib.lightmap,
  42203. UniformsLib.emissivemap,
  42204. UniformsLib.bumpmap,
  42205. UniformsLib.normalmap,
  42206. UniformsLib.displacementmap,
  42207. UniformsLib.fog,
  42208. UniformsLib.lights,
  42209. {
  42210. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42211. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  42212. shininess: { value: 30 }
  42213. }
  42214. ] ),
  42215. vertexShader: ShaderChunk.meshphong_vert,
  42216. fragmentShader: ShaderChunk.meshphong_frag
  42217. },
  42218. standard: {
  42219. uniforms: /*@__PURE__*/ mergeUniforms( [
  42220. UniformsLib.common,
  42221. UniformsLib.envmap,
  42222. UniformsLib.aomap,
  42223. UniformsLib.lightmap,
  42224. UniformsLib.emissivemap,
  42225. UniformsLib.bumpmap,
  42226. UniformsLib.normalmap,
  42227. UniformsLib.displacementmap,
  42228. UniformsLib.roughnessmap,
  42229. UniformsLib.metalnessmap,
  42230. UniformsLib.fog,
  42231. UniformsLib.lights,
  42232. {
  42233. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42234. roughness: { value: 1.0 },
  42235. metalness: { value: 0.0 },
  42236. envMapIntensity: { value: 1 }
  42237. }
  42238. ] ),
  42239. vertexShader: ShaderChunk.meshphysical_vert,
  42240. fragmentShader: ShaderChunk.meshphysical_frag
  42241. },
  42242. toon: {
  42243. uniforms: /*@__PURE__*/ mergeUniforms( [
  42244. UniformsLib.common,
  42245. UniformsLib.aomap,
  42246. UniformsLib.lightmap,
  42247. UniformsLib.emissivemap,
  42248. UniformsLib.bumpmap,
  42249. UniformsLib.normalmap,
  42250. UniformsLib.displacementmap,
  42251. UniformsLib.gradientmap,
  42252. UniformsLib.fog,
  42253. UniformsLib.lights,
  42254. {
  42255. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  42256. }
  42257. ] ),
  42258. vertexShader: ShaderChunk.meshtoon_vert,
  42259. fragmentShader: ShaderChunk.meshtoon_frag
  42260. },
  42261. matcap: {
  42262. uniforms: /*@__PURE__*/ mergeUniforms( [
  42263. UniformsLib.common,
  42264. UniformsLib.bumpmap,
  42265. UniformsLib.normalmap,
  42266. UniformsLib.displacementmap,
  42267. UniformsLib.fog,
  42268. {
  42269. matcap: { value: null }
  42270. }
  42271. ] ),
  42272. vertexShader: ShaderChunk.meshmatcap_vert,
  42273. fragmentShader: ShaderChunk.meshmatcap_frag
  42274. },
  42275. points: {
  42276. uniforms: /*@__PURE__*/ mergeUniforms( [
  42277. UniformsLib.points,
  42278. UniformsLib.fog
  42279. ] ),
  42280. vertexShader: ShaderChunk.points_vert,
  42281. fragmentShader: ShaderChunk.points_frag
  42282. },
  42283. dashed: {
  42284. uniforms: /*@__PURE__*/ mergeUniforms( [
  42285. UniformsLib.common,
  42286. UniformsLib.fog,
  42287. {
  42288. scale: { value: 1 },
  42289. dashSize: { value: 1 },
  42290. totalSize: { value: 2 }
  42291. }
  42292. ] ),
  42293. vertexShader: ShaderChunk.linedashed_vert,
  42294. fragmentShader: ShaderChunk.linedashed_frag
  42295. },
  42296. depth: {
  42297. uniforms: /*@__PURE__*/ mergeUniforms( [
  42298. UniformsLib.common,
  42299. UniformsLib.displacementmap
  42300. ] ),
  42301. vertexShader: ShaderChunk.depth_vert,
  42302. fragmentShader: ShaderChunk.depth_frag
  42303. },
  42304. normal: {
  42305. uniforms: /*@__PURE__*/ mergeUniforms( [
  42306. UniformsLib.common,
  42307. UniformsLib.bumpmap,
  42308. UniformsLib.normalmap,
  42309. UniformsLib.displacementmap,
  42310. {
  42311. opacity: { value: 1.0 }
  42312. }
  42313. ] ),
  42314. vertexShader: ShaderChunk.meshnormal_vert,
  42315. fragmentShader: ShaderChunk.meshnormal_frag
  42316. },
  42317. sprite: {
  42318. uniforms: /*@__PURE__*/ mergeUniforms( [
  42319. UniformsLib.sprite,
  42320. UniformsLib.fog
  42321. ] ),
  42322. vertexShader: ShaderChunk.sprite_vert,
  42323. fragmentShader: ShaderChunk.sprite_frag
  42324. },
  42325. background: {
  42326. uniforms: {
  42327. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  42328. t2D: { value: null },
  42329. backgroundIntensity: { value: 1 }
  42330. },
  42331. vertexShader: ShaderChunk.background_vert,
  42332. fragmentShader: ShaderChunk.background_frag
  42333. },
  42334. backgroundCube: {
  42335. uniforms: {
  42336. envMap: { value: null },
  42337. flipEnvMap: { value: - 1 },
  42338. backgroundBlurriness: { value: 0 },
  42339. backgroundIntensity: { value: 1 },
  42340. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  42341. },
  42342. vertexShader: ShaderChunk.backgroundCube_vert,
  42343. fragmentShader: ShaderChunk.backgroundCube_frag
  42344. },
  42345. cube: {
  42346. uniforms: {
  42347. tCube: { value: null },
  42348. tFlip: { value: - 1 },
  42349. opacity: { value: 1.0 }
  42350. },
  42351. vertexShader: ShaderChunk.cube_vert,
  42352. fragmentShader: ShaderChunk.cube_frag
  42353. },
  42354. equirect: {
  42355. uniforms: {
  42356. tEquirect: { value: null },
  42357. },
  42358. vertexShader: ShaderChunk.equirect_vert,
  42359. fragmentShader: ShaderChunk.equirect_frag
  42360. },
  42361. distanceRGBA: {
  42362. uniforms: /*@__PURE__*/ mergeUniforms( [
  42363. UniformsLib.common,
  42364. UniformsLib.displacementmap,
  42365. {
  42366. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  42367. nearDistance: { value: 1 },
  42368. farDistance: { value: 1000 }
  42369. }
  42370. ] ),
  42371. vertexShader: ShaderChunk.distanceRGBA_vert,
  42372. fragmentShader: ShaderChunk.distanceRGBA_frag
  42373. },
  42374. shadow: {
  42375. uniforms: /*@__PURE__*/ mergeUniforms( [
  42376. UniformsLib.lights,
  42377. UniformsLib.fog,
  42378. {
  42379. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  42380. opacity: { value: 1.0 }
  42381. },
  42382. ] ),
  42383. vertexShader: ShaderChunk.shadow_vert,
  42384. fragmentShader: ShaderChunk.shadow_frag
  42385. }
  42386. };
  42387. ShaderLib.physical = {
  42388. uniforms: /*@__PURE__*/ mergeUniforms( [
  42389. ShaderLib.standard.uniforms,
  42390. {
  42391. clearcoat: { value: 0 },
  42392. clearcoatMap: { value: null },
  42393. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42394. clearcoatNormalMap: { value: null },
  42395. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42396. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  42397. clearcoatRoughness: { value: 0 },
  42398. clearcoatRoughnessMap: { value: null },
  42399. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42400. dispersion: { value: 0 },
  42401. iridescence: { value: 0 },
  42402. iridescenceMap: { value: null },
  42403. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42404. iridescenceIOR: { value: 1.3 },
  42405. iridescenceThicknessMinimum: { value: 100 },
  42406. iridescenceThicknessMaximum: { value: 400 },
  42407. iridescenceThicknessMap: { value: null },
  42408. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42409. sheen: { value: 0 },
  42410. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42411. sheenColorMap: { value: null },
  42412. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42413. sheenRoughness: { value: 1 },
  42414. sheenRoughnessMap: { value: null },
  42415. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42416. transmission: { value: 0 },
  42417. transmissionMap: { value: null },
  42418. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42419. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  42420. transmissionSamplerMap: { value: null },
  42421. thickness: { value: 0 },
  42422. thicknessMap: { value: null },
  42423. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42424. attenuationDistance: { value: 0 },
  42425. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  42426. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  42427. specularColorMap: { value: null },
  42428. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42429. specularIntensity: { value: 1 },
  42430. specularIntensityMap: { value: null },
  42431. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42432. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  42433. anisotropyMap: { value: null },
  42434. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  42435. }
  42436. ] ),
  42437. vertexShader: ShaderChunk.meshphysical_vert,
  42438. fragmentShader: ShaderChunk.meshphysical_frag
  42439. };
  42440. const _rgb = { r: 0, b: 0, g: 0 };
  42441. const _e1$1 = /*@__PURE__*/ new Euler();
  42442. const _m1$1 = /*@__PURE__*/ new Matrix4();
  42443. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  42444. const clearColor = new Color( 0x000000 );
  42445. let clearAlpha = alpha === true ? 0 : 1;
  42446. let planeMesh;
  42447. let boxMesh;
  42448. let currentBackground = null;
  42449. let currentBackgroundVersion = 0;
  42450. let currentTonemapping = null;
  42451. function getBackground( scene ) {
  42452. let background = scene.isScene === true ? scene.background : null;
  42453. if ( background && background.isTexture ) {
  42454. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  42455. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  42456. }
  42457. return background;
  42458. }
  42459. function render( scene ) {
  42460. let forceClear = false;
  42461. const background = getBackground( scene );
  42462. if ( background === null ) {
  42463. setClear( clearColor, clearAlpha );
  42464. } else if ( background && background.isColor ) {
  42465. setClear( background, 1 );
  42466. forceClear = true;
  42467. }
  42468. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  42469. if ( environmentBlendMode === 'additive' ) {
  42470. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  42471. } else if ( environmentBlendMode === 'alpha-blend' ) {
  42472. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  42473. }
  42474. if ( renderer.autoClear || forceClear ) {
  42475. // buffers might not be writable which is required to ensure a correct clear
  42476. state.buffers.depth.setTest( true );
  42477. state.buffers.depth.setMask( true );
  42478. state.buffers.color.setMask( true );
  42479. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  42480. }
  42481. }
  42482. function addToRenderList( renderList, scene ) {
  42483. const background = getBackground( scene );
  42484. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  42485. if ( boxMesh === undefined ) {
  42486. boxMesh = new Mesh(
  42487. new BoxGeometry( 1, 1, 1 ),
  42488. new ShaderMaterial( {
  42489. name: 'BackgroundCubeMaterial',
  42490. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  42491. vertexShader: ShaderLib.backgroundCube.vertexShader,
  42492. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  42493. side: BackSide,
  42494. depthTest: false,
  42495. depthWrite: false,
  42496. fog: false,
  42497. allowOverride: false
  42498. } )
  42499. );
  42500. boxMesh.geometry.deleteAttribute( 'normal' );
  42501. boxMesh.geometry.deleteAttribute( 'uv' );
  42502. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  42503. this.matrixWorld.copyPosition( camera.matrixWorld );
  42504. };
  42505. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  42506. Object.defineProperty( boxMesh.material, 'envMap', {
  42507. get: function () {
  42508. return this.uniforms.envMap.value;
  42509. }
  42510. } );
  42511. objects.update( boxMesh );
  42512. }
  42513. _e1$1.copy( scene.backgroundRotation );
  42514. // accommodate left-handed frame
  42515. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  42516. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  42517. // environment maps which are not cube render targets or PMREMs follow a different convention
  42518. _e1$1.y *= - 1;
  42519. _e1$1.z *= - 1;
  42520. }
  42521. boxMesh.material.uniforms.envMap.value = background;
  42522. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  42523. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  42524. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  42525. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  42526. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  42527. if ( currentBackground !== background ||
  42528. currentBackgroundVersion !== background.version ||
  42529. currentTonemapping !== renderer.toneMapping ) {
  42530. boxMesh.material.needsUpdate = true;
  42531. currentBackground = background;
  42532. currentBackgroundVersion = background.version;
  42533. currentTonemapping = renderer.toneMapping;
  42534. }
  42535. boxMesh.layers.enableAll();
  42536. // push to the pre-sorted opaque render list
  42537. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  42538. } else if ( background && background.isTexture ) {
  42539. if ( planeMesh === undefined ) {
  42540. planeMesh = new Mesh(
  42541. new PlaneGeometry( 2, 2 ),
  42542. new ShaderMaterial( {
  42543. name: 'BackgroundMaterial',
  42544. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  42545. vertexShader: ShaderLib.background.vertexShader,
  42546. fragmentShader: ShaderLib.background.fragmentShader,
  42547. side: FrontSide,
  42548. depthTest: false,
  42549. depthWrite: false,
  42550. fog: false,
  42551. allowOverride: false
  42552. } )
  42553. );
  42554. planeMesh.geometry.deleteAttribute( 'normal' );
  42555. // add "map" material property so the renderer can evaluate it like for built-in materials
  42556. Object.defineProperty( planeMesh.material, 'map', {
  42557. get: function () {
  42558. return this.uniforms.t2D.value;
  42559. }
  42560. } );
  42561. objects.update( planeMesh );
  42562. }
  42563. planeMesh.material.uniforms.t2D.value = background;
  42564. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  42565. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  42566. if ( background.matrixAutoUpdate === true ) {
  42567. background.updateMatrix();
  42568. }
  42569. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  42570. if ( currentBackground !== background ||
  42571. currentBackgroundVersion !== background.version ||
  42572. currentTonemapping !== renderer.toneMapping ) {
  42573. planeMesh.material.needsUpdate = true;
  42574. currentBackground = background;
  42575. currentBackgroundVersion = background.version;
  42576. currentTonemapping = renderer.toneMapping;
  42577. }
  42578. planeMesh.layers.enableAll();
  42579. // push to the pre-sorted opaque render list
  42580. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  42581. }
  42582. }
  42583. function setClear( color, alpha ) {
  42584. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  42585. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  42586. }
  42587. function dispose() {
  42588. if ( boxMesh !== undefined ) {
  42589. boxMesh.geometry.dispose();
  42590. boxMesh.material.dispose();
  42591. boxMesh = undefined;
  42592. }
  42593. if ( planeMesh !== undefined ) {
  42594. planeMesh.geometry.dispose();
  42595. planeMesh.material.dispose();
  42596. planeMesh = undefined;
  42597. }
  42598. }
  42599. return {
  42600. getClearColor: function () {
  42601. return clearColor;
  42602. },
  42603. setClearColor: function ( color, alpha = 1 ) {
  42604. clearColor.set( color );
  42605. clearAlpha = alpha;
  42606. setClear( clearColor, clearAlpha );
  42607. },
  42608. getClearAlpha: function () {
  42609. return clearAlpha;
  42610. },
  42611. setClearAlpha: function ( alpha ) {
  42612. clearAlpha = alpha;
  42613. setClear( clearColor, clearAlpha );
  42614. },
  42615. render: render,
  42616. addToRenderList: addToRenderList,
  42617. dispose: dispose
  42618. };
  42619. }
  42620. function WebGLBindingStates( gl, attributes ) {
  42621. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  42622. const bindingStates = {};
  42623. const defaultState = createBindingState( null );
  42624. let currentState = defaultState;
  42625. let forceUpdate = false;
  42626. function setup( object, material, program, geometry, index ) {
  42627. let updateBuffers = false;
  42628. const state = getBindingState( geometry, program, material );
  42629. if ( currentState !== state ) {
  42630. currentState = state;
  42631. bindVertexArrayObject( currentState.object );
  42632. }
  42633. updateBuffers = needsUpdate( object, geometry, program, index );
  42634. if ( updateBuffers ) saveCache( object, geometry, program, index );
  42635. if ( index !== null ) {
  42636. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  42637. }
  42638. if ( updateBuffers || forceUpdate ) {
  42639. forceUpdate = false;
  42640. setupVertexAttributes( object, material, program, geometry );
  42641. if ( index !== null ) {
  42642. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  42643. }
  42644. }
  42645. }
  42646. function createVertexArrayObject() {
  42647. return gl.createVertexArray();
  42648. }
  42649. function bindVertexArrayObject( vao ) {
  42650. return gl.bindVertexArray( vao );
  42651. }
  42652. function deleteVertexArrayObject( vao ) {
  42653. return gl.deleteVertexArray( vao );
  42654. }
  42655. function getBindingState( geometry, program, material ) {
  42656. const wireframe = ( material.wireframe === true );
  42657. let programMap = bindingStates[ geometry.id ];
  42658. if ( programMap === undefined ) {
  42659. programMap = {};
  42660. bindingStates[ geometry.id ] = programMap;
  42661. }
  42662. let stateMap = programMap[ program.id ];
  42663. if ( stateMap === undefined ) {
  42664. stateMap = {};
  42665. programMap[ program.id ] = stateMap;
  42666. }
  42667. let state = stateMap[ wireframe ];
  42668. if ( state === undefined ) {
  42669. state = createBindingState( createVertexArrayObject() );
  42670. stateMap[ wireframe ] = state;
  42671. }
  42672. return state;
  42673. }
  42674. function createBindingState( vao ) {
  42675. const newAttributes = [];
  42676. const enabledAttributes = [];
  42677. const attributeDivisors = [];
  42678. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  42679. newAttributes[ i ] = 0;
  42680. enabledAttributes[ i ] = 0;
  42681. attributeDivisors[ i ] = 0;
  42682. }
  42683. return {
  42684. // for backward compatibility on non-VAO support browser
  42685. geometry: null,
  42686. program: null,
  42687. wireframe: false,
  42688. newAttributes: newAttributes,
  42689. enabledAttributes: enabledAttributes,
  42690. attributeDivisors: attributeDivisors,
  42691. object: vao,
  42692. attributes: {},
  42693. index: null
  42694. };
  42695. }
  42696. function needsUpdate( object, geometry, program, index ) {
  42697. const cachedAttributes = currentState.attributes;
  42698. const geometryAttributes = geometry.attributes;
  42699. let attributesNum = 0;
  42700. const programAttributes = program.getAttributes();
  42701. for ( const name in programAttributes ) {
  42702. const programAttribute = programAttributes[ name ];
  42703. if ( programAttribute.location >= 0 ) {
  42704. const cachedAttribute = cachedAttributes[ name ];
  42705. let geometryAttribute = geometryAttributes[ name ];
  42706. if ( geometryAttribute === undefined ) {
  42707. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  42708. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  42709. }
  42710. if ( cachedAttribute === undefined ) return true;
  42711. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  42712. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  42713. attributesNum ++;
  42714. }
  42715. }
  42716. if ( currentState.attributesNum !== attributesNum ) return true;
  42717. if ( currentState.index !== index ) return true;
  42718. return false;
  42719. }
  42720. function saveCache( object, geometry, program, index ) {
  42721. const cache = {};
  42722. const attributes = geometry.attributes;
  42723. let attributesNum = 0;
  42724. const programAttributes = program.getAttributes();
  42725. for ( const name in programAttributes ) {
  42726. const programAttribute = programAttributes[ name ];
  42727. if ( programAttribute.location >= 0 ) {
  42728. let attribute = attributes[ name ];
  42729. if ( attribute === undefined ) {
  42730. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  42731. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  42732. }
  42733. const data = {};
  42734. data.attribute = attribute;
  42735. if ( attribute && attribute.data ) {
  42736. data.data = attribute.data;
  42737. }
  42738. cache[ name ] = data;
  42739. attributesNum ++;
  42740. }
  42741. }
  42742. currentState.attributes = cache;
  42743. currentState.attributesNum = attributesNum;
  42744. currentState.index = index;
  42745. }
  42746. function initAttributes() {
  42747. const newAttributes = currentState.newAttributes;
  42748. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  42749. newAttributes[ i ] = 0;
  42750. }
  42751. }
  42752. function enableAttribute( attribute ) {
  42753. enableAttributeAndDivisor( attribute, 0 );
  42754. }
  42755. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  42756. const newAttributes = currentState.newAttributes;
  42757. const enabledAttributes = currentState.enabledAttributes;
  42758. const attributeDivisors = currentState.attributeDivisors;
  42759. newAttributes[ attribute ] = 1;
  42760. if ( enabledAttributes[ attribute ] === 0 ) {
  42761. gl.enableVertexAttribArray( attribute );
  42762. enabledAttributes[ attribute ] = 1;
  42763. }
  42764. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  42765. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  42766. attributeDivisors[ attribute ] = meshPerAttribute;
  42767. }
  42768. }
  42769. function disableUnusedAttributes() {
  42770. const newAttributes = currentState.newAttributes;
  42771. const enabledAttributes = currentState.enabledAttributes;
  42772. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  42773. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  42774. gl.disableVertexAttribArray( i );
  42775. enabledAttributes[ i ] = 0;
  42776. }
  42777. }
  42778. }
  42779. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  42780. if ( integer === true ) {
  42781. gl.vertexAttribIPointer( index, size, type, stride, offset );
  42782. } else {
  42783. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  42784. }
  42785. }
  42786. function setupVertexAttributes( object, material, program, geometry ) {
  42787. initAttributes();
  42788. const geometryAttributes = geometry.attributes;
  42789. const programAttributes = program.getAttributes();
  42790. const materialDefaultAttributeValues = material.defaultAttributeValues;
  42791. for ( const name in programAttributes ) {
  42792. const programAttribute = programAttributes[ name ];
  42793. if ( programAttribute.location >= 0 ) {
  42794. let geometryAttribute = geometryAttributes[ name ];
  42795. if ( geometryAttribute === undefined ) {
  42796. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  42797. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  42798. }
  42799. if ( geometryAttribute !== undefined ) {
  42800. const normalized = geometryAttribute.normalized;
  42801. const size = geometryAttribute.itemSize;
  42802. const attribute = attributes.get( geometryAttribute );
  42803. // TODO Attribute may not be available on context restore
  42804. if ( attribute === undefined ) continue;
  42805. const buffer = attribute.buffer;
  42806. const type = attribute.type;
  42807. const bytesPerElement = attribute.bytesPerElement;
  42808. // check for integer attributes
  42809. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  42810. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  42811. const data = geometryAttribute.data;
  42812. const stride = data.stride;
  42813. const offset = geometryAttribute.offset;
  42814. if ( data.isInstancedInterleavedBuffer ) {
  42815. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  42816. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  42817. }
  42818. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  42819. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  42820. }
  42821. } else {
  42822. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  42823. enableAttribute( programAttribute.location + i );
  42824. }
  42825. }
  42826. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  42827. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  42828. vertexAttribPointer(
  42829. programAttribute.location + i,
  42830. size / programAttribute.locationSize,
  42831. type,
  42832. normalized,
  42833. stride * bytesPerElement,
  42834. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  42835. integer
  42836. );
  42837. }
  42838. } else {
  42839. if ( geometryAttribute.isInstancedBufferAttribute ) {
  42840. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  42841. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  42842. }
  42843. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  42844. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  42845. }
  42846. } else {
  42847. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  42848. enableAttribute( programAttribute.location + i );
  42849. }
  42850. }
  42851. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  42852. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  42853. vertexAttribPointer(
  42854. programAttribute.location + i,
  42855. size / programAttribute.locationSize,
  42856. type,
  42857. normalized,
  42858. size * bytesPerElement,
  42859. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  42860. integer
  42861. );
  42862. }
  42863. }
  42864. } else if ( materialDefaultAttributeValues !== undefined ) {
  42865. const value = materialDefaultAttributeValues[ name ];
  42866. if ( value !== undefined ) {
  42867. switch ( value.length ) {
  42868. case 2:
  42869. gl.vertexAttrib2fv( programAttribute.location, value );
  42870. break;
  42871. case 3:
  42872. gl.vertexAttrib3fv( programAttribute.location, value );
  42873. break;
  42874. case 4:
  42875. gl.vertexAttrib4fv( programAttribute.location, value );
  42876. break;
  42877. default:
  42878. gl.vertexAttrib1fv( programAttribute.location, value );
  42879. }
  42880. }
  42881. }
  42882. }
  42883. }
  42884. disableUnusedAttributes();
  42885. }
  42886. function dispose() {
  42887. reset();
  42888. for ( const geometryId in bindingStates ) {
  42889. const programMap = bindingStates[ geometryId ];
  42890. for ( const programId in programMap ) {
  42891. const stateMap = programMap[ programId ];
  42892. for ( const wireframe in stateMap ) {
  42893. deleteVertexArrayObject( stateMap[ wireframe ].object );
  42894. delete stateMap[ wireframe ];
  42895. }
  42896. delete programMap[ programId ];
  42897. }
  42898. delete bindingStates[ geometryId ];
  42899. }
  42900. }
  42901. function releaseStatesOfGeometry( geometry ) {
  42902. if ( bindingStates[ geometry.id ] === undefined ) return;
  42903. const programMap = bindingStates[ geometry.id ];
  42904. for ( const programId in programMap ) {
  42905. const stateMap = programMap[ programId ];
  42906. for ( const wireframe in stateMap ) {
  42907. deleteVertexArrayObject( stateMap[ wireframe ].object );
  42908. delete stateMap[ wireframe ];
  42909. }
  42910. delete programMap[ programId ];
  42911. }
  42912. delete bindingStates[ geometry.id ];
  42913. }
  42914. function releaseStatesOfProgram( program ) {
  42915. for ( const geometryId in bindingStates ) {
  42916. const programMap = bindingStates[ geometryId ];
  42917. if ( programMap[ program.id ] === undefined ) continue;
  42918. const stateMap = programMap[ program.id ];
  42919. for ( const wireframe in stateMap ) {
  42920. deleteVertexArrayObject( stateMap[ wireframe ].object );
  42921. delete stateMap[ wireframe ];
  42922. }
  42923. delete programMap[ program.id ];
  42924. }
  42925. }
  42926. function reset() {
  42927. resetDefaultState();
  42928. forceUpdate = true;
  42929. if ( currentState === defaultState ) return;
  42930. currentState = defaultState;
  42931. bindVertexArrayObject( currentState.object );
  42932. }
  42933. // for backward-compatibility
  42934. function resetDefaultState() {
  42935. defaultState.geometry = null;
  42936. defaultState.program = null;
  42937. defaultState.wireframe = false;
  42938. }
  42939. return {
  42940. setup: setup,
  42941. reset: reset,
  42942. resetDefaultState: resetDefaultState,
  42943. dispose: dispose,
  42944. releaseStatesOfGeometry: releaseStatesOfGeometry,
  42945. releaseStatesOfProgram: releaseStatesOfProgram,
  42946. initAttributes: initAttributes,
  42947. enableAttribute: enableAttribute,
  42948. disableUnusedAttributes: disableUnusedAttributes
  42949. };
  42950. }
  42951. function WebGLBufferRenderer( gl, extensions, info ) {
  42952. let mode;
  42953. function setMode( value ) {
  42954. mode = value;
  42955. }
  42956. function render( start, count ) {
  42957. gl.drawArrays( mode, start, count );
  42958. info.update( count, mode, 1 );
  42959. }
  42960. function renderInstances( start, count, primcount ) {
  42961. if ( primcount === 0 ) return;
  42962. gl.drawArraysInstanced( mode, start, count, primcount );
  42963. info.update( count, mode, primcount );
  42964. }
  42965. function renderMultiDraw( starts, counts, drawCount ) {
  42966. if ( drawCount === 0 ) return;
  42967. const extension = extensions.get( 'WEBGL_multi_draw' );
  42968. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  42969. let elementCount = 0;
  42970. for ( let i = 0; i < drawCount; i ++ ) {
  42971. elementCount += counts[ i ];
  42972. }
  42973. info.update( elementCount, mode, 1 );
  42974. }
  42975. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  42976. if ( drawCount === 0 ) return;
  42977. const extension = extensions.get( 'WEBGL_multi_draw' );
  42978. if ( extension === null ) {
  42979. for ( let i = 0; i < starts.length; i ++ ) {
  42980. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  42981. }
  42982. } else {
  42983. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  42984. let elementCount = 0;
  42985. for ( let i = 0; i < drawCount; i ++ ) {
  42986. elementCount += counts[ i ] * primcount[ i ];
  42987. }
  42988. info.update( elementCount, mode, 1 );
  42989. }
  42990. }
  42991. //
  42992. this.setMode = setMode;
  42993. this.render = render;
  42994. this.renderInstances = renderInstances;
  42995. this.renderMultiDraw = renderMultiDraw;
  42996. this.renderMultiDrawInstances = renderMultiDrawInstances;
  42997. }
  42998. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  42999. let maxAnisotropy;
  43000. function getMaxAnisotropy() {
  43001. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  43002. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43003. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43004. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43005. } else {
  43006. maxAnisotropy = 0;
  43007. }
  43008. return maxAnisotropy;
  43009. }
  43010. function textureFormatReadable( textureFormat ) {
  43011. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  43012. return false;
  43013. }
  43014. return true;
  43015. }
  43016. function textureTypeReadable( textureType ) {
  43017. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  43018. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  43019. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  43020. return false;
  43021. }
  43022. return true;
  43023. }
  43024. function getMaxPrecision( precision ) {
  43025. if ( precision === 'highp' ) {
  43026. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  43027. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  43028. return 'highp';
  43029. }
  43030. precision = 'mediump';
  43031. }
  43032. if ( precision === 'mediump' ) {
  43033. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  43034. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  43035. return 'mediump';
  43036. }
  43037. }
  43038. return 'lowp';
  43039. }
  43040. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  43041. const maxPrecision = getMaxPrecision( precision );
  43042. if ( maxPrecision !== precision ) {
  43043. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  43044. precision = maxPrecision;
  43045. }
  43046. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  43047. const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  43048. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  43049. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  43050. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  43051. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  43052. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43053. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  43054. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  43055. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  43056. const vertexTextures = maxVertexTextures > 0;
  43057. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  43058. return {
  43059. isWebGL2: true, // keeping this for backwards compatibility
  43060. getMaxAnisotropy: getMaxAnisotropy,
  43061. getMaxPrecision: getMaxPrecision,
  43062. textureFormatReadable: textureFormatReadable,
  43063. textureTypeReadable: textureTypeReadable,
  43064. precision: precision,
  43065. logarithmicDepthBuffer: logarithmicDepthBuffer,
  43066. reverseDepthBuffer: reverseDepthBuffer,
  43067. maxTextures: maxTextures,
  43068. maxVertexTextures: maxVertexTextures,
  43069. maxTextureSize: maxTextureSize,
  43070. maxCubemapSize: maxCubemapSize,
  43071. maxAttributes: maxAttributes,
  43072. maxVertexUniforms: maxVertexUniforms,
  43073. maxVaryings: maxVaryings,
  43074. maxFragmentUniforms: maxFragmentUniforms,
  43075. vertexTextures: vertexTextures,
  43076. maxSamples: maxSamples
  43077. };
  43078. }
  43079. function WebGLClipping( properties ) {
  43080. const scope = this;
  43081. let globalState = null,
  43082. numGlobalPlanes = 0,
  43083. localClippingEnabled = false,
  43084. renderingShadows = false;
  43085. const plane = new Plane(),
  43086. viewNormalMatrix = new Matrix3(),
  43087. uniform = { value: null, needsUpdate: false };
  43088. this.uniform = uniform;
  43089. this.numPlanes = 0;
  43090. this.numIntersection = 0;
  43091. this.init = function ( planes, enableLocalClipping ) {
  43092. const enabled =
  43093. planes.length !== 0 ||
  43094. enableLocalClipping ||
  43095. // enable state of previous frame - the clipping code has to
  43096. // run another frame in order to reset the state:
  43097. numGlobalPlanes !== 0 ||
  43098. localClippingEnabled;
  43099. localClippingEnabled = enableLocalClipping;
  43100. numGlobalPlanes = planes.length;
  43101. return enabled;
  43102. };
  43103. this.beginShadows = function () {
  43104. renderingShadows = true;
  43105. projectPlanes( null );
  43106. };
  43107. this.endShadows = function () {
  43108. renderingShadows = false;
  43109. };
  43110. this.setGlobalState = function ( planes, camera ) {
  43111. globalState = projectPlanes( planes, camera, 0 );
  43112. };
  43113. this.setState = function ( material, camera, useCache ) {
  43114. const planes = material.clippingPlanes,
  43115. clipIntersection = material.clipIntersection,
  43116. clipShadows = material.clipShadows;
  43117. const materialProperties = properties.get( material );
  43118. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  43119. // there's no local clipping
  43120. if ( renderingShadows ) {
  43121. // there's no global clipping
  43122. projectPlanes( null );
  43123. } else {
  43124. resetGlobalState();
  43125. }
  43126. } else {
  43127. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  43128. lGlobal = nGlobal * 4;
  43129. let dstArray = materialProperties.clippingState || null;
  43130. uniform.value = dstArray; // ensure unique state
  43131. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  43132. for ( let i = 0; i !== lGlobal; ++ i ) {
  43133. dstArray[ i ] = globalState[ i ];
  43134. }
  43135. materialProperties.clippingState = dstArray;
  43136. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  43137. this.numPlanes += nGlobal;
  43138. }
  43139. };
  43140. function resetGlobalState() {
  43141. if ( uniform.value !== globalState ) {
  43142. uniform.value = globalState;
  43143. uniform.needsUpdate = numGlobalPlanes > 0;
  43144. }
  43145. scope.numPlanes = numGlobalPlanes;
  43146. scope.numIntersection = 0;
  43147. }
  43148. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  43149. const nPlanes = planes !== null ? planes.length : 0;
  43150. let dstArray = null;
  43151. if ( nPlanes !== 0 ) {
  43152. dstArray = uniform.value;
  43153. if ( skipTransform !== true || dstArray === null ) {
  43154. const flatSize = dstOffset + nPlanes * 4,
  43155. viewMatrix = camera.matrixWorldInverse;
  43156. viewNormalMatrix.getNormalMatrix( viewMatrix );
  43157. if ( dstArray === null || dstArray.length < flatSize ) {
  43158. dstArray = new Float32Array( flatSize );
  43159. }
  43160. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  43161. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  43162. plane.normal.toArray( dstArray, i4 );
  43163. dstArray[ i4 + 3 ] = plane.constant;
  43164. }
  43165. }
  43166. uniform.value = dstArray;
  43167. uniform.needsUpdate = true;
  43168. }
  43169. scope.numPlanes = nPlanes;
  43170. scope.numIntersection = 0;
  43171. return dstArray;
  43172. }
  43173. }
  43174. function WebGLCubeMaps( renderer ) {
  43175. let cubemaps = new WeakMap();
  43176. function mapTextureMapping( texture, mapping ) {
  43177. if ( mapping === EquirectangularReflectionMapping ) {
  43178. texture.mapping = CubeReflectionMapping;
  43179. } else if ( mapping === EquirectangularRefractionMapping ) {
  43180. texture.mapping = CubeRefractionMapping;
  43181. }
  43182. return texture;
  43183. }
  43184. function get( texture ) {
  43185. if ( texture && texture.isTexture ) {
  43186. const mapping = texture.mapping;
  43187. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  43188. if ( cubemaps.has( texture ) ) {
  43189. const cubemap = cubemaps.get( texture ).texture;
  43190. return mapTextureMapping( cubemap, texture.mapping );
  43191. } else {
  43192. const image = texture.image;
  43193. if ( image && image.height > 0 ) {
  43194. const renderTarget = new WebGLCubeRenderTarget( image.height );
  43195. renderTarget.fromEquirectangularTexture( renderer, texture );
  43196. cubemaps.set( texture, renderTarget );
  43197. texture.addEventListener( 'dispose', onTextureDispose );
  43198. return mapTextureMapping( renderTarget.texture, texture.mapping );
  43199. } else {
  43200. // image not yet ready. try the conversion next frame
  43201. return null;
  43202. }
  43203. }
  43204. }
  43205. }
  43206. return texture;
  43207. }
  43208. function onTextureDispose( event ) {
  43209. const texture = event.target;
  43210. texture.removeEventListener( 'dispose', onTextureDispose );
  43211. const cubemap = cubemaps.get( texture );
  43212. if ( cubemap !== undefined ) {
  43213. cubemaps.delete( texture );
  43214. cubemap.dispose();
  43215. }
  43216. }
  43217. function dispose() {
  43218. cubemaps = new WeakMap();
  43219. }
  43220. return {
  43221. get: get,
  43222. dispose: dispose
  43223. };
  43224. }
  43225. const LOD_MIN = 4;
  43226. // The standard deviations (radians) associated with the extra mips. These are
  43227. // chosen to approximate a Trowbridge-Reitz distribution function times the
  43228. // geometric shadowing function. These sigma values squared must match the
  43229. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  43230. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  43231. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  43232. // samples and exit early, but not recompile the shader.
  43233. const MAX_SAMPLES = 20;
  43234. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  43235. const _clearColor = /*@__PURE__*/ new Color();
  43236. let _oldTarget = null;
  43237. let _oldActiveCubeFace = 0;
  43238. let _oldActiveMipmapLevel = 0;
  43239. let _oldXrEnabled = false;
  43240. // Golden Ratio
  43241. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  43242. const INV_PHI = 1 / PHI;
  43243. // Vertices of a dodecahedron (except the opposites, which represent the
  43244. // same axis), used as axis directions evenly spread on a sphere.
  43245. const _axisDirections = [
  43246. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  43247. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  43248. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  43249. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  43250. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  43251. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  43252. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  43253. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  43254. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  43255. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  43256. const _origin = /*@__PURE__*/ new Vector3();
  43257. /**
  43258. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  43259. * (PMREM) from a cubeMap environment texture. This allows different levels of
  43260. * blur to be quickly accessed based on material roughness. It is packed into a
  43261. * special CubeUV format that allows us to perform custom interpolation so that
  43262. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  43263. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  43264. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  43265. * higher roughness levels. In this way we maintain resolution to smoothly
  43266. * interpolate diffuse lighting while limiting sampling computation.
  43267. *
  43268. * Paper: Fast, Accurate Image-Based Lighting:
  43269. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  43270. */
  43271. class PMREMGenerator {
  43272. /**
  43273. * Constructs a new PMREM generator.
  43274. *
  43275. * @param {WebGLRenderer} renderer - The renderer.
  43276. */
  43277. constructor( renderer ) {
  43278. this._renderer = renderer;
  43279. this._pingPongRenderTarget = null;
  43280. this._lodMax = 0;
  43281. this._cubeSize = 0;
  43282. this._lodPlanes = [];
  43283. this._sizeLods = [];
  43284. this._sigmas = [];
  43285. this._blurMaterial = null;
  43286. this._cubemapMaterial = null;
  43287. this._equirectMaterial = null;
  43288. this._compileMaterial( this._blurMaterial );
  43289. }
  43290. /**
  43291. * Generates a PMREM from a supplied Scene, which can be faster than using an
  43292. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  43293. * in radians to be applied to the scene before PMREM generation. Optional near
  43294. * and far planes ensure the scene is rendered in its entirety.
  43295. *
  43296. * @param {Scene} scene - The scene to be captured.
  43297. * @param {number} [sigma=0] - The blur radius in radians.
  43298. * @param {number} [near=0.1] - The near plane distance.
  43299. * @param {number} [far=100] - The far plane distance.
  43300. * @param {Object} [options={}] - The configuration options.
  43301. * @param {number} [options.size=256] - The texture size of the PMREM.
  43302. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  43303. * @return {WebGLRenderTarget} The resulting PMREM.
  43304. */
  43305. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  43306. const {
  43307. size = 256,
  43308. position = _origin,
  43309. } = options;
  43310. _oldTarget = this._renderer.getRenderTarget();
  43311. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  43312. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  43313. _oldXrEnabled = this._renderer.xr.enabled;
  43314. this._renderer.xr.enabled = false;
  43315. this._setSize( size );
  43316. const cubeUVRenderTarget = this._allocateTargets();
  43317. cubeUVRenderTarget.depthBuffer = true;
  43318. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  43319. if ( sigma > 0 ) {
  43320. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  43321. }
  43322. this._applyPMREM( cubeUVRenderTarget );
  43323. this._cleanup( cubeUVRenderTarget );
  43324. return cubeUVRenderTarget;
  43325. }
  43326. /**
  43327. * Generates a PMREM from an equirectangular texture, which can be either LDR
  43328. * or HDR. The ideal input image size is 1k (1024 x 512),
  43329. * as this matches best with the 256 x 256 cubemap output.
  43330. *
  43331. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  43332. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  43333. * @return {WebGLRenderTarget} The resulting PMREM.
  43334. */
  43335. fromEquirectangular( equirectangular, renderTarget = null ) {
  43336. return this._fromTexture( equirectangular, renderTarget );
  43337. }
  43338. /**
  43339. * Generates a PMREM from an cubemap texture, which can be either LDR
  43340. * or HDR. The ideal input cube size is 256 x 256,
  43341. * as this matches best with the 256 x 256 cubemap output.
  43342. *
  43343. * @param {Texture} cubemap - The cubemap texture to be converted.
  43344. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  43345. * @return {WebGLRenderTarget} The resulting PMREM.
  43346. */
  43347. fromCubemap( cubemap, renderTarget = null ) {
  43348. return this._fromTexture( cubemap, renderTarget );
  43349. }
  43350. /**
  43351. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  43352. * your texture's network fetch for increased concurrency.
  43353. */
  43354. compileCubemapShader() {
  43355. if ( this._cubemapMaterial === null ) {
  43356. this._cubemapMaterial = _getCubemapMaterial();
  43357. this._compileMaterial( this._cubemapMaterial );
  43358. }
  43359. }
  43360. /**
  43361. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  43362. * your texture's network fetch for increased concurrency.
  43363. */
  43364. compileEquirectangularShader() {
  43365. if ( this._equirectMaterial === null ) {
  43366. this._equirectMaterial = _getEquirectMaterial();
  43367. this._compileMaterial( this._equirectMaterial );
  43368. }
  43369. }
  43370. /**
  43371. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  43372. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  43373. * one of them will cause any others to also become unusable.
  43374. */
  43375. dispose() {
  43376. this._dispose();
  43377. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  43378. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  43379. }
  43380. // private interface
  43381. _setSize( cubeSize ) {
  43382. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  43383. this._cubeSize = Math.pow( 2, this._lodMax );
  43384. }
  43385. _dispose() {
  43386. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  43387. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  43388. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  43389. this._lodPlanes[ i ].dispose();
  43390. }
  43391. }
  43392. _cleanup( outputTarget ) {
  43393. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  43394. this._renderer.xr.enabled = _oldXrEnabled;
  43395. outputTarget.scissorTest = false;
  43396. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  43397. }
  43398. _fromTexture( texture, renderTarget ) {
  43399. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  43400. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  43401. } else { // Equirectangular
  43402. this._setSize( texture.image.width / 4 );
  43403. }
  43404. _oldTarget = this._renderer.getRenderTarget();
  43405. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  43406. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  43407. _oldXrEnabled = this._renderer.xr.enabled;
  43408. this._renderer.xr.enabled = false;
  43409. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  43410. this._textureToCubeUV( texture, cubeUVRenderTarget );
  43411. this._applyPMREM( cubeUVRenderTarget );
  43412. this._cleanup( cubeUVRenderTarget );
  43413. return cubeUVRenderTarget;
  43414. }
  43415. _allocateTargets() {
  43416. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  43417. const height = 4 * this._cubeSize;
  43418. const params = {
  43419. magFilter: LinearFilter,
  43420. minFilter: LinearFilter,
  43421. generateMipmaps: false,
  43422. type: HalfFloatType,
  43423. format: RGBAFormat,
  43424. colorSpace: LinearSRGBColorSpace,
  43425. depthBuffer: false
  43426. };
  43427. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  43428. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  43429. if ( this._pingPongRenderTarget !== null ) {
  43430. this._dispose();
  43431. }
  43432. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  43433. const { _lodMax } = this;
  43434. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  43435. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  43436. }
  43437. return cubeUVRenderTarget;
  43438. }
  43439. _compileMaterial( material ) {
  43440. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  43441. this._renderer.compile( tmpMesh, _flatCamera );
  43442. }
  43443. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  43444. const fov = 90;
  43445. const aspect = 1;
  43446. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  43447. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  43448. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  43449. const renderer = this._renderer;
  43450. const originalAutoClear = renderer.autoClear;
  43451. const toneMapping = renderer.toneMapping;
  43452. renderer.getClearColor( _clearColor );
  43453. renderer.toneMapping = NoToneMapping;
  43454. renderer.autoClear = false;
  43455. const backgroundMaterial = new MeshBasicMaterial( {
  43456. name: 'PMREM.Background',
  43457. side: BackSide,
  43458. depthWrite: false,
  43459. depthTest: false,
  43460. } );
  43461. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  43462. let useSolidColor = false;
  43463. const background = scene.background;
  43464. if ( background ) {
  43465. if ( background.isColor ) {
  43466. backgroundMaterial.color.copy( background );
  43467. scene.background = null;
  43468. useSolidColor = true;
  43469. }
  43470. } else {
  43471. backgroundMaterial.color.copy( _clearColor );
  43472. useSolidColor = true;
  43473. }
  43474. for ( let i = 0; i < 6; i ++ ) {
  43475. const col = i % 3;
  43476. if ( col === 0 ) {
  43477. cubeCamera.up.set( 0, upSign[ i ], 0 );
  43478. cubeCamera.position.set( position.x, position.y, position.z );
  43479. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  43480. } else if ( col === 1 ) {
  43481. cubeCamera.up.set( 0, 0, upSign[ i ] );
  43482. cubeCamera.position.set( position.x, position.y, position.z );
  43483. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  43484. } else {
  43485. cubeCamera.up.set( 0, upSign[ i ], 0 );
  43486. cubeCamera.position.set( position.x, position.y, position.z );
  43487. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  43488. }
  43489. const size = this._cubeSize;
  43490. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  43491. renderer.setRenderTarget( cubeUVRenderTarget );
  43492. if ( useSolidColor ) {
  43493. renderer.render( backgroundBox, cubeCamera );
  43494. }
  43495. renderer.render( scene, cubeCamera );
  43496. }
  43497. backgroundBox.geometry.dispose();
  43498. backgroundBox.material.dispose();
  43499. renderer.toneMapping = toneMapping;
  43500. renderer.autoClear = originalAutoClear;
  43501. scene.background = background;
  43502. }
  43503. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  43504. const renderer = this._renderer;
  43505. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  43506. if ( isCubeTexture ) {
  43507. if ( this._cubemapMaterial === null ) {
  43508. this._cubemapMaterial = _getCubemapMaterial();
  43509. }
  43510. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  43511. } else {
  43512. if ( this._equirectMaterial === null ) {
  43513. this._equirectMaterial = _getEquirectMaterial();
  43514. }
  43515. }
  43516. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  43517. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  43518. const uniforms = material.uniforms;
  43519. uniforms[ 'envMap' ].value = texture;
  43520. const size = this._cubeSize;
  43521. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  43522. renderer.setRenderTarget( cubeUVRenderTarget );
  43523. renderer.render( mesh, _flatCamera );
  43524. }
  43525. _applyPMREM( cubeUVRenderTarget ) {
  43526. const renderer = this._renderer;
  43527. const autoClear = renderer.autoClear;
  43528. renderer.autoClear = false;
  43529. const n = this._lodPlanes.length;
  43530. for ( let i = 1; i < n; i ++ ) {
  43531. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  43532. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  43533. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  43534. }
  43535. renderer.autoClear = autoClear;
  43536. }
  43537. /**
  43538. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  43539. * vertically and horizontally, but this breaks down on a cube. Here we apply
  43540. * the blur latitudinally (around the poles), and then longitudinally (towards
  43541. * the poles) to approximate the orthogonally-separable blur. It is least
  43542. * accurate at the poles, but still does a decent job.
  43543. *
  43544. * @private
  43545. * @param {WebGLRenderTarget} cubeUVRenderTarget
  43546. * @param {number} lodIn
  43547. * @param {number} lodOut
  43548. * @param {number} sigma
  43549. * @param {Vector3} [poleAxis]
  43550. */
  43551. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  43552. const pingPongRenderTarget = this._pingPongRenderTarget;
  43553. this._halfBlur(
  43554. cubeUVRenderTarget,
  43555. pingPongRenderTarget,
  43556. lodIn,
  43557. lodOut,
  43558. sigma,
  43559. 'latitudinal',
  43560. poleAxis );
  43561. this._halfBlur(
  43562. pingPongRenderTarget,
  43563. cubeUVRenderTarget,
  43564. lodOut,
  43565. lodOut,
  43566. sigma,
  43567. 'longitudinal',
  43568. poleAxis );
  43569. }
  43570. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  43571. const renderer = this._renderer;
  43572. const blurMaterial = this._blurMaterial;
  43573. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  43574. console.error(
  43575. 'blur direction must be either latitudinal or longitudinal!' );
  43576. }
  43577. // Number of standard deviations at which to cut off the discrete approximation.
  43578. const STANDARD_DEVIATIONS = 3;
  43579. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  43580. const blurUniforms = blurMaterial.uniforms;
  43581. const pixels = this._sizeLods[ lodIn ] - 1;
  43582. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  43583. const sigmaPixels = sigmaRadians / radiansPerPixel;
  43584. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  43585. if ( samples > MAX_SAMPLES ) {
  43586. console.warn( `sigmaRadians, ${
  43587. sigmaRadians}, is too large and will clip, as it requested ${
  43588. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  43589. }
  43590. const weights = [];
  43591. let sum = 0;
  43592. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  43593. const x = i / sigmaPixels;
  43594. const weight = Math.exp( - x * x / 2 );
  43595. weights.push( weight );
  43596. if ( i === 0 ) {
  43597. sum += weight;
  43598. } else if ( i < samples ) {
  43599. sum += 2 * weight;
  43600. }
  43601. }
  43602. for ( let i = 0; i < weights.length; i ++ ) {
  43603. weights[ i ] = weights[ i ] / sum;
  43604. }
  43605. blurUniforms[ 'envMap' ].value = targetIn.texture;
  43606. blurUniforms[ 'samples' ].value = samples;
  43607. blurUniforms[ 'weights' ].value = weights;
  43608. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  43609. if ( poleAxis ) {
  43610. blurUniforms[ 'poleAxis' ].value = poleAxis;
  43611. }
  43612. const { _lodMax } = this;
  43613. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  43614. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  43615. const outputSize = this._sizeLods[ lodOut ];
  43616. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  43617. const y = 4 * ( this._cubeSize - outputSize );
  43618. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  43619. renderer.setRenderTarget( targetOut );
  43620. renderer.render( blurMesh, _flatCamera );
  43621. }
  43622. }
  43623. function _createPlanes( lodMax ) {
  43624. const lodPlanes = [];
  43625. const sizeLods = [];
  43626. const sigmas = [];
  43627. let lod = lodMax;
  43628. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  43629. for ( let i = 0; i < totalLods; i ++ ) {
  43630. const sizeLod = Math.pow( 2, lod );
  43631. sizeLods.push( sizeLod );
  43632. let sigma = 1.0 / sizeLod;
  43633. if ( i > lodMax - LOD_MIN ) {
  43634. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  43635. } else if ( i === 0 ) {
  43636. sigma = 0;
  43637. }
  43638. sigmas.push( sigma );
  43639. const texelSize = 1.0 / ( sizeLod - 2 );
  43640. const min = - texelSize;
  43641. const max = 1 + texelSize;
  43642. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  43643. const cubeFaces = 6;
  43644. const vertices = 6;
  43645. const positionSize = 3;
  43646. const uvSize = 2;
  43647. const faceIndexSize = 1;
  43648. const position = new Float32Array( positionSize * vertices * cubeFaces );
  43649. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  43650. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  43651. for ( let face = 0; face < cubeFaces; face ++ ) {
  43652. const x = ( face % 3 ) * 2 / 3 - 1;
  43653. const y = face > 2 ? 0 : - 1;
  43654. const coordinates = [
  43655. x, y, 0,
  43656. x + 2 / 3, y, 0,
  43657. x + 2 / 3, y + 1, 0,
  43658. x, y, 0,
  43659. x + 2 / 3, y + 1, 0,
  43660. x, y + 1, 0
  43661. ];
  43662. position.set( coordinates, positionSize * vertices * face );
  43663. uv.set( uv1, uvSize * vertices * face );
  43664. const fill = [ face, face, face, face, face, face ];
  43665. faceIndex.set( fill, faceIndexSize * vertices * face );
  43666. }
  43667. const planes = new BufferGeometry();
  43668. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  43669. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  43670. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  43671. lodPlanes.push( planes );
  43672. if ( lod > LOD_MIN ) {
  43673. lod --;
  43674. }
  43675. }
  43676. return { lodPlanes, sizeLods, sigmas };
  43677. }
  43678. function _createRenderTarget( width, height, params ) {
  43679. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  43680. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  43681. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  43682. cubeUVRenderTarget.scissorTest = true;
  43683. return cubeUVRenderTarget;
  43684. }
  43685. function _setViewport( target, x, y, width, height ) {
  43686. target.viewport.set( x, y, width, height );
  43687. target.scissor.set( x, y, width, height );
  43688. }
  43689. function _getBlurShader( lodMax, width, height ) {
  43690. const weights = new Float32Array( MAX_SAMPLES );
  43691. const poleAxis = new Vector3( 0, 1, 0 );
  43692. const shaderMaterial = new ShaderMaterial( {
  43693. name: 'SphericalGaussianBlur',
  43694. defines: {
  43695. 'n': MAX_SAMPLES,
  43696. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  43697. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  43698. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  43699. },
  43700. uniforms: {
  43701. 'envMap': { value: null },
  43702. 'samples': { value: 1 },
  43703. 'weights': { value: weights },
  43704. 'latitudinal': { value: false },
  43705. 'dTheta': { value: 0 },
  43706. 'mipInt': { value: 0 },
  43707. 'poleAxis': { value: poleAxis }
  43708. },
  43709. vertexShader: _getCommonVertexShader(),
  43710. fragmentShader: /* glsl */`
  43711. precision mediump float;
  43712. precision mediump int;
  43713. varying vec3 vOutputDirection;
  43714. uniform sampler2D envMap;
  43715. uniform int samples;
  43716. uniform float weights[ n ];
  43717. uniform bool latitudinal;
  43718. uniform float dTheta;
  43719. uniform float mipInt;
  43720. uniform vec3 poleAxis;
  43721. #define ENVMAP_TYPE_CUBE_UV
  43722. #include <cube_uv_reflection_fragment>
  43723. vec3 getSample( float theta, vec3 axis ) {
  43724. float cosTheta = cos( theta );
  43725. // Rodrigues' axis-angle rotation
  43726. vec3 sampleDirection = vOutputDirection * cosTheta
  43727. + cross( axis, vOutputDirection ) * sin( theta )
  43728. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  43729. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  43730. }
  43731. void main() {
  43732. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  43733. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  43734. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  43735. }
  43736. axis = normalize( axis );
  43737. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  43738. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  43739. for ( int i = 1; i < n; i++ ) {
  43740. if ( i >= samples ) {
  43741. break;
  43742. }
  43743. float theta = dTheta * float( i );
  43744. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  43745. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  43746. }
  43747. }
  43748. `,
  43749. blending: NoBlending,
  43750. depthTest: false,
  43751. depthWrite: false
  43752. } );
  43753. return shaderMaterial;
  43754. }
  43755. function _getEquirectMaterial() {
  43756. return new ShaderMaterial( {
  43757. name: 'EquirectangularToCubeUV',
  43758. uniforms: {
  43759. 'envMap': { value: null }
  43760. },
  43761. vertexShader: _getCommonVertexShader(),
  43762. fragmentShader: /* glsl */`
  43763. precision mediump float;
  43764. precision mediump int;
  43765. varying vec3 vOutputDirection;
  43766. uniform sampler2D envMap;
  43767. #include <common>
  43768. void main() {
  43769. vec3 outputDirection = normalize( vOutputDirection );
  43770. vec2 uv = equirectUv( outputDirection );
  43771. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  43772. }
  43773. `,
  43774. blending: NoBlending,
  43775. depthTest: false,
  43776. depthWrite: false
  43777. } );
  43778. }
  43779. function _getCubemapMaterial() {
  43780. return new ShaderMaterial( {
  43781. name: 'CubemapToCubeUV',
  43782. uniforms: {
  43783. 'envMap': { value: null },
  43784. 'flipEnvMap': { value: - 1 }
  43785. },
  43786. vertexShader: _getCommonVertexShader(),
  43787. fragmentShader: /* glsl */`
  43788. precision mediump float;
  43789. precision mediump int;
  43790. uniform float flipEnvMap;
  43791. varying vec3 vOutputDirection;
  43792. uniform samplerCube envMap;
  43793. void main() {
  43794. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  43795. }
  43796. `,
  43797. blending: NoBlending,
  43798. depthTest: false,
  43799. depthWrite: false
  43800. } );
  43801. }
  43802. function _getCommonVertexShader() {
  43803. return /* glsl */`
  43804. precision mediump float;
  43805. precision mediump int;
  43806. attribute float faceIndex;
  43807. varying vec3 vOutputDirection;
  43808. // RH coordinate system; PMREM face-indexing convention
  43809. vec3 getDirection( vec2 uv, float face ) {
  43810. uv = 2.0 * uv - 1.0;
  43811. vec3 direction = vec3( uv, 1.0 );
  43812. if ( face == 0.0 ) {
  43813. direction = direction.zyx; // ( 1, v, u ) pos x
  43814. } else if ( face == 1.0 ) {
  43815. direction = direction.xzy;
  43816. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  43817. } else if ( face == 2.0 ) {
  43818. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  43819. } else if ( face == 3.0 ) {
  43820. direction = direction.zyx;
  43821. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  43822. } else if ( face == 4.0 ) {
  43823. direction = direction.xzy;
  43824. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  43825. } else if ( face == 5.0 ) {
  43826. direction.z *= -1.0; // ( u, v, -1 ) neg z
  43827. }
  43828. return direction;
  43829. }
  43830. void main() {
  43831. vOutputDirection = getDirection( uv, faceIndex );
  43832. gl_Position = vec4( position, 1.0 );
  43833. }
  43834. `;
  43835. }
  43836. function WebGLCubeUVMaps( renderer ) {
  43837. let cubeUVmaps = new WeakMap();
  43838. let pmremGenerator = null;
  43839. function get( texture ) {
  43840. if ( texture && texture.isTexture ) {
  43841. const mapping = texture.mapping;
  43842. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  43843. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  43844. // equirect/cube map to cubeUV conversion
  43845. if ( isEquirectMap || isCubeMap ) {
  43846. let renderTarget = cubeUVmaps.get( texture );
  43847. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  43848. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  43849. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  43850. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  43851. renderTarget.texture.pmremVersion = texture.pmremVersion;
  43852. cubeUVmaps.set( texture, renderTarget );
  43853. return renderTarget.texture;
  43854. } else {
  43855. if ( renderTarget !== undefined ) {
  43856. return renderTarget.texture;
  43857. } else {
  43858. const image = texture.image;
  43859. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  43860. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  43861. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  43862. renderTarget.texture.pmremVersion = texture.pmremVersion;
  43863. cubeUVmaps.set( texture, renderTarget );
  43864. texture.addEventListener( 'dispose', onTextureDispose );
  43865. return renderTarget.texture;
  43866. } else {
  43867. // image not yet ready. try the conversion next frame
  43868. return null;
  43869. }
  43870. }
  43871. }
  43872. }
  43873. }
  43874. return texture;
  43875. }
  43876. function isCubeTextureComplete( image ) {
  43877. let count = 0;
  43878. const length = 6;
  43879. for ( let i = 0; i < length; i ++ ) {
  43880. if ( image[ i ] !== undefined ) count ++;
  43881. }
  43882. return count === length;
  43883. }
  43884. function onTextureDispose( event ) {
  43885. const texture = event.target;
  43886. texture.removeEventListener( 'dispose', onTextureDispose );
  43887. const cubemapUV = cubeUVmaps.get( texture );
  43888. if ( cubemapUV !== undefined ) {
  43889. cubeUVmaps.delete( texture );
  43890. cubemapUV.dispose();
  43891. }
  43892. }
  43893. function dispose() {
  43894. cubeUVmaps = new WeakMap();
  43895. if ( pmremGenerator !== null ) {
  43896. pmremGenerator.dispose();
  43897. pmremGenerator = null;
  43898. }
  43899. }
  43900. return {
  43901. get: get,
  43902. dispose: dispose
  43903. };
  43904. }
  43905. function WebGLExtensions( gl ) {
  43906. const extensions = {};
  43907. function getExtension( name ) {
  43908. if ( extensions[ name ] !== undefined ) {
  43909. return extensions[ name ];
  43910. }
  43911. let extension;
  43912. switch ( name ) {
  43913. case 'WEBGL_depth_texture':
  43914. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  43915. break;
  43916. case 'EXT_texture_filter_anisotropic':
  43917. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  43918. break;
  43919. case 'WEBGL_compressed_texture_s3tc':
  43920. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  43921. break;
  43922. case 'WEBGL_compressed_texture_pvrtc':
  43923. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  43924. break;
  43925. default:
  43926. extension = gl.getExtension( name );
  43927. }
  43928. extensions[ name ] = extension;
  43929. return extension;
  43930. }
  43931. return {
  43932. has: function ( name ) {
  43933. return getExtension( name ) !== null;
  43934. },
  43935. init: function () {
  43936. getExtension( 'EXT_color_buffer_float' );
  43937. getExtension( 'WEBGL_clip_cull_distance' );
  43938. getExtension( 'OES_texture_float_linear' );
  43939. getExtension( 'EXT_color_buffer_half_float' );
  43940. getExtension( 'WEBGL_multisampled_render_to_texture' );
  43941. getExtension( 'WEBGL_render_shared_exponent' );
  43942. },
  43943. get: function ( name ) {
  43944. const extension = getExtension( name );
  43945. if ( extension === null ) {
  43946. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  43947. }
  43948. return extension;
  43949. }
  43950. };
  43951. }
  43952. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  43953. const geometries = {};
  43954. const wireframeAttributes = new WeakMap();
  43955. function onGeometryDispose( event ) {
  43956. const geometry = event.target;
  43957. if ( geometry.index !== null ) {
  43958. attributes.remove( geometry.index );
  43959. }
  43960. for ( const name in geometry.attributes ) {
  43961. attributes.remove( geometry.attributes[ name ] );
  43962. }
  43963. geometry.removeEventListener( 'dispose', onGeometryDispose );
  43964. delete geometries[ geometry.id ];
  43965. const attribute = wireframeAttributes.get( geometry );
  43966. if ( attribute ) {
  43967. attributes.remove( attribute );
  43968. wireframeAttributes.delete( geometry );
  43969. }
  43970. bindingStates.releaseStatesOfGeometry( geometry );
  43971. if ( geometry.isInstancedBufferGeometry === true ) {
  43972. delete geometry._maxInstanceCount;
  43973. }
  43974. //
  43975. info.memory.geometries --;
  43976. }
  43977. function get( object, geometry ) {
  43978. if ( geometries[ geometry.id ] === true ) return geometry;
  43979. geometry.addEventListener( 'dispose', onGeometryDispose );
  43980. geometries[ geometry.id ] = true;
  43981. info.memory.geometries ++;
  43982. return geometry;
  43983. }
  43984. function update( geometry ) {
  43985. const geometryAttributes = geometry.attributes;
  43986. // Updating index buffer in VAO now. See WebGLBindingStates.
  43987. for ( const name in geometryAttributes ) {
  43988. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  43989. }
  43990. }
  43991. function updateWireframeAttribute( geometry ) {
  43992. const indices = [];
  43993. const geometryIndex = geometry.index;
  43994. const geometryPosition = geometry.attributes.position;
  43995. let version = 0;
  43996. if ( geometryIndex !== null ) {
  43997. const array = geometryIndex.array;
  43998. version = geometryIndex.version;
  43999. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  44000. const a = array[ i + 0 ];
  44001. const b = array[ i + 1 ];
  44002. const c = array[ i + 2 ];
  44003. indices.push( a, b, b, c, c, a );
  44004. }
  44005. } else if ( geometryPosition !== undefined ) {
  44006. const array = geometryPosition.array;
  44007. version = geometryPosition.version;
  44008. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  44009. const a = i + 0;
  44010. const b = i + 1;
  44011. const c = i + 2;
  44012. indices.push( a, b, b, c, c, a );
  44013. }
  44014. } else {
  44015. return;
  44016. }
  44017. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  44018. attribute.version = version;
  44019. // Updating index buffer in VAO now. See WebGLBindingStates
  44020. //
  44021. const previousAttribute = wireframeAttributes.get( geometry );
  44022. if ( previousAttribute ) attributes.remove( previousAttribute );
  44023. //
  44024. wireframeAttributes.set( geometry, attribute );
  44025. }
  44026. function getWireframeAttribute( geometry ) {
  44027. const currentAttribute = wireframeAttributes.get( geometry );
  44028. if ( currentAttribute ) {
  44029. const geometryIndex = geometry.index;
  44030. if ( geometryIndex !== null ) {
  44031. // if the attribute is obsolete, create a new one
  44032. if ( currentAttribute.version < geometryIndex.version ) {
  44033. updateWireframeAttribute( geometry );
  44034. }
  44035. }
  44036. } else {
  44037. updateWireframeAttribute( geometry );
  44038. }
  44039. return wireframeAttributes.get( geometry );
  44040. }
  44041. return {
  44042. get: get,
  44043. update: update,
  44044. getWireframeAttribute: getWireframeAttribute
  44045. };
  44046. }
  44047. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  44048. let mode;
  44049. function setMode( value ) {
  44050. mode = value;
  44051. }
  44052. let type, bytesPerElement;
  44053. function setIndex( value ) {
  44054. type = value.type;
  44055. bytesPerElement = value.bytesPerElement;
  44056. }
  44057. function render( start, count ) {
  44058. gl.drawElements( mode, count, type, start * bytesPerElement );
  44059. info.update( count, mode, 1 );
  44060. }
  44061. function renderInstances( start, count, primcount ) {
  44062. if ( primcount === 0 ) return;
  44063. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  44064. info.update( count, mode, primcount );
  44065. }
  44066. function renderMultiDraw( starts, counts, drawCount ) {
  44067. if ( drawCount === 0 ) return;
  44068. const extension = extensions.get( 'WEBGL_multi_draw' );
  44069. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  44070. let elementCount = 0;
  44071. for ( let i = 0; i < drawCount; i ++ ) {
  44072. elementCount += counts[ i ];
  44073. }
  44074. info.update( elementCount, mode, 1 );
  44075. }
  44076. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44077. if ( drawCount === 0 ) return;
  44078. const extension = extensions.get( 'WEBGL_multi_draw' );
  44079. if ( extension === null ) {
  44080. for ( let i = 0; i < starts.length; i ++ ) {
  44081. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  44082. }
  44083. } else {
  44084. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  44085. let elementCount = 0;
  44086. for ( let i = 0; i < drawCount; i ++ ) {
  44087. elementCount += counts[ i ] * primcount[ i ];
  44088. }
  44089. info.update( elementCount, mode, 1 );
  44090. }
  44091. }
  44092. //
  44093. this.setMode = setMode;
  44094. this.setIndex = setIndex;
  44095. this.render = render;
  44096. this.renderInstances = renderInstances;
  44097. this.renderMultiDraw = renderMultiDraw;
  44098. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44099. }
  44100. function WebGLInfo( gl ) {
  44101. const memory = {
  44102. geometries: 0,
  44103. textures: 0
  44104. };
  44105. const render = {
  44106. frame: 0,
  44107. calls: 0,
  44108. triangles: 0,
  44109. points: 0,
  44110. lines: 0
  44111. };
  44112. function update( count, mode, instanceCount ) {
  44113. render.calls ++;
  44114. switch ( mode ) {
  44115. case gl.TRIANGLES:
  44116. render.triangles += instanceCount * ( count / 3 );
  44117. break;
  44118. case gl.LINES:
  44119. render.lines += instanceCount * ( count / 2 );
  44120. break;
  44121. case gl.LINE_STRIP:
  44122. render.lines += instanceCount * ( count - 1 );
  44123. break;
  44124. case gl.LINE_LOOP:
  44125. render.lines += instanceCount * count;
  44126. break;
  44127. case gl.POINTS:
  44128. render.points += instanceCount * count;
  44129. break;
  44130. default:
  44131. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  44132. break;
  44133. }
  44134. }
  44135. function reset() {
  44136. render.calls = 0;
  44137. render.triangles = 0;
  44138. render.points = 0;
  44139. render.lines = 0;
  44140. }
  44141. return {
  44142. memory: memory,
  44143. render: render,
  44144. programs: null,
  44145. autoReset: true,
  44146. reset: reset,
  44147. update: update
  44148. };
  44149. }
  44150. function WebGLMorphtargets( gl, capabilities, textures ) {
  44151. const morphTextures = new WeakMap();
  44152. const morph = new Vector4();
  44153. function update( object, geometry, program ) {
  44154. const objectInfluences = object.morphTargetInfluences;
  44155. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  44156. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  44157. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  44158. let entry = morphTextures.get( geometry );
  44159. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  44160. if ( entry !== undefined ) entry.texture.dispose();
  44161. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  44162. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  44163. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  44164. const morphTargets = geometry.morphAttributes.position || [];
  44165. const morphNormals = geometry.morphAttributes.normal || [];
  44166. const morphColors = geometry.morphAttributes.color || [];
  44167. let vertexDataCount = 0;
  44168. if ( hasMorphPosition === true ) vertexDataCount = 1;
  44169. if ( hasMorphNormals === true ) vertexDataCount = 2;
  44170. if ( hasMorphColors === true ) vertexDataCount = 3;
  44171. let width = geometry.attributes.position.count * vertexDataCount;
  44172. let height = 1;
  44173. if ( width > capabilities.maxTextureSize ) {
  44174. height = Math.ceil( width / capabilities.maxTextureSize );
  44175. width = capabilities.maxTextureSize;
  44176. }
  44177. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  44178. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  44179. texture.type = FloatType;
  44180. texture.needsUpdate = true;
  44181. // fill buffer
  44182. const vertexDataStride = vertexDataCount * 4;
  44183. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  44184. const morphTarget = morphTargets[ i ];
  44185. const morphNormal = morphNormals[ i ];
  44186. const morphColor = morphColors[ i ];
  44187. const offset = width * height * 4 * i;
  44188. for ( let j = 0; j < morphTarget.count; j ++ ) {
  44189. const stride = j * vertexDataStride;
  44190. if ( hasMorphPosition === true ) {
  44191. morph.fromBufferAttribute( morphTarget, j );
  44192. buffer[ offset + stride + 0 ] = morph.x;
  44193. buffer[ offset + stride + 1 ] = morph.y;
  44194. buffer[ offset + stride + 2 ] = morph.z;
  44195. buffer[ offset + stride + 3 ] = 0;
  44196. }
  44197. if ( hasMorphNormals === true ) {
  44198. morph.fromBufferAttribute( morphNormal, j );
  44199. buffer[ offset + stride + 4 ] = morph.x;
  44200. buffer[ offset + stride + 5 ] = morph.y;
  44201. buffer[ offset + stride + 6 ] = morph.z;
  44202. buffer[ offset + stride + 7 ] = 0;
  44203. }
  44204. if ( hasMorphColors === true ) {
  44205. morph.fromBufferAttribute( morphColor, j );
  44206. buffer[ offset + stride + 8 ] = morph.x;
  44207. buffer[ offset + stride + 9 ] = morph.y;
  44208. buffer[ offset + stride + 10 ] = morph.z;
  44209. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  44210. }
  44211. }
  44212. }
  44213. entry = {
  44214. count: morphTargetsCount,
  44215. texture: texture,
  44216. size: new Vector2( width, height )
  44217. };
  44218. morphTextures.set( geometry, entry );
  44219. function disposeTexture() {
  44220. texture.dispose();
  44221. morphTextures.delete( geometry );
  44222. geometry.removeEventListener( 'dispose', disposeTexture );
  44223. }
  44224. geometry.addEventListener( 'dispose', disposeTexture );
  44225. }
  44226. //
  44227. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  44228. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  44229. } else {
  44230. let morphInfluencesSum = 0;
  44231. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  44232. morphInfluencesSum += objectInfluences[ i ];
  44233. }
  44234. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  44235. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  44236. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  44237. }
  44238. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  44239. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  44240. }
  44241. return {
  44242. update: update
  44243. };
  44244. }
  44245. function WebGLObjects( gl, geometries, attributes, info ) {
  44246. let updateMap = new WeakMap();
  44247. function update( object ) {
  44248. const frame = info.render.frame;
  44249. const geometry = object.geometry;
  44250. const buffergeometry = geometries.get( object, geometry );
  44251. // Update once per frame
  44252. if ( updateMap.get( buffergeometry ) !== frame ) {
  44253. geometries.update( buffergeometry );
  44254. updateMap.set( buffergeometry, frame );
  44255. }
  44256. if ( object.isInstancedMesh ) {
  44257. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  44258. object.addEventListener( 'dispose', onInstancedMeshDispose );
  44259. }
  44260. if ( updateMap.get( object ) !== frame ) {
  44261. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  44262. if ( object.instanceColor !== null ) {
  44263. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  44264. }
  44265. updateMap.set( object, frame );
  44266. }
  44267. }
  44268. if ( object.isSkinnedMesh ) {
  44269. const skeleton = object.skeleton;
  44270. if ( updateMap.get( skeleton ) !== frame ) {
  44271. skeleton.update();
  44272. updateMap.set( skeleton, frame );
  44273. }
  44274. }
  44275. return buffergeometry;
  44276. }
  44277. function dispose() {
  44278. updateMap = new WeakMap();
  44279. }
  44280. function onInstancedMeshDispose( event ) {
  44281. const instancedMesh = event.target;
  44282. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  44283. attributes.remove( instancedMesh.instanceMatrix );
  44284. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  44285. }
  44286. return {
  44287. update: update,
  44288. dispose: dispose
  44289. };
  44290. }
  44291. /**
  44292. * Uniforms of a program.
  44293. * Those form a tree structure with a special top-level container for the root,
  44294. * which you get by calling 'new WebGLUniforms( gl, program )'.
  44295. *
  44296. *
  44297. * Properties of inner nodes including the top-level container:
  44298. *
  44299. * .seq - array of nested uniforms
  44300. * .map - nested uniforms by name
  44301. *
  44302. *
  44303. * Methods of all nodes except the top-level container:
  44304. *
  44305. * .setValue( gl, value, [textures] )
  44306. *
  44307. * uploads a uniform value(s)
  44308. * the 'textures' parameter is needed for sampler uniforms
  44309. *
  44310. *
  44311. * Static methods of the top-level container (textures factorizations):
  44312. *
  44313. * .upload( gl, seq, values, textures )
  44314. *
  44315. * sets uniforms in 'seq' to 'values[id].value'
  44316. *
  44317. * .seqWithValue( seq, values ) : filteredSeq
  44318. *
  44319. * filters 'seq' entries with corresponding entry in values
  44320. *
  44321. *
  44322. * Methods of the top-level container (textures factorizations):
  44323. *
  44324. * .setValue( gl, name, value, textures )
  44325. *
  44326. * sets uniform with name 'name' to 'value'
  44327. *
  44328. * .setOptional( gl, obj, prop )
  44329. *
  44330. * like .set for an optional property of the object
  44331. *
  44332. */
  44333. const emptyTexture = /*@__PURE__*/ new Texture();
  44334. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  44335. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  44336. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  44337. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  44338. // --- Utilities ---
  44339. // Array Caches (provide typed arrays for temporary by size)
  44340. const arrayCacheF32 = [];
  44341. const arrayCacheI32 = [];
  44342. // Float32Array caches used for uploading Matrix uniforms
  44343. const mat4array = new Float32Array( 16 );
  44344. const mat3array = new Float32Array( 9 );
  44345. const mat2array = new Float32Array( 4 );
  44346. // Flattening for arrays of vectors and matrices
  44347. function flatten( array, nBlocks, blockSize ) {
  44348. const firstElem = array[ 0 ];
  44349. if ( firstElem <= 0 || firstElem > 0 ) return array;
  44350. // unoptimized: ! isNaN( firstElem )
  44351. // see http://jacksondunstan.com/articles/983
  44352. const n = nBlocks * blockSize;
  44353. let r = arrayCacheF32[ n ];
  44354. if ( r === undefined ) {
  44355. r = new Float32Array( n );
  44356. arrayCacheF32[ n ] = r;
  44357. }
  44358. if ( nBlocks !== 0 ) {
  44359. firstElem.toArray( r, 0 );
  44360. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  44361. offset += blockSize;
  44362. array[ i ].toArray( r, offset );
  44363. }
  44364. }
  44365. return r;
  44366. }
  44367. function arraysEqual( a, b ) {
  44368. if ( a.length !== b.length ) return false;
  44369. for ( let i = 0, l = a.length; i < l; i ++ ) {
  44370. if ( a[ i ] !== b[ i ] ) return false;
  44371. }
  44372. return true;
  44373. }
  44374. function copyArray( a, b ) {
  44375. for ( let i = 0, l = b.length; i < l; i ++ ) {
  44376. a[ i ] = b[ i ];
  44377. }
  44378. }
  44379. // Texture unit allocation
  44380. function allocTexUnits( textures, n ) {
  44381. let r = arrayCacheI32[ n ];
  44382. if ( r === undefined ) {
  44383. r = new Int32Array( n );
  44384. arrayCacheI32[ n ] = r;
  44385. }
  44386. for ( let i = 0; i !== n; ++ i ) {
  44387. r[ i ] = textures.allocateTextureUnit();
  44388. }
  44389. return r;
  44390. }
  44391. // --- Setters ---
  44392. // Note: Defining these methods externally, because they come in a bunch
  44393. // and this way their names minify.
  44394. // Single scalar
  44395. function setValueV1f( gl, v ) {
  44396. const cache = this.cache;
  44397. if ( cache[ 0 ] === v ) return;
  44398. gl.uniform1f( this.addr, v );
  44399. cache[ 0 ] = v;
  44400. }
  44401. // Single float vector (from flat array or THREE.VectorN)
  44402. function setValueV2f( gl, v ) {
  44403. const cache = this.cache;
  44404. if ( v.x !== undefined ) {
  44405. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  44406. gl.uniform2f( this.addr, v.x, v.y );
  44407. cache[ 0 ] = v.x;
  44408. cache[ 1 ] = v.y;
  44409. }
  44410. } else {
  44411. if ( arraysEqual( cache, v ) ) return;
  44412. gl.uniform2fv( this.addr, v );
  44413. copyArray( cache, v );
  44414. }
  44415. }
  44416. function setValueV3f( gl, v ) {
  44417. const cache = this.cache;
  44418. if ( v.x !== undefined ) {
  44419. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  44420. gl.uniform3f( this.addr, v.x, v.y, v.z );
  44421. cache[ 0 ] = v.x;
  44422. cache[ 1 ] = v.y;
  44423. cache[ 2 ] = v.z;
  44424. }
  44425. } else if ( v.r !== undefined ) {
  44426. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  44427. gl.uniform3f( this.addr, v.r, v.g, v.b );
  44428. cache[ 0 ] = v.r;
  44429. cache[ 1 ] = v.g;
  44430. cache[ 2 ] = v.b;
  44431. }
  44432. } else {
  44433. if ( arraysEqual( cache, v ) ) return;
  44434. gl.uniform3fv( this.addr, v );
  44435. copyArray( cache, v );
  44436. }
  44437. }
  44438. function setValueV4f( gl, v ) {
  44439. const cache = this.cache;
  44440. if ( v.x !== undefined ) {
  44441. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  44442. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  44443. cache[ 0 ] = v.x;
  44444. cache[ 1 ] = v.y;
  44445. cache[ 2 ] = v.z;
  44446. cache[ 3 ] = v.w;
  44447. }
  44448. } else {
  44449. if ( arraysEqual( cache, v ) ) return;
  44450. gl.uniform4fv( this.addr, v );
  44451. copyArray( cache, v );
  44452. }
  44453. }
  44454. // Single matrix (from flat array or THREE.MatrixN)
  44455. function setValueM2( gl, v ) {
  44456. const cache = this.cache;
  44457. const elements = v.elements;
  44458. if ( elements === undefined ) {
  44459. if ( arraysEqual( cache, v ) ) return;
  44460. gl.uniformMatrix2fv( this.addr, false, v );
  44461. copyArray( cache, v );
  44462. } else {
  44463. if ( arraysEqual( cache, elements ) ) return;
  44464. mat2array.set( elements );
  44465. gl.uniformMatrix2fv( this.addr, false, mat2array );
  44466. copyArray( cache, elements );
  44467. }
  44468. }
  44469. function setValueM3( gl, v ) {
  44470. const cache = this.cache;
  44471. const elements = v.elements;
  44472. if ( elements === undefined ) {
  44473. if ( arraysEqual( cache, v ) ) return;
  44474. gl.uniformMatrix3fv( this.addr, false, v );
  44475. copyArray( cache, v );
  44476. } else {
  44477. if ( arraysEqual( cache, elements ) ) return;
  44478. mat3array.set( elements );
  44479. gl.uniformMatrix3fv( this.addr, false, mat3array );
  44480. copyArray( cache, elements );
  44481. }
  44482. }
  44483. function setValueM4( gl, v ) {
  44484. const cache = this.cache;
  44485. const elements = v.elements;
  44486. if ( elements === undefined ) {
  44487. if ( arraysEqual( cache, v ) ) return;
  44488. gl.uniformMatrix4fv( this.addr, false, v );
  44489. copyArray( cache, v );
  44490. } else {
  44491. if ( arraysEqual( cache, elements ) ) return;
  44492. mat4array.set( elements );
  44493. gl.uniformMatrix4fv( this.addr, false, mat4array );
  44494. copyArray( cache, elements );
  44495. }
  44496. }
  44497. // Single integer / boolean
  44498. function setValueV1i( gl, v ) {
  44499. const cache = this.cache;
  44500. if ( cache[ 0 ] === v ) return;
  44501. gl.uniform1i( this.addr, v );
  44502. cache[ 0 ] = v;
  44503. }
  44504. // Single integer / boolean vector (from flat array or THREE.VectorN)
  44505. function setValueV2i( gl, v ) {
  44506. const cache = this.cache;
  44507. if ( v.x !== undefined ) {
  44508. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  44509. gl.uniform2i( this.addr, v.x, v.y );
  44510. cache[ 0 ] = v.x;
  44511. cache[ 1 ] = v.y;
  44512. }
  44513. } else {
  44514. if ( arraysEqual( cache, v ) ) return;
  44515. gl.uniform2iv( this.addr, v );
  44516. copyArray( cache, v );
  44517. }
  44518. }
  44519. function setValueV3i( gl, v ) {
  44520. const cache = this.cache;
  44521. if ( v.x !== undefined ) {
  44522. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  44523. gl.uniform3i( this.addr, v.x, v.y, v.z );
  44524. cache[ 0 ] = v.x;
  44525. cache[ 1 ] = v.y;
  44526. cache[ 2 ] = v.z;
  44527. }
  44528. } else {
  44529. if ( arraysEqual( cache, v ) ) return;
  44530. gl.uniform3iv( this.addr, v );
  44531. copyArray( cache, v );
  44532. }
  44533. }
  44534. function setValueV4i( gl, v ) {
  44535. const cache = this.cache;
  44536. if ( v.x !== undefined ) {
  44537. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  44538. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  44539. cache[ 0 ] = v.x;
  44540. cache[ 1 ] = v.y;
  44541. cache[ 2 ] = v.z;
  44542. cache[ 3 ] = v.w;
  44543. }
  44544. } else {
  44545. if ( arraysEqual( cache, v ) ) return;
  44546. gl.uniform4iv( this.addr, v );
  44547. copyArray( cache, v );
  44548. }
  44549. }
  44550. // Single unsigned integer
  44551. function setValueV1ui( gl, v ) {
  44552. const cache = this.cache;
  44553. if ( cache[ 0 ] === v ) return;
  44554. gl.uniform1ui( this.addr, v );
  44555. cache[ 0 ] = v;
  44556. }
  44557. // Single unsigned integer vector (from flat array or THREE.VectorN)
  44558. function setValueV2ui( gl, v ) {
  44559. const cache = this.cache;
  44560. if ( v.x !== undefined ) {
  44561. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  44562. gl.uniform2ui( this.addr, v.x, v.y );
  44563. cache[ 0 ] = v.x;
  44564. cache[ 1 ] = v.y;
  44565. }
  44566. } else {
  44567. if ( arraysEqual( cache, v ) ) return;
  44568. gl.uniform2uiv( this.addr, v );
  44569. copyArray( cache, v );
  44570. }
  44571. }
  44572. function setValueV3ui( gl, v ) {
  44573. const cache = this.cache;
  44574. if ( v.x !== undefined ) {
  44575. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  44576. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  44577. cache[ 0 ] = v.x;
  44578. cache[ 1 ] = v.y;
  44579. cache[ 2 ] = v.z;
  44580. }
  44581. } else {
  44582. if ( arraysEqual( cache, v ) ) return;
  44583. gl.uniform3uiv( this.addr, v );
  44584. copyArray( cache, v );
  44585. }
  44586. }
  44587. function setValueV4ui( gl, v ) {
  44588. const cache = this.cache;
  44589. if ( v.x !== undefined ) {
  44590. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  44591. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  44592. cache[ 0 ] = v.x;
  44593. cache[ 1 ] = v.y;
  44594. cache[ 2 ] = v.z;
  44595. cache[ 3 ] = v.w;
  44596. }
  44597. } else {
  44598. if ( arraysEqual( cache, v ) ) return;
  44599. gl.uniform4uiv( this.addr, v );
  44600. copyArray( cache, v );
  44601. }
  44602. }
  44603. // Single texture (2D / Cube)
  44604. function setValueT1( gl, v, textures ) {
  44605. const cache = this.cache;
  44606. const unit = textures.allocateTextureUnit();
  44607. if ( cache[ 0 ] !== unit ) {
  44608. gl.uniform1i( this.addr, unit );
  44609. cache[ 0 ] = unit;
  44610. }
  44611. let emptyTexture2D;
  44612. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  44613. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  44614. emptyTexture2D = emptyShadowTexture;
  44615. } else {
  44616. emptyTexture2D = emptyTexture;
  44617. }
  44618. textures.setTexture2D( v || emptyTexture2D, unit );
  44619. }
  44620. function setValueT3D1( gl, v, textures ) {
  44621. const cache = this.cache;
  44622. const unit = textures.allocateTextureUnit();
  44623. if ( cache[ 0 ] !== unit ) {
  44624. gl.uniform1i( this.addr, unit );
  44625. cache[ 0 ] = unit;
  44626. }
  44627. textures.setTexture3D( v || empty3dTexture, unit );
  44628. }
  44629. function setValueT6( gl, v, textures ) {
  44630. const cache = this.cache;
  44631. const unit = textures.allocateTextureUnit();
  44632. if ( cache[ 0 ] !== unit ) {
  44633. gl.uniform1i( this.addr, unit );
  44634. cache[ 0 ] = unit;
  44635. }
  44636. textures.setTextureCube( v || emptyCubeTexture, unit );
  44637. }
  44638. function setValueT2DArray1( gl, v, textures ) {
  44639. const cache = this.cache;
  44640. const unit = textures.allocateTextureUnit();
  44641. if ( cache[ 0 ] !== unit ) {
  44642. gl.uniform1i( this.addr, unit );
  44643. cache[ 0 ] = unit;
  44644. }
  44645. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  44646. }
  44647. // Helper to pick the right setter for the singular case
  44648. function getSingularSetter( type ) {
  44649. switch ( type ) {
  44650. case 0x1406: return setValueV1f; // FLOAT
  44651. case 0x8b50: return setValueV2f; // _VEC2
  44652. case 0x8b51: return setValueV3f; // _VEC3
  44653. case 0x8b52: return setValueV4f; // _VEC4
  44654. case 0x8b5a: return setValueM2; // _MAT2
  44655. case 0x8b5b: return setValueM3; // _MAT3
  44656. case 0x8b5c: return setValueM4; // _MAT4
  44657. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  44658. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  44659. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  44660. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  44661. case 0x1405: return setValueV1ui; // UINT
  44662. case 0x8dc6: return setValueV2ui; // _VEC2
  44663. case 0x8dc7: return setValueV3ui; // _VEC3
  44664. case 0x8dc8: return setValueV4ui; // _VEC4
  44665. case 0x8b5e: // SAMPLER_2D
  44666. case 0x8d66: // SAMPLER_EXTERNAL_OES
  44667. case 0x8dca: // INT_SAMPLER_2D
  44668. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  44669. case 0x8b62: // SAMPLER_2D_SHADOW
  44670. return setValueT1;
  44671. case 0x8b5f: // SAMPLER_3D
  44672. case 0x8dcb: // INT_SAMPLER_3D
  44673. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  44674. return setValueT3D1;
  44675. case 0x8b60: // SAMPLER_CUBE
  44676. case 0x8dcc: // INT_SAMPLER_CUBE
  44677. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  44678. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  44679. return setValueT6;
  44680. case 0x8dc1: // SAMPLER_2D_ARRAY
  44681. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  44682. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  44683. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  44684. return setValueT2DArray1;
  44685. }
  44686. }
  44687. // Array of scalars
  44688. function setValueV1fArray( gl, v ) {
  44689. gl.uniform1fv( this.addr, v );
  44690. }
  44691. // Array of vectors (from flat array or array of THREE.VectorN)
  44692. function setValueV2fArray( gl, v ) {
  44693. const data = flatten( v, this.size, 2 );
  44694. gl.uniform2fv( this.addr, data );
  44695. }
  44696. function setValueV3fArray( gl, v ) {
  44697. const data = flatten( v, this.size, 3 );
  44698. gl.uniform3fv( this.addr, data );
  44699. }
  44700. function setValueV4fArray( gl, v ) {
  44701. const data = flatten( v, this.size, 4 );
  44702. gl.uniform4fv( this.addr, data );
  44703. }
  44704. // Array of matrices (from flat array or array of THREE.MatrixN)
  44705. function setValueM2Array( gl, v ) {
  44706. const data = flatten( v, this.size, 4 );
  44707. gl.uniformMatrix2fv( this.addr, false, data );
  44708. }
  44709. function setValueM3Array( gl, v ) {
  44710. const data = flatten( v, this.size, 9 );
  44711. gl.uniformMatrix3fv( this.addr, false, data );
  44712. }
  44713. function setValueM4Array( gl, v ) {
  44714. const data = flatten( v, this.size, 16 );
  44715. gl.uniformMatrix4fv( this.addr, false, data );
  44716. }
  44717. // Array of integer / boolean
  44718. function setValueV1iArray( gl, v ) {
  44719. gl.uniform1iv( this.addr, v );
  44720. }
  44721. // Array of integer / boolean vectors (from flat array)
  44722. function setValueV2iArray( gl, v ) {
  44723. gl.uniform2iv( this.addr, v );
  44724. }
  44725. function setValueV3iArray( gl, v ) {
  44726. gl.uniform3iv( this.addr, v );
  44727. }
  44728. function setValueV4iArray( gl, v ) {
  44729. gl.uniform4iv( this.addr, v );
  44730. }
  44731. // Array of unsigned integer
  44732. function setValueV1uiArray( gl, v ) {
  44733. gl.uniform1uiv( this.addr, v );
  44734. }
  44735. // Array of unsigned integer vectors (from flat array)
  44736. function setValueV2uiArray( gl, v ) {
  44737. gl.uniform2uiv( this.addr, v );
  44738. }
  44739. function setValueV3uiArray( gl, v ) {
  44740. gl.uniform3uiv( this.addr, v );
  44741. }
  44742. function setValueV4uiArray( gl, v ) {
  44743. gl.uniform4uiv( this.addr, v );
  44744. }
  44745. // Array of textures (2D / 3D / Cube / 2DArray)
  44746. function setValueT1Array( gl, v, textures ) {
  44747. const cache = this.cache;
  44748. const n = v.length;
  44749. const units = allocTexUnits( textures, n );
  44750. if ( ! arraysEqual( cache, units ) ) {
  44751. gl.uniform1iv( this.addr, units );
  44752. copyArray( cache, units );
  44753. }
  44754. for ( let i = 0; i !== n; ++ i ) {
  44755. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  44756. }
  44757. }
  44758. function setValueT3DArray( gl, v, textures ) {
  44759. const cache = this.cache;
  44760. const n = v.length;
  44761. const units = allocTexUnits( textures, n );
  44762. if ( ! arraysEqual( cache, units ) ) {
  44763. gl.uniform1iv( this.addr, units );
  44764. copyArray( cache, units );
  44765. }
  44766. for ( let i = 0; i !== n; ++ i ) {
  44767. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  44768. }
  44769. }
  44770. function setValueT6Array( gl, v, textures ) {
  44771. const cache = this.cache;
  44772. const n = v.length;
  44773. const units = allocTexUnits( textures, n );
  44774. if ( ! arraysEqual( cache, units ) ) {
  44775. gl.uniform1iv( this.addr, units );
  44776. copyArray( cache, units );
  44777. }
  44778. for ( let i = 0; i !== n; ++ i ) {
  44779. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  44780. }
  44781. }
  44782. function setValueT2DArrayArray( gl, v, textures ) {
  44783. const cache = this.cache;
  44784. const n = v.length;
  44785. const units = allocTexUnits( textures, n );
  44786. if ( ! arraysEqual( cache, units ) ) {
  44787. gl.uniform1iv( this.addr, units );
  44788. copyArray( cache, units );
  44789. }
  44790. for ( let i = 0; i !== n; ++ i ) {
  44791. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  44792. }
  44793. }
  44794. // Helper to pick the right setter for a pure (bottom-level) array
  44795. function getPureArraySetter( type ) {
  44796. switch ( type ) {
  44797. case 0x1406: return setValueV1fArray; // FLOAT
  44798. case 0x8b50: return setValueV2fArray; // _VEC2
  44799. case 0x8b51: return setValueV3fArray; // _VEC3
  44800. case 0x8b52: return setValueV4fArray; // _VEC4
  44801. case 0x8b5a: return setValueM2Array; // _MAT2
  44802. case 0x8b5b: return setValueM3Array; // _MAT3
  44803. case 0x8b5c: return setValueM4Array; // _MAT4
  44804. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  44805. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  44806. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  44807. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  44808. case 0x1405: return setValueV1uiArray; // UINT
  44809. case 0x8dc6: return setValueV2uiArray; // _VEC2
  44810. case 0x8dc7: return setValueV3uiArray; // _VEC3
  44811. case 0x8dc8: return setValueV4uiArray; // _VEC4
  44812. case 0x8b5e: // SAMPLER_2D
  44813. case 0x8d66: // SAMPLER_EXTERNAL_OES
  44814. case 0x8dca: // INT_SAMPLER_2D
  44815. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  44816. case 0x8b62: // SAMPLER_2D_SHADOW
  44817. return setValueT1Array;
  44818. case 0x8b5f: // SAMPLER_3D
  44819. case 0x8dcb: // INT_SAMPLER_3D
  44820. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  44821. return setValueT3DArray;
  44822. case 0x8b60: // SAMPLER_CUBE
  44823. case 0x8dcc: // INT_SAMPLER_CUBE
  44824. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  44825. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  44826. return setValueT6Array;
  44827. case 0x8dc1: // SAMPLER_2D_ARRAY
  44828. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  44829. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  44830. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  44831. return setValueT2DArrayArray;
  44832. }
  44833. }
  44834. // --- Uniform Classes ---
  44835. class SingleUniform {
  44836. constructor( id, activeInfo, addr ) {
  44837. this.id = id;
  44838. this.addr = addr;
  44839. this.cache = [];
  44840. this.type = activeInfo.type;
  44841. this.setValue = getSingularSetter( activeInfo.type );
  44842. // this.path = activeInfo.name; // DEBUG
  44843. }
  44844. }
  44845. class PureArrayUniform {
  44846. constructor( id, activeInfo, addr ) {
  44847. this.id = id;
  44848. this.addr = addr;
  44849. this.cache = [];
  44850. this.type = activeInfo.type;
  44851. this.size = activeInfo.size;
  44852. this.setValue = getPureArraySetter( activeInfo.type );
  44853. // this.path = activeInfo.name; // DEBUG
  44854. }
  44855. }
  44856. class StructuredUniform {
  44857. constructor( id ) {
  44858. this.id = id;
  44859. this.seq = [];
  44860. this.map = {};
  44861. }
  44862. setValue( gl, value, textures ) {
  44863. const seq = this.seq;
  44864. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  44865. const u = seq[ i ];
  44866. u.setValue( gl, value[ u.id ], textures );
  44867. }
  44868. }
  44869. }
  44870. // --- Top-level ---
  44871. // Parser - builds up the property tree from the path strings
  44872. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  44873. // extracts
  44874. // - the identifier (member name or array index)
  44875. // - followed by an optional right bracket (found when array index)
  44876. // - followed by an optional left bracket or dot (type of subscript)
  44877. //
  44878. // Note: These portions can be read in a non-overlapping fashion and
  44879. // allow straightforward parsing of the hierarchy that WebGL encodes
  44880. // in the uniform names.
  44881. function addUniform( container, uniformObject ) {
  44882. container.seq.push( uniformObject );
  44883. container.map[ uniformObject.id ] = uniformObject;
  44884. }
  44885. function parseUniform( activeInfo, addr, container ) {
  44886. const path = activeInfo.name,
  44887. pathLength = path.length;
  44888. // reset RegExp object, because of the early exit of a previous run
  44889. RePathPart.lastIndex = 0;
  44890. while ( true ) {
  44891. const match = RePathPart.exec( path ),
  44892. matchEnd = RePathPart.lastIndex;
  44893. let id = match[ 1 ];
  44894. const idIsIndex = match[ 2 ] === ']',
  44895. subscript = match[ 3 ];
  44896. if ( idIsIndex ) id = id | 0; // convert to integer
  44897. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  44898. // bare name or "pure" bottom-level array "[0]" suffix
  44899. addUniform( container, subscript === undefined ?
  44900. new SingleUniform( id, activeInfo, addr ) :
  44901. new PureArrayUniform( id, activeInfo, addr ) );
  44902. break;
  44903. } else {
  44904. // step into inner node / create it in case it doesn't exist
  44905. const map = container.map;
  44906. let next = map[ id ];
  44907. if ( next === undefined ) {
  44908. next = new StructuredUniform( id );
  44909. addUniform( container, next );
  44910. }
  44911. container = next;
  44912. }
  44913. }
  44914. }
  44915. // Root Container
  44916. class WebGLUniforms {
  44917. constructor( gl, program ) {
  44918. this.seq = [];
  44919. this.map = {};
  44920. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  44921. for ( let i = 0; i < n; ++ i ) {
  44922. const info = gl.getActiveUniform( program, i ),
  44923. addr = gl.getUniformLocation( program, info.name );
  44924. parseUniform( info, addr, this );
  44925. }
  44926. }
  44927. setValue( gl, name, value, textures ) {
  44928. const u = this.map[ name ];
  44929. if ( u !== undefined ) u.setValue( gl, value, textures );
  44930. }
  44931. setOptional( gl, object, name ) {
  44932. const v = object[ name ];
  44933. if ( v !== undefined ) this.setValue( gl, name, v );
  44934. }
  44935. static upload( gl, seq, values, textures ) {
  44936. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  44937. const u = seq[ i ],
  44938. v = values[ u.id ];
  44939. if ( v.needsUpdate !== false ) {
  44940. // note: always updating when .needsUpdate is undefined
  44941. u.setValue( gl, v.value, textures );
  44942. }
  44943. }
  44944. }
  44945. static seqWithValue( seq, values ) {
  44946. const r = [];
  44947. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  44948. const u = seq[ i ];
  44949. if ( u.id in values ) r.push( u );
  44950. }
  44951. return r;
  44952. }
  44953. }
  44954. function WebGLShader( gl, type, string ) {
  44955. const shader = gl.createShader( type );
  44956. gl.shaderSource( shader, string );
  44957. gl.compileShader( shader );
  44958. return shader;
  44959. }
  44960. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  44961. const COMPLETION_STATUS_KHR = 0x91B1;
  44962. let programIdCount = 0;
  44963. function handleSource( string, errorLine ) {
  44964. const lines = string.split( '\n' );
  44965. const lines2 = [];
  44966. const from = Math.max( errorLine - 6, 0 );
  44967. const to = Math.min( errorLine + 6, lines.length );
  44968. for ( let i = from; i < to; i ++ ) {
  44969. const line = i + 1;
  44970. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  44971. }
  44972. return lines2.join( '\n' );
  44973. }
  44974. const _m0 = /*@__PURE__*/ new Matrix3();
  44975. function getEncodingComponents( colorSpace ) {
  44976. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  44977. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  44978. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  44979. case LinearTransfer:
  44980. return [ encodingMatrix, 'LinearTransferOETF' ];
  44981. case SRGBTransfer:
  44982. return [ encodingMatrix, 'sRGBTransferOETF' ];
  44983. default:
  44984. console.warn( 'THREE.WebGLProgram: Unsupported color space: ', colorSpace );
  44985. return [ encodingMatrix, 'LinearTransferOETF' ];
  44986. }
  44987. }
  44988. function getShaderErrors( gl, shader, type ) {
  44989. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  44990. const errors = gl.getShaderInfoLog( shader ).trim();
  44991. if ( status && errors === '' ) return '';
  44992. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  44993. if ( errorMatches ) {
  44994. // --enable-privileged-webgl-extension
  44995. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  44996. const errorLine = parseInt( errorMatches[ 1 ] );
  44997. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  44998. } else {
  44999. return errors;
  45000. }
  45001. }
  45002. function getTexelEncodingFunction( functionName, colorSpace ) {
  45003. const components = getEncodingComponents( colorSpace );
  45004. return [
  45005. `vec4 ${functionName}( vec4 value ) {`,
  45006. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  45007. '}',
  45008. ].join( '\n' );
  45009. }
  45010. function getToneMappingFunction( functionName, toneMapping ) {
  45011. let toneMappingName;
  45012. switch ( toneMapping ) {
  45013. case LinearToneMapping:
  45014. toneMappingName = 'Linear';
  45015. break;
  45016. case ReinhardToneMapping:
  45017. toneMappingName = 'Reinhard';
  45018. break;
  45019. case CineonToneMapping:
  45020. toneMappingName = 'Cineon';
  45021. break;
  45022. case ACESFilmicToneMapping:
  45023. toneMappingName = 'ACESFilmic';
  45024. break;
  45025. case AgXToneMapping:
  45026. toneMappingName = 'AgX';
  45027. break;
  45028. case NeutralToneMapping:
  45029. toneMappingName = 'Neutral';
  45030. break;
  45031. case CustomToneMapping:
  45032. toneMappingName = 'Custom';
  45033. break;
  45034. default:
  45035. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  45036. toneMappingName = 'Linear';
  45037. }
  45038. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  45039. }
  45040. const _v0 = /*@__PURE__*/ new Vector3();
  45041. function getLuminanceFunction() {
  45042. ColorManagement.getLuminanceCoefficients( _v0 );
  45043. const r = _v0.x.toFixed( 4 );
  45044. const g = _v0.y.toFixed( 4 );
  45045. const b = _v0.z.toFixed( 4 );
  45046. return [
  45047. 'float luminance( const in vec3 rgb ) {',
  45048. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  45049. ' return dot( weights, rgb );',
  45050. '}'
  45051. ].join( '\n' );
  45052. }
  45053. function generateVertexExtensions( parameters ) {
  45054. const chunks = [
  45055. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  45056. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  45057. ];
  45058. return chunks.filter( filterEmptyLine ).join( '\n' );
  45059. }
  45060. function generateDefines( defines ) {
  45061. const chunks = [];
  45062. for ( const name in defines ) {
  45063. const value = defines[ name ];
  45064. if ( value === false ) continue;
  45065. chunks.push( '#define ' + name + ' ' + value );
  45066. }
  45067. return chunks.join( '\n' );
  45068. }
  45069. function fetchAttributeLocations( gl, program ) {
  45070. const attributes = {};
  45071. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  45072. for ( let i = 0; i < n; i ++ ) {
  45073. const info = gl.getActiveAttrib( program, i );
  45074. const name = info.name;
  45075. let locationSize = 1;
  45076. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  45077. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  45078. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  45079. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  45080. attributes[ name ] = {
  45081. type: info.type,
  45082. location: gl.getAttribLocation( program, name ),
  45083. locationSize: locationSize
  45084. };
  45085. }
  45086. return attributes;
  45087. }
  45088. function filterEmptyLine( string ) {
  45089. return string !== '';
  45090. }
  45091. function replaceLightNums( string, parameters ) {
  45092. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  45093. return string
  45094. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  45095. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  45096. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  45097. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  45098. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  45099. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  45100. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  45101. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  45102. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  45103. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  45104. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  45105. }
  45106. function replaceClippingPlaneNums( string, parameters ) {
  45107. return string
  45108. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  45109. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  45110. }
  45111. // Resolve Includes
  45112. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  45113. function resolveIncludes( string ) {
  45114. return string.replace( includePattern, includeReplacer );
  45115. }
  45116. const shaderChunkMap = new Map();
  45117. function includeReplacer( match, include ) {
  45118. let string = ShaderChunk[ include ];
  45119. if ( string === undefined ) {
  45120. const newInclude = shaderChunkMap.get( include );
  45121. if ( newInclude !== undefined ) {
  45122. string = ShaderChunk[ newInclude ];
  45123. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  45124. } else {
  45125. throw new Error( 'Can not resolve #include <' + include + '>' );
  45126. }
  45127. }
  45128. return resolveIncludes( string );
  45129. }
  45130. // Unroll Loops
  45131. 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;
  45132. function unrollLoops( string ) {
  45133. return string.replace( unrollLoopPattern, loopReplacer );
  45134. }
  45135. function loopReplacer( match, start, end, snippet ) {
  45136. let string = '';
  45137. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  45138. string += snippet
  45139. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  45140. .replace( /UNROLLED_LOOP_INDEX/g, i );
  45141. }
  45142. return string;
  45143. }
  45144. //
  45145. function generatePrecision( parameters ) {
  45146. let precisionstring = `precision ${parameters.precision} float;
  45147. precision ${parameters.precision} int;
  45148. precision ${parameters.precision} sampler2D;
  45149. precision ${parameters.precision} samplerCube;
  45150. precision ${parameters.precision} sampler3D;
  45151. precision ${parameters.precision} sampler2DArray;
  45152. precision ${parameters.precision} sampler2DShadow;
  45153. precision ${parameters.precision} samplerCubeShadow;
  45154. precision ${parameters.precision} sampler2DArrayShadow;
  45155. precision ${parameters.precision} isampler2D;
  45156. precision ${parameters.precision} isampler3D;
  45157. precision ${parameters.precision} isamplerCube;
  45158. precision ${parameters.precision} isampler2DArray;
  45159. precision ${parameters.precision} usampler2D;
  45160. precision ${parameters.precision} usampler3D;
  45161. precision ${parameters.precision} usamplerCube;
  45162. precision ${parameters.precision} usampler2DArray;
  45163. `;
  45164. if ( parameters.precision === 'highp' ) {
  45165. precisionstring += '\n#define HIGH_PRECISION';
  45166. } else if ( parameters.precision === 'mediump' ) {
  45167. precisionstring += '\n#define MEDIUM_PRECISION';
  45168. } else if ( parameters.precision === 'lowp' ) {
  45169. precisionstring += '\n#define LOW_PRECISION';
  45170. }
  45171. return precisionstring;
  45172. }
  45173. function generateShadowMapTypeDefine( parameters ) {
  45174. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  45175. if ( parameters.shadowMapType === PCFShadowMap ) {
  45176. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  45177. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  45178. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  45179. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  45180. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  45181. }
  45182. return shadowMapTypeDefine;
  45183. }
  45184. function generateEnvMapTypeDefine( parameters ) {
  45185. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  45186. if ( parameters.envMap ) {
  45187. switch ( parameters.envMapMode ) {
  45188. case CubeReflectionMapping:
  45189. case CubeRefractionMapping:
  45190. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  45191. break;
  45192. case CubeUVReflectionMapping:
  45193. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  45194. break;
  45195. }
  45196. }
  45197. return envMapTypeDefine;
  45198. }
  45199. function generateEnvMapModeDefine( parameters ) {
  45200. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  45201. if ( parameters.envMap ) {
  45202. switch ( parameters.envMapMode ) {
  45203. case CubeRefractionMapping:
  45204. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  45205. break;
  45206. }
  45207. }
  45208. return envMapModeDefine;
  45209. }
  45210. function generateEnvMapBlendingDefine( parameters ) {
  45211. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  45212. if ( parameters.envMap ) {
  45213. switch ( parameters.combine ) {
  45214. case MultiplyOperation:
  45215. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  45216. break;
  45217. case MixOperation:
  45218. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  45219. break;
  45220. case AddOperation:
  45221. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  45222. break;
  45223. }
  45224. }
  45225. return envMapBlendingDefine;
  45226. }
  45227. function generateCubeUVSize( parameters ) {
  45228. const imageHeight = parameters.envMapCubeUVHeight;
  45229. if ( imageHeight === null ) return null;
  45230. const maxMip = Math.log2( imageHeight ) - 2;
  45231. const texelHeight = 1.0 / imageHeight;
  45232. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  45233. return { texelWidth, texelHeight, maxMip };
  45234. }
  45235. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  45236. // TODO Send this event to Three.js DevTools
  45237. // console.log( 'WebGLProgram', cacheKey );
  45238. const gl = renderer.getContext();
  45239. const defines = parameters.defines;
  45240. let vertexShader = parameters.vertexShader;
  45241. let fragmentShader = parameters.fragmentShader;
  45242. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  45243. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  45244. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  45245. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  45246. const envMapCubeUVSize = generateCubeUVSize( parameters );
  45247. const customVertexExtensions = generateVertexExtensions( parameters );
  45248. const customDefines = generateDefines( defines );
  45249. const program = gl.createProgram();
  45250. let prefixVertex, prefixFragment;
  45251. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  45252. if ( parameters.isRawShaderMaterial ) {
  45253. prefixVertex = [
  45254. '#define SHADER_TYPE ' + parameters.shaderType,
  45255. '#define SHADER_NAME ' + parameters.shaderName,
  45256. customDefines
  45257. ].filter( filterEmptyLine ).join( '\n' );
  45258. if ( prefixVertex.length > 0 ) {
  45259. prefixVertex += '\n';
  45260. }
  45261. prefixFragment = [
  45262. '#define SHADER_TYPE ' + parameters.shaderType,
  45263. '#define SHADER_NAME ' + parameters.shaderName,
  45264. customDefines
  45265. ].filter( filterEmptyLine ).join( '\n' );
  45266. if ( prefixFragment.length > 0 ) {
  45267. prefixFragment += '\n';
  45268. }
  45269. } else {
  45270. prefixVertex = [
  45271. generatePrecision( parameters ),
  45272. '#define SHADER_TYPE ' + parameters.shaderType,
  45273. '#define SHADER_NAME ' + parameters.shaderName,
  45274. customDefines,
  45275. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  45276. parameters.batching ? '#define USE_BATCHING' : '',
  45277. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  45278. parameters.instancing ? '#define USE_INSTANCING' : '',
  45279. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  45280. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  45281. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  45282. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  45283. parameters.map ? '#define USE_MAP' : '',
  45284. parameters.envMap ? '#define USE_ENVMAP' : '',
  45285. parameters.envMap ? '#define ' + envMapModeDefine : '',
  45286. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  45287. parameters.aoMap ? '#define USE_AOMAP' : '',
  45288. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  45289. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  45290. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  45291. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  45292. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  45293. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  45294. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  45295. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  45296. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  45297. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  45298. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  45299. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  45300. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  45301. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  45302. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  45303. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  45304. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  45305. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  45306. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  45307. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  45308. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  45309. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  45310. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  45311. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  45312. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  45313. //
  45314. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  45315. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  45316. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  45317. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  45318. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  45319. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  45320. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  45321. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  45322. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  45323. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  45324. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  45325. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  45326. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  45327. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  45328. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  45329. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  45330. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  45331. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  45332. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  45333. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  45334. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  45335. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  45336. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  45337. //
  45338. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  45339. parameters.vertexColors ? '#define USE_COLOR' : '',
  45340. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  45341. parameters.vertexUv1s ? '#define USE_UV1' : '',
  45342. parameters.vertexUv2s ? '#define USE_UV2' : '',
  45343. parameters.vertexUv3s ? '#define USE_UV3' : '',
  45344. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  45345. parameters.flatShading ? '#define FLAT_SHADED' : '',
  45346. parameters.skinning ? '#define USE_SKINNING' : '',
  45347. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  45348. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  45349. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  45350. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  45351. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  45352. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  45353. parameters.flipSided ? '#define FLIP_SIDED' : '',
  45354. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  45355. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  45356. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  45357. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  45358. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  45359. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  45360. 'uniform mat4 modelMatrix;',
  45361. 'uniform mat4 modelViewMatrix;',
  45362. 'uniform mat4 projectionMatrix;',
  45363. 'uniform mat4 viewMatrix;',
  45364. 'uniform mat3 normalMatrix;',
  45365. 'uniform vec3 cameraPosition;',
  45366. 'uniform bool isOrthographic;',
  45367. '#ifdef USE_INSTANCING',
  45368. ' attribute mat4 instanceMatrix;',
  45369. '#endif',
  45370. '#ifdef USE_INSTANCING_COLOR',
  45371. ' attribute vec3 instanceColor;',
  45372. '#endif',
  45373. '#ifdef USE_INSTANCING_MORPH',
  45374. ' uniform sampler2D morphTexture;',
  45375. '#endif',
  45376. 'attribute vec3 position;',
  45377. 'attribute vec3 normal;',
  45378. 'attribute vec2 uv;',
  45379. '#ifdef USE_UV1',
  45380. ' attribute vec2 uv1;',
  45381. '#endif',
  45382. '#ifdef USE_UV2',
  45383. ' attribute vec2 uv2;',
  45384. '#endif',
  45385. '#ifdef USE_UV3',
  45386. ' attribute vec2 uv3;',
  45387. '#endif',
  45388. '#ifdef USE_TANGENT',
  45389. ' attribute vec4 tangent;',
  45390. '#endif',
  45391. '#if defined( USE_COLOR_ALPHA )',
  45392. ' attribute vec4 color;',
  45393. '#elif defined( USE_COLOR )',
  45394. ' attribute vec3 color;',
  45395. '#endif',
  45396. '#ifdef USE_SKINNING',
  45397. ' attribute vec4 skinIndex;',
  45398. ' attribute vec4 skinWeight;',
  45399. '#endif',
  45400. '\n'
  45401. ].filter( filterEmptyLine ).join( '\n' );
  45402. prefixFragment = [
  45403. generatePrecision( parameters ),
  45404. '#define SHADER_TYPE ' + parameters.shaderType,
  45405. '#define SHADER_NAME ' + parameters.shaderName,
  45406. customDefines,
  45407. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  45408. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  45409. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  45410. parameters.map ? '#define USE_MAP' : '',
  45411. parameters.matcap ? '#define USE_MATCAP' : '',
  45412. parameters.envMap ? '#define USE_ENVMAP' : '',
  45413. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  45414. parameters.envMap ? '#define ' + envMapModeDefine : '',
  45415. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  45416. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  45417. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  45418. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  45419. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  45420. parameters.aoMap ? '#define USE_AOMAP' : '',
  45421. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  45422. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  45423. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  45424. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  45425. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  45426. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  45427. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  45428. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  45429. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  45430. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  45431. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  45432. parameters.dispersion ? '#define USE_DISPERSION' : '',
  45433. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  45434. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  45435. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  45436. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  45437. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  45438. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  45439. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  45440. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  45441. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  45442. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  45443. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  45444. parameters.sheen ? '#define USE_SHEEN' : '',
  45445. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  45446. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  45447. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  45448. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  45449. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  45450. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  45451. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  45452. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  45453. parameters.vertexUv1s ? '#define USE_UV1' : '',
  45454. parameters.vertexUv2s ? '#define USE_UV2' : '',
  45455. parameters.vertexUv3s ? '#define USE_UV3' : '',
  45456. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  45457. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  45458. parameters.flatShading ? '#define FLAT_SHADED' : '',
  45459. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  45460. parameters.flipSided ? '#define FLIP_SIDED' : '',
  45461. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  45462. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  45463. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  45464. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  45465. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  45466. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  45467. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  45468. parameters.reverseDepthBuffer ? '#define USE_REVERSEDEPTHBUF' : '',
  45469. 'uniform mat4 viewMatrix;',
  45470. 'uniform vec3 cameraPosition;',
  45471. 'uniform bool isOrthographic;',
  45472. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  45473. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  45474. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  45475. parameters.dithering ? '#define DITHERING' : '',
  45476. parameters.opaque ? '#define OPAQUE' : '',
  45477. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  45478. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  45479. getLuminanceFunction(),
  45480. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  45481. '\n'
  45482. ].filter( filterEmptyLine ).join( '\n' );
  45483. }
  45484. vertexShader = resolveIncludes( vertexShader );
  45485. vertexShader = replaceLightNums( vertexShader, parameters );
  45486. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  45487. fragmentShader = resolveIncludes( fragmentShader );
  45488. fragmentShader = replaceLightNums( fragmentShader, parameters );
  45489. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  45490. vertexShader = unrollLoops( vertexShader );
  45491. fragmentShader = unrollLoops( fragmentShader );
  45492. if ( parameters.isRawShaderMaterial !== true ) {
  45493. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  45494. versionString = '#version 300 es\n';
  45495. prefixVertex = [
  45496. customVertexExtensions,
  45497. '#define attribute in',
  45498. '#define varying out',
  45499. '#define texture2D texture'
  45500. ].join( '\n' ) + '\n' + prefixVertex;
  45501. prefixFragment = [
  45502. '#define varying in',
  45503. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  45504. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  45505. '#define gl_FragDepthEXT gl_FragDepth',
  45506. '#define texture2D texture',
  45507. '#define textureCube texture',
  45508. '#define texture2DProj textureProj',
  45509. '#define texture2DLodEXT textureLod',
  45510. '#define texture2DProjLodEXT textureProjLod',
  45511. '#define textureCubeLodEXT textureLod',
  45512. '#define texture2DGradEXT textureGrad',
  45513. '#define texture2DProjGradEXT textureProjGrad',
  45514. '#define textureCubeGradEXT textureGrad'
  45515. ].join( '\n' ) + '\n' + prefixFragment;
  45516. }
  45517. const vertexGlsl = versionString + prefixVertex + vertexShader;
  45518. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  45519. // console.log( '*VERTEX*', vertexGlsl );
  45520. // console.log( '*FRAGMENT*', fragmentGlsl );
  45521. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  45522. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  45523. gl.attachShader( program, glVertexShader );
  45524. gl.attachShader( program, glFragmentShader );
  45525. // Force a particular attribute to index 0.
  45526. if ( parameters.index0AttributeName !== undefined ) {
  45527. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  45528. } else if ( parameters.morphTargets === true ) {
  45529. // programs with morphTargets displace position out of attribute 0
  45530. gl.bindAttribLocation( program, 0, 'position' );
  45531. }
  45532. gl.linkProgram( program );
  45533. function onFirstUse( self ) {
  45534. // check for link errors
  45535. if ( renderer.debug.checkShaderErrors ) {
  45536. const programLog = gl.getProgramInfoLog( program ).trim();
  45537. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  45538. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  45539. let runnable = true;
  45540. let haveDiagnostics = true;
  45541. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  45542. runnable = false;
  45543. if ( typeof renderer.debug.onShaderError === 'function' ) {
  45544. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  45545. } else {
  45546. // default error reporting
  45547. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  45548. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  45549. console.error(
  45550. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  45551. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  45552. 'Material Name: ' + self.name + '\n' +
  45553. 'Material Type: ' + self.type + '\n\n' +
  45554. 'Program Info Log: ' + programLog + '\n' +
  45555. vertexErrors + '\n' +
  45556. fragmentErrors
  45557. );
  45558. }
  45559. } else if ( programLog !== '' ) {
  45560. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  45561. } else if ( vertexLog === '' || fragmentLog === '' ) {
  45562. haveDiagnostics = false;
  45563. }
  45564. if ( haveDiagnostics ) {
  45565. self.diagnostics = {
  45566. runnable: runnable,
  45567. programLog: programLog,
  45568. vertexShader: {
  45569. log: vertexLog,
  45570. prefix: prefixVertex
  45571. },
  45572. fragmentShader: {
  45573. log: fragmentLog,
  45574. prefix: prefixFragment
  45575. }
  45576. };
  45577. }
  45578. }
  45579. // Clean up
  45580. // Crashes in iOS9 and iOS10. #18402
  45581. // gl.detachShader( program, glVertexShader );
  45582. // gl.detachShader( program, glFragmentShader );
  45583. gl.deleteShader( glVertexShader );
  45584. gl.deleteShader( glFragmentShader );
  45585. cachedUniforms = new WebGLUniforms( gl, program );
  45586. cachedAttributes = fetchAttributeLocations( gl, program );
  45587. }
  45588. // set up caching for uniform locations
  45589. let cachedUniforms;
  45590. this.getUniforms = function () {
  45591. if ( cachedUniforms === undefined ) {
  45592. // Populates cachedUniforms and cachedAttributes
  45593. onFirstUse( this );
  45594. }
  45595. return cachedUniforms;
  45596. };
  45597. // set up caching for attribute locations
  45598. let cachedAttributes;
  45599. this.getAttributes = function () {
  45600. if ( cachedAttributes === undefined ) {
  45601. // Populates cachedAttributes and cachedUniforms
  45602. onFirstUse( this );
  45603. }
  45604. return cachedAttributes;
  45605. };
  45606. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  45607. // flag the program as ready immediately. It may cause a stall when it's first used.
  45608. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  45609. this.isReady = function () {
  45610. if ( programReady === false ) {
  45611. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  45612. }
  45613. return programReady;
  45614. };
  45615. // free resource
  45616. this.destroy = function () {
  45617. bindingStates.releaseStatesOfProgram( this );
  45618. gl.deleteProgram( program );
  45619. this.program = undefined;
  45620. };
  45621. //
  45622. this.type = parameters.shaderType;
  45623. this.name = parameters.shaderName;
  45624. this.id = programIdCount ++;
  45625. this.cacheKey = cacheKey;
  45626. this.usedTimes = 1;
  45627. this.program = program;
  45628. this.vertexShader = glVertexShader;
  45629. this.fragmentShader = glFragmentShader;
  45630. return this;
  45631. }
  45632. let _id = 0;
  45633. class WebGLShaderCache {
  45634. constructor() {
  45635. this.shaderCache = new Map();
  45636. this.materialCache = new Map();
  45637. }
  45638. update( material ) {
  45639. const vertexShader = material.vertexShader;
  45640. const fragmentShader = material.fragmentShader;
  45641. const vertexShaderStage = this._getShaderStage( vertexShader );
  45642. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  45643. const materialShaders = this._getShaderCacheForMaterial( material );
  45644. if ( materialShaders.has( vertexShaderStage ) === false ) {
  45645. materialShaders.add( vertexShaderStage );
  45646. vertexShaderStage.usedTimes ++;
  45647. }
  45648. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  45649. materialShaders.add( fragmentShaderStage );
  45650. fragmentShaderStage.usedTimes ++;
  45651. }
  45652. return this;
  45653. }
  45654. remove( material ) {
  45655. const materialShaders = this.materialCache.get( material );
  45656. for ( const shaderStage of materialShaders ) {
  45657. shaderStage.usedTimes --;
  45658. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  45659. }
  45660. this.materialCache.delete( material );
  45661. return this;
  45662. }
  45663. getVertexShaderID( material ) {
  45664. return this._getShaderStage( material.vertexShader ).id;
  45665. }
  45666. getFragmentShaderID( material ) {
  45667. return this._getShaderStage( material.fragmentShader ).id;
  45668. }
  45669. dispose() {
  45670. this.shaderCache.clear();
  45671. this.materialCache.clear();
  45672. }
  45673. _getShaderCacheForMaterial( material ) {
  45674. const cache = this.materialCache;
  45675. let set = cache.get( material );
  45676. if ( set === undefined ) {
  45677. set = new Set();
  45678. cache.set( material, set );
  45679. }
  45680. return set;
  45681. }
  45682. _getShaderStage( code ) {
  45683. const cache = this.shaderCache;
  45684. let stage = cache.get( code );
  45685. if ( stage === undefined ) {
  45686. stage = new WebGLShaderStage( code );
  45687. cache.set( code, stage );
  45688. }
  45689. return stage;
  45690. }
  45691. }
  45692. class WebGLShaderStage {
  45693. constructor( code ) {
  45694. this.id = _id ++;
  45695. this.code = code;
  45696. this.usedTimes = 0;
  45697. }
  45698. }
  45699. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  45700. const _programLayers = new Layers();
  45701. const _customShaders = new WebGLShaderCache();
  45702. const _activeChannels = new Set();
  45703. const programs = [];
  45704. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  45705. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  45706. let precision = capabilities.precision;
  45707. const shaderIDs = {
  45708. MeshDepthMaterial: 'depth',
  45709. MeshDistanceMaterial: 'distanceRGBA',
  45710. MeshNormalMaterial: 'normal',
  45711. MeshBasicMaterial: 'basic',
  45712. MeshLambertMaterial: 'lambert',
  45713. MeshPhongMaterial: 'phong',
  45714. MeshToonMaterial: 'toon',
  45715. MeshStandardMaterial: 'physical',
  45716. MeshPhysicalMaterial: 'physical',
  45717. MeshMatcapMaterial: 'matcap',
  45718. LineBasicMaterial: 'basic',
  45719. LineDashedMaterial: 'dashed',
  45720. PointsMaterial: 'points',
  45721. ShadowMaterial: 'shadow',
  45722. SpriteMaterial: 'sprite'
  45723. };
  45724. function getChannel( value ) {
  45725. _activeChannels.add( value );
  45726. if ( value === 0 ) return 'uv';
  45727. return `uv${ value }`;
  45728. }
  45729. function getParameters( material, lights, shadows, scene, object ) {
  45730. const fog = scene.fog;
  45731. const geometry = object.geometry;
  45732. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  45733. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  45734. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  45735. const shaderID = shaderIDs[ material.type ];
  45736. // heuristics to create shader parameters according to lights in the scene
  45737. // (not to blow over maxLights budget)
  45738. if ( material.precision !== null ) {
  45739. precision = capabilities.getMaxPrecision( material.precision );
  45740. if ( precision !== material.precision ) {
  45741. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  45742. }
  45743. }
  45744. //
  45745. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45746. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45747. let morphTextureStride = 0;
  45748. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  45749. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  45750. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  45751. //
  45752. let vertexShader, fragmentShader;
  45753. let customVertexShaderID, customFragmentShaderID;
  45754. if ( shaderID ) {
  45755. const shader = ShaderLib[ shaderID ];
  45756. vertexShader = shader.vertexShader;
  45757. fragmentShader = shader.fragmentShader;
  45758. } else {
  45759. vertexShader = material.vertexShader;
  45760. fragmentShader = material.fragmentShader;
  45761. _customShaders.update( material );
  45762. customVertexShaderID = _customShaders.getVertexShaderID( material );
  45763. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  45764. }
  45765. const currentRenderTarget = renderer.getRenderTarget();
  45766. const reverseDepthBuffer = renderer.state.buffers.depth.getReversed();
  45767. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  45768. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  45769. const HAS_MAP = !! material.map;
  45770. const HAS_MATCAP = !! material.matcap;
  45771. const HAS_ENVMAP = !! envMap;
  45772. const HAS_AOMAP = !! material.aoMap;
  45773. const HAS_LIGHTMAP = !! material.lightMap;
  45774. const HAS_BUMPMAP = !! material.bumpMap;
  45775. const HAS_NORMALMAP = !! material.normalMap;
  45776. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  45777. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  45778. const HAS_METALNESSMAP = !! material.metalnessMap;
  45779. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  45780. const HAS_ANISOTROPY = material.anisotropy > 0;
  45781. const HAS_CLEARCOAT = material.clearcoat > 0;
  45782. const HAS_DISPERSION = material.dispersion > 0;
  45783. const HAS_IRIDESCENCE = material.iridescence > 0;
  45784. const HAS_SHEEN = material.sheen > 0;
  45785. const HAS_TRANSMISSION = material.transmission > 0;
  45786. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  45787. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  45788. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  45789. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  45790. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  45791. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  45792. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  45793. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  45794. const HAS_SPECULARMAP = !! material.specularMap;
  45795. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  45796. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  45797. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  45798. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  45799. const HAS_GRADIENTMAP = !! material.gradientMap;
  45800. const HAS_ALPHAMAP = !! material.alphaMap;
  45801. const HAS_ALPHATEST = material.alphaTest > 0;
  45802. const HAS_ALPHAHASH = !! material.alphaHash;
  45803. const HAS_EXTENSIONS = !! material.extensions;
  45804. let toneMapping = NoToneMapping;
  45805. if ( material.toneMapped ) {
  45806. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  45807. toneMapping = renderer.toneMapping;
  45808. }
  45809. }
  45810. const parameters = {
  45811. shaderID: shaderID,
  45812. shaderType: material.type,
  45813. shaderName: material.name,
  45814. vertexShader: vertexShader,
  45815. fragmentShader: fragmentShader,
  45816. defines: material.defines,
  45817. customVertexShaderID: customVertexShaderID,
  45818. customFragmentShaderID: customFragmentShaderID,
  45819. isRawShaderMaterial: material.isRawShaderMaterial === true,
  45820. glslVersion: material.glslVersion,
  45821. precision: precision,
  45822. batching: IS_BATCHEDMESH,
  45823. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  45824. instancing: IS_INSTANCEDMESH,
  45825. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  45826. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  45827. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  45828. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  45829. alphaToCoverage: !! material.alphaToCoverage,
  45830. map: HAS_MAP,
  45831. matcap: HAS_MATCAP,
  45832. envMap: HAS_ENVMAP,
  45833. envMapMode: HAS_ENVMAP && envMap.mapping,
  45834. envMapCubeUVHeight: envMapCubeUVHeight,
  45835. aoMap: HAS_AOMAP,
  45836. lightMap: HAS_LIGHTMAP,
  45837. bumpMap: HAS_BUMPMAP,
  45838. normalMap: HAS_NORMALMAP,
  45839. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  45840. emissiveMap: HAS_EMISSIVEMAP,
  45841. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  45842. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  45843. metalnessMap: HAS_METALNESSMAP,
  45844. roughnessMap: HAS_ROUGHNESSMAP,
  45845. anisotropy: HAS_ANISOTROPY,
  45846. anisotropyMap: HAS_ANISOTROPYMAP,
  45847. clearcoat: HAS_CLEARCOAT,
  45848. clearcoatMap: HAS_CLEARCOATMAP,
  45849. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  45850. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  45851. dispersion: HAS_DISPERSION,
  45852. iridescence: HAS_IRIDESCENCE,
  45853. iridescenceMap: HAS_IRIDESCENCEMAP,
  45854. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  45855. sheen: HAS_SHEEN,
  45856. sheenColorMap: HAS_SHEEN_COLORMAP,
  45857. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  45858. specularMap: HAS_SPECULARMAP,
  45859. specularColorMap: HAS_SPECULAR_COLORMAP,
  45860. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  45861. transmission: HAS_TRANSMISSION,
  45862. transmissionMap: HAS_TRANSMISSIONMAP,
  45863. thicknessMap: HAS_THICKNESSMAP,
  45864. gradientMap: HAS_GRADIENTMAP,
  45865. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  45866. alphaMap: HAS_ALPHAMAP,
  45867. alphaTest: HAS_ALPHATEST,
  45868. alphaHash: HAS_ALPHAHASH,
  45869. combine: material.combine,
  45870. //
  45871. mapUv: HAS_MAP && getChannel( material.map.channel ),
  45872. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  45873. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  45874. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  45875. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  45876. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  45877. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  45878. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  45879. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  45880. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  45881. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  45882. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  45883. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  45884. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  45885. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  45886. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  45887. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  45888. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  45889. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  45890. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  45891. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  45892. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  45893. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  45894. //
  45895. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  45896. vertexColors: material.vertexColors,
  45897. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  45898. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  45899. fog: !! fog,
  45900. useFog: material.fog === true,
  45901. fogExp2: ( !! fog && fog.isFogExp2 ),
  45902. flatShading: material.flatShading === true,
  45903. sizeAttenuation: material.sizeAttenuation === true,
  45904. logarithmicDepthBuffer: logarithmicDepthBuffer,
  45905. reverseDepthBuffer: reverseDepthBuffer,
  45906. skinning: object.isSkinnedMesh === true,
  45907. morphTargets: geometry.morphAttributes.position !== undefined,
  45908. morphNormals: geometry.morphAttributes.normal !== undefined,
  45909. morphColors: geometry.morphAttributes.color !== undefined,
  45910. morphTargetsCount: morphTargetsCount,
  45911. morphTextureStride: morphTextureStride,
  45912. numDirLights: lights.directional.length,
  45913. numPointLights: lights.point.length,
  45914. numSpotLights: lights.spot.length,
  45915. numSpotLightMaps: lights.spotLightMap.length,
  45916. numRectAreaLights: lights.rectArea.length,
  45917. numHemiLights: lights.hemi.length,
  45918. numDirLightShadows: lights.directionalShadowMap.length,
  45919. numPointLightShadows: lights.pointShadowMap.length,
  45920. numSpotLightShadows: lights.spotShadowMap.length,
  45921. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  45922. numLightProbes: lights.numLightProbes,
  45923. numClippingPlanes: clipping.numPlanes,
  45924. numClipIntersection: clipping.numIntersection,
  45925. dithering: material.dithering,
  45926. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  45927. shadowMapType: renderer.shadowMap.type,
  45928. toneMapping: toneMapping,
  45929. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  45930. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  45931. premultipliedAlpha: material.premultipliedAlpha,
  45932. doubleSided: material.side === DoubleSide,
  45933. flipSided: material.side === BackSide,
  45934. useDepthPacking: material.depthPacking >= 0,
  45935. depthPacking: material.depthPacking || 0,
  45936. index0AttributeName: material.index0AttributeName,
  45937. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  45938. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  45939. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  45940. customProgramCacheKey: material.customProgramCacheKey()
  45941. };
  45942. // the usage of getChannel() determines the active texture channels for this shader
  45943. parameters.vertexUv1s = _activeChannels.has( 1 );
  45944. parameters.vertexUv2s = _activeChannels.has( 2 );
  45945. parameters.vertexUv3s = _activeChannels.has( 3 );
  45946. _activeChannels.clear();
  45947. return parameters;
  45948. }
  45949. function getProgramCacheKey( parameters ) {
  45950. const array = [];
  45951. if ( parameters.shaderID ) {
  45952. array.push( parameters.shaderID );
  45953. } else {
  45954. array.push( parameters.customVertexShaderID );
  45955. array.push( parameters.customFragmentShaderID );
  45956. }
  45957. if ( parameters.defines !== undefined ) {
  45958. for ( const name in parameters.defines ) {
  45959. array.push( name );
  45960. array.push( parameters.defines[ name ] );
  45961. }
  45962. }
  45963. if ( parameters.isRawShaderMaterial === false ) {
  45964. getProgramCacheKeyParameters( array, parameters );
  45965. getProgramCacheKeyBooleans( array, parameters );
  45966. array.push( renderer.outputColorSpace );
  45967. }
  45968. array.push( parameters.customProgramCacheKey );
  45969. return array.join();
  45970. }
  45971. function getProgramCacheKeyParameters( array, parameters ) {
  45972. array.push( parameters.precision );
  45973. array.push( parameters.outputColorSpace );
  45974. array.push( parameters.envMapMode );
  45975. array.push( parameters.envMapCubeUVHeight );
  45976. array.push( parameters.mapUv );
  45977. array.push( parameters.alphaMapUv );
  45978. array.push( parameters.lightMapUv );
  45979. array.push( parameters.aoMapUv );
  45980. array.push( parameters.bumpMapUv );
  45981. array.push( parameters.normalMapUv );
  45982. array.push( parameters.displacementMapUv );
  45983. array.push( parameters.emissiveMapUv );
  45984. array.push( parameters.metalnessMapUv );
  45985. array.push( parameters.roughnessMapUv );
  45986. array.push( parameters.anisotropyMapUv );
  45987. array.push( parameters.clearcoatMapUv );
  45988. array.push( parameters.clearcoatNormalMapUv );
  45989. array.push( parameters.clearcoatRoughnessMapUv );
  45990. array.push( parameters.iridescenceMapUv );
  45991. array.push( parameters.iridescenceThicknessMapUv );
  45992. array.push( parameters.sheenColorMapUv );
  45993. array.push( parameters.sheenRoughnessMapUv );
  45994. array.push( parameters.specularMapUv );
  45995. array.push( parameters.specularColorMapUv );
  45996. array.push( parameters.specularIntensityMapUv );
  45997. array.push( parameters.transmissionMapUv );
  45998. array.push( parameters.thicknessMapUv );
  45999. array.push( parameters.combine );
  46000. array.push( parameters.fogExp2 );
  46001. array.push( parameters.sizeAttenuation );
  46002. array.push( parameters.morphTargetsCount );
  46003. array.push( parameters.morphAttributeCount );
  46004. array.push( parameters.numDirLights );
  46005. array.push( parameters.numPointLights );
  46006. array.push( parameters.numSpotLights );
  46007. array.push( parameters.numSpotLightMaps );
  46008. array.push( parameters.numHemiLights );
  46009. array.push( parameters.numRectAreaLights );
  46010. array.push( parameters.numDirLightShadows );
  46011. array.push( parameters.numPointLightShadows );
  46012. array.push( parameters.numSpotLightShadows );
  46013. array.push( parameters.numSpotLightShadowsWithMaps );
  46014. array.push( parameters.numLightProbes );
  46015. array.push( parameters.shadowMapType );
  46016. array.push( parameters.toneMapping );
  46017. array.push( parameters.numClippingPlanes );
  46018. array.push( parameters.numClipIntersection );
  46019. array.push( parameters.depthPacking );
  46020. }
  46021. function getProgramCacheKeyBooleans( array, parameters ) {
  46022. _programLayers.disableAll();
  46023. if ( parameters.supportsVertexTextures )
  46024. _programLayers.enable( 0 );
  46025. if ( parameters.instancing )
  46026. _programLayers.enable( 1 );
  46027. if ( parameters.instancingColor )
  46028. _programLayers.enable( 2 );
  46029. if ( parameters.instancingMorph )
  46030. _programLayers.enable( 3 );
  46031. if ( parameters.matcap )
  46032. _programLayers.enable( 4 );
  46033. if ( parameters.envMap )
  46034. _programLayers.enable( 5 );
  46035. if ( parameters.normalMapObjectSpace )
  46036. _programLayers.enable( 6 );
  46037. if ( parameters.normalMapTangentSpace )
  46038. _programLayers.enable( 7 );
  46039. if ( parameters.clearcoat )
  46040. _programLayers.enable( 8 );
  46041. if ( parameters.iridescence )
  46042. _programLayers.enable( 9 );
  46043. if ( parameters.alphaTest )
  46044. _programLayers.enable( 10 );
  46045. if ( parameters.vertexColors )
  46046. _programLayers.enable( 11 );
  46047. if ( parameters.vertexAlphas )
  46048. _programLayers.enable( 12 );
  46049. if ( parameters.vertexUv1s )
  46050. _programLayers.enable( 13 );
  46051. if ( parameters.vertexUv2s )
  46052. _programLayers.enable( 14 );
  46053. if ( parameters.vertexUv3s )
  46054. _programLayers.enable( 15 );
  46055. if ( parameters.vertexTangents )
  46056. _programLayers.enable( 16 );
  46057. if ( parameters.anisotropy )
  46058. _programLayers.enable( 17 );
  46059. if ( parameters.alphaHash )
  46060. _programLayers.enable( 18 );
  46061. if ( parameters.batching )
  46062. _programLayers.enable( 19 );
  46063. if ( parameters.dispersion )
  46064. _programLayers.enable( 20 );
  46065. if ( parameters.batchingColor )
  46066. _programLayers.enable( 21 );
  46067. array.push( _programLayers.mask );
  46068. _programLayers.disableAll();
  46069. if ( parameters.fog )
  46070. _programLayers.enable( 0 );
  46071. if ( parameters.useFog )
  46072. _programLayers.enable( 1 );
  46073. if ( parameters.flatShading )
  46074. _programLayers.enable( 2 );
  46075. if ( parameters.logarithmicDepthBuffer )
  46076. _programLayers.enable( 3 );
  46077. if ( parameters.reverseDepthBuffer )
  46078. _programLayers.enable( 4 );
  46079. if ( parameters.skinning )
  46080. _programLayers.enable( 5 );
  46081. if ( parameters.morphTargets )
  46082. _programLayers.enable( 6 );
  46083. if ( parameters.morphNormals )
  46084. _programLayers.enable( 7 );
  46085. if ( parameters.morphColors )
  46086. _programLayers.enable( 8 );
  46087. if ( parameters.premultipliedAlpha )
  46088. _programLayers.enable( 9 );
  46089. if ( parameters.shadowMapEnabled )
  46090. _programLayers.enable( 10 );
  46091. if ( parameters.doubleSided )
  46092. _programLayers.enable( 11 );
  46093. if ( parameters.flipSided )
  46094. _programLayers.enable( 12 );
  46095. if ( parameters.useDepthPacking )
  46096. _programLayers.enable( 13 );
  46097. if ( parameters.dithering )
  46098. _programLayers.enable( 14 );
  46099. if ( parameters.transmission )
  46100. _programLayers.enable( 15 );
  46101. if ( parameters.sheen )
  46102. _programLayers.enable( 16 );
  46103. if ( parameters.opaque )
  46104. _programLayers.enable( 17 );
  46105. if ( parameters.pointsUvs )
  46106. _programLayers.enable( 18 );
  46107. if ( parameters.decodeVideoTexture )
  46108. _programLayers.enable( 19 );
  46109. if ( parameters.decodeVideoTextureEmissive )
  46110. _programLayers.enable( 20 );
  46111. if ( parameters.alphaToCoverage )
  46112. _programLayers.enable( 21 );
  46113. array.push( _programLayers.mask );
  46114. }
  46115. function getUniforms( material ) {
  46116. const shaderID = shaderIDs[ material.type ];
  46117. let uniforms;
  46118. if ( shaderID ) {
  46119. const shader = ShaderLib[ shaderID ];
  46120. uniforms = UniformsUtils.clone( shader.uniforms );
  46121. } else {
  46122. uniforms = material.uniforms;
  46123. }
  46124. return uniforms;
  46125. }
  46126. function acquireProgram( parameters, cacheKey ) {
  46127. let program;
  46128. // Check if code has been already compiled
  46129. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  46130. const preexistingProgram = programs[ p ];
  46131. if ( preexistingProgram.cacheKey === cacheKey ) {
  46132. program = preexistingProgram;
  46133. ++ program.usedTimes;
  46134. break;
  46135. }
  46136. }
  46137. if ( program === undefined ) {
  46138. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  46139. programs.push( program );
  46140. }
  46141. return program;
  46142. }
  46143. function releaseProgram( program ) {
  46144. if ( -- program.usedTimes === 0 ) {
  46145. // Remove from unordered set
  46146. const i = programs.indexOf( program );
  46147. programs[ i ] = programs[ programs.length - 1 ];
  46148. programs.pop();
  46149. // Free WebGL resources
  46150. program.destroy();
  46151. }
  46152. }
  46153. function releaseShaderCache( material ) {
  46154. _customShaders.remove( material );
  46155. }
  46156. function dispose() {
  46157. _customShaders.dispose();
  46158. }
  46159. return {
  46160. getParameters: getParameters,
  46161. getProgramCacheKey: getProgramCacheKey,
  46162. getUniforms: getUniforms,
  46163. acquireProgram: acquireProgram,
  46164. releaseProgram: releaseProgram,
  46165. releaseShaderCache: releaseShaderCache,
  46166. // Exposed for resource monitoring & error feedback via renderer.info:
  46167. programs: programs,
  46168. dispose: dispose
  46169. };
  46170. }
  46171. function WebGLProperties() {
  46172. let properties = new WeakMap();
  46173. function has( object ) {
  46174. return properties.has( object );
  46175. }
  46176. function get( object ) {
  46177. let map = properties.get( object );
  46178. if ( map === undefined ) {
  46179. map = {};
  46180. properties.set( object, map );
  46181. }
  46182. return map;
  46183. }
  46184. function remove( object ) {
  46185. properties.delete( object );
  46186. }
  46187. function update( object, key, value ) {
  46188. properties.get( object )[ key ] = value;
  46189. }
  46190. function dispose() {
  46191. properties = new WeakMap();
  46192. }
  46193. return {
  46194. has: has,
  46195. get: get,
  46196. remove: remove,
  46197. update: update,
  46198. dispose: dispose
  46199. };
  46200. }
  46201. function painterSortStable( a, b ) {
  46202. if ( a.groupOrder !== b.groupOrder ) {
  46203. return a.groupOrder - b.groupOrder;
  46204. } else if ( a.renderOrder !== b.renderOrder ) {
  46205. return a.renderOrder - b.renderOrder;
  46206. } else if ( a.material.id !== b.material.id ) {
  46207. return a.material.id - b.material.id;
  46208. } else if ( a.z !== b.z ) {
  46209. return a.z - b.z;
  46210. } else {
  46211. return a.id - b.id;
  46212. }
  46213. }
  46214. function reversePainterSortStable( a, b ) {
  46215. if ( a.groupOrder !== b.groupOrder ) {
  46216. return a.groupOrder - b.groupOrder;
  46217. } else if ( a.renderOrder !== b.renderOrder ) {
  46218. return a.renderOrder - b.renderOrder;
  46219. } else if ( a.z !== b.z ) {
  46220. return b.z - a.z;
  46221. } else {
  46222. return a.id - b.id;
  46223. }
  46224. }
  46225. function WebGLRenderList() {
  46226. const renderItems = [];
  46227. let renderItemsIndex = 0;
  46228. const opaque = [];
  46229. const transmissive = [];
  46230. const transparent = [];
  46231. function init() {
  46232. renderItemsIndex = 0;
  46233. opaque.length = 0;
  46234. transmissive.length = 0;
  46235. transparent.length = 0;
  46236. }
  46237. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  46238. let renderItem = renderItems[ renderItemsIndex ];
  46239. if ( renderItem === undefined ) {
  46240. renderItem = {
  46241. id: object.id,
  46242. object: object,
  46243. geometry: geometry,
  46244. material: material,
  46245. groupOrder: groupOrder,
  46246. renderOrder: object.renderOrder,
  46247. z: z,
  46248. group: group
  46249. };
  46250. renderItems[ renderItemsIndex ] = renderItem;
  46251. } else {
  46252. renderItem.id = object.id;
  46253. renderItem.object = object;
  46254. renderItem.geometry = geometry;
  46255. renderItem.material = material;
  46256. renderItem.groupOrder = groupOrder;
  46257. renderItem.renderOrder = object.renderOrder;
  46258. renderItem.z = z;
  46259. renderItem.group = group;
  46260. }
  46261. renderItemsIndex ++;
  46262. return renderItem;
  46263. }
  46264. function push( object, geometry, material, groupOrder, z, group ) {
  46265. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  46266. if ( material.transmission > 0.0 ) {
  46267. transmissive.push( renderItem );
  46268. } else if ( material.transparent === true ) {
  46269. transparent.push( renderItem );
  46270. } else {
  46271. opaque.push( renderItem );
  46272. }
  46273. }
  46274. function unshift( object, geometry, material, groupOrder, z, group ) {
  46275. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  46276. if ( material.transmission > 0.0 ) {
  46277. transmissive.unshift( renderItem );
  46278. } else if ( material.transparent === true ) {
  46279. transparent.unshift( renderItem );
  46280. } else {
  46281. opaque.unshift( renderItem );
  46282. }
  46283. }
  46284. function sort( customOpaqueSort, customTransparentSort ) {
  46285. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  46286. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  46287. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  46288. }
  46289. function finish() {
  46290. // Clear references from inactive renderItems in the list
  46291. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  46292. const renderItem = renderItems[ i ];
  46293. if ( renderItem.id === null ) break;
  46294. renderItem.id = null;
  46295. renderItem.object = null;
  46296. renderItem.geometry = null;
  46297. renderItem.material = null;
  46298. renderItem.group = null;
  46299. }
  46300. }
  46301. return {
  46302. opaque: opaque,
  46303. transmissive: transmissive,
  46304. transparent: transparent,
  46305. init: init,
  46306. push: push,
  46307. unshift: unshift,
  46308. finish: finish,
  46309. sort: sort
  46310. };
  46311. }
  46312. function WebGLRenderLists() {
  46313. let lists = new WeakMap();
  46314. function get( scene, renderCallDepth ) {
  46315. const listArray = lists.get( scene );
  46316. let list;
  46317. if ( listArray === undefined ) {
  46318. list = new WebGLRenderList();
  46319. lists.set( scene, [ list ] );
  46320. } else {
  46321. if ( renderCallDepth >= listArray.length ) {
  46322. list = new WebGLRenderList();
  46323. listArray.push( list );
  46324. } else {
  46325. list = listArray[ renderCallDepth ];
  46326. }
  46327. }
  46328. return list;
  46329. }
  46330. function dispose() {
  46331. lists = new WeakMap();
  46332. }
  46333. return {
  46334. get: get,
  46335. dispose: dispose
  46336. };
  46337. }
  46338. function UniformsCache() {
  46339. const lights = {};
  46340. return {
  46341. get: function ( light ) {
  46342. if ( lights[ light.id ] !== undefined ) {
  46343. return lights[ light.id ];
  46344. }
  46345. let uniforms;
  46346. switch ( light.type ) {
  46347. case 'DirectionalLight':
  46348. uniforms = {
  46349. direction: new Vector3(),
  46350. color: new Color()
  46351. };
  46352. break;
  46353. case 'SpotLight':
  46354. uniforms = {
  46355. position: new Vector3(),
  46356. direction: new Vector3(),
  46357. color: new Color(),
  46358. distance: 0,
  46359. coneCos: 0,
  46360. penumbraCos: 0,
  46361. decay: 0
  46362. };
  46363. break;
  46364. case 'PointLight':
  46365. uniforms = {
  46366. position: new Vector3(),
  46367. color: new Color(),
  46368. distance: 0,
  46369. decay: 0
  46370. };
  46371. break;
  46372. case 'HemisphereLight':
  46373. uniforms = {
  46374. direction: new Vector3(),
  46375. skyColor: new Color(),
  46376. groundColor: new Color()
  46377. };
  46378. break;
  46379. case 'RectAreaLight':
  46380. uniforms = {
  46381. color: new Color(),
  46382. position: new Vector3(),
  46383. halfWidth: new Vector3(),
  46384. halfHeight: new Vector3()
  46385. };
  46386. break;
  46387. }
  46388. lights[ light.id ] = uniforms;
  46389. return uniforms;
  46390. }
  46391. };
  46392. }
  46393. function ShadowUniformsCache() {
  46394. const lights = {};
  46395. return {
  46396. get: function ( light ) {
  46397. if ( lights[ light.id ] !== undefined ) {
  46398. return lights[ light.id ];
  46399. }
  46400. let uniforms;
  46401. switch ( light.type ) {
  46402. case 'DirectionalLight':
  46403. uniforms = {
  46404. shadowIntensity: 1,
  46405. shadowBias: 0,
  46406. shadowNormalBias: 0,
  46407. shadowRadius: 1,
  46408. shadowMapSize: new Vector2()
  46409. };
  46410. break;
  46411. case 'SpotLight':
  46412. uniforms = {
  46413. shadowIntensity: 1,
  46414. shadowBias: 0,
  46415. shadowNormalBias: 0,
  46416. shadowRadius: 1,
  46417. shadowMapSize: new Vector2()
  46418. };
  46419. break;
  46420. case 'PointLight':
  46421. uniforms = {
  46422. shadowIntensity: 1,
  46423. shadowBias: 0,
  46424. shadowNormalBias: 0,
  46425. shadowRadius: 1,
  46426. shadowMapSize: new Vector2(),
  46427. shadowCameraNear: 1,
  46428. shadowCameraFar: 1000
  46429. };
  46430. break;
  46431. // TODO (abelnation): set RectAreaLight shadow uniforms
  46432. }
  46433. lights[ light.id ] = uniforms;
  46434. return uniforms;
  46435. }
  46436. };
  46437. }
  46438. let nextVersion = 0;
  46439. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  46440. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  46441. }
  46442. function WebGLLights( extensions ) {
  46443. const cache = new UniformsCache();
  46444. const shadowCache = ShadowUniformsCache();
  46445. const state = {
  46446. version: 0,
  46447. hash: {
  46448. directionalLength: - 1,
  46449. pointLength: - 1,
  46450. spotLength: - 1,
  46451. rectAreaLength: - 1,
  46452. hemiLength: - 1,
  46453. numDirectionalShadows: - 1,
  46454. numPointShadows: - 1,
  46455. numSpotShadows: - 1,
  46456. numSpotMaps: - 1,
  46457. numLightProbes: - 1
  46458. },
  46459. ambient: [ 0, 0, 0 ],
  46460. probe: [],
  46461. directional: [],
  46462. directionalShadow: [],
  46463. directionalShadowMap: [],
  46464. directionalShadowMatrix: [],
  46465. spot: [],
  46466. spotLightMap: [],
  46467. spotShadow: [],
  46468. spotShadowMap: [],
  46469. spotLightMatrix: [],
  46470. rectArea: [],
  46471. rectAreaLTC1: null,
  46472. rectAreaLTC2: null,
  46473. point: [],
  46474. pointShadow: [],
  46475. pointShadowMap: [],
  46476. pointShadowMatrix: [],
  46477. hemi: [],
  46478. numSpotLightShadowsWithMaps: 0,
  46479. numLightProbes: 0
  46480. };
  46481. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  46482. const vector3 = new Vector3();
  46483. const matrix4 = new Matrix4();
  46484. const matrix42 = new Matrix4();
  46485. function setup( lights ) {
  46486. let r = 0, g = 0, b = 0;
  46487. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  46488. let directionalLength = 0;
  46489. let pointLength = 0;
  46490. let spotLength = 0;
  46491. let rectAreaLength = 0;
  46492. let hemiLength = 0;
  46493. let numDirectionalShadows = 0;
  46494. let numPointShadows = 0;
  46495. let numSpotShadows = 0;
  46496. let numSpotMaps = 0;
  46497. let numSpotShadowsWithMaps = 0;
  46498. let numLightProbes = 0;
  46499. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  46500. lights.sort( shadowCastingAndTexturingLightsFirst );
  46501. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  46502. const light = lights[ i ];
  46503. const color = light.color;
  46504. const intensity = light.intensity;
  46505. const distance = light.distance;
  46506. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  46507. if ( light.isAmbientLight ) {
  46508. r += color.r * intensity;
  46509. g += color.g * intensity;
  46510. b += color.b * intensity;
  46511. } else if ( light.isLightProbe ) {
  46512. for ( let j = 0; j < 9; j ++ ) {
  46513. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  46514. }
  46515. numLightProbes ++;
  46516. } else if ( light.isDirectionalLight ) {
  46517. const uniforms = cache.get( light );
  46518. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  46519. if ( light.castShadow ) {
  46520. const shadow = light.shadow;
  46521. const shadowUniforms = shadowCache.get( light );
  46522. shadowUniforms.shadowIntensity = shadow.intensity;
  46523. shadowUniforms.shadowBias = shadow.bias;
  46524. shadowUniforms.shadowNormalBias = shadow.normalBias;
  46525. shadowUniforms.shadowRadius = shadow.radius;
  46526. shadowUniforms.shadowMapSize = shadow.mapSize;
  46527. state.directionalShadow[ directionalLength ] = shadowUniforms;
  46528. state.directionalShadowMap[ directionalLength ] = shadowMap;
  46529. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  46530. numDirectionalShadows ++;
  46531. }
  46532. state.directional[ directionalLength ] = uniforms;
  46533. directionalLength ++;
  46534. } else if ( light.isSpotLight ) {
  46535. const uniforms = cache.get( light );
  46536. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  46537. uniforms.color.copy( color ).multiplyScalar( intensity );
  46538. uniforms.distance = distance;
  46539. uniforms.coneCos = Math.cos( light.angle );
  46540. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  46541. uniforms.decay = light.decay;
  46542. state.spot[ spotLength ] = uniforms;
  46543. const shadow = light.shadow;
  46544. if ( light.map ) {
  46545. state.spotLightMap[ numSpotMaps ] = light.map;
  46546. numSpotMaps ++;
  46547. // make sure the lightMatrix is up to date
  46548. // TODO : do it if required only
  46549. shadow.updateMatrices( light );
  46550. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  46551. }
  46552. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  46553. if ( light.castShadow ) {
  46554. const shadowUniforms = shadowCache.get( light );
  46555. shadowUniforms.shadowIntensity = shadow.intensity;
  46556. shadowUniforms.shadowBias = shadow.bias;
  46557. shadowUniforms.shadowNormalBias = shadow.normalBias;
  46558. shadowUniforms.shadowRadius = shadow.radius;
  46559. shadowUniforms.shadowMapSize = shadow.mapSize;
  46560. state.spotShadow[ spotLength ] = shadowUniforms;
  46561. state.spotShadowMap[ spotLength ] = shadowMap;
  46562. numSpotShadows ++;
  46563. }
  46564. spotLength ++;
  46565. } else if ( light.isRectAreaLight ) {
  46566. const uniforms = cache.get( light );
  46567. uniforms.color.copy( color ).multiplyScalar( intensity );
  46568. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  46569. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  46570. state.rectArea[ rectAreaLength ] = uniforms;
  46571. rectAreaLength ++;
  46572. } else if ( light.isPointLight ) {
  46573. const uniforms = cache.get( light );
  46574. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  46575. uniforms.distance = light.distance;
  46576. uniforms.decay = light.decay;
  46577. if ( light.castShadow ) {
  46578. const shadow = light.shadow;
  46579. const shadowUniforms = shadowCache.get( light );
  46580. shadowUniforms.shadowIntensity = shadow.intensity;
  46581. shadowUniforms.shadowBias = shadow.bias;
  46582. shadowUniforms.shadowNormalBias = shadow.normalBias;
  46583. shadowUniforms.shadowRadius = shadow.radius;
  46584. shadowUniforms.shadowMapSize = shadow.mapSize;
  46585. shadowUniforms.shadowCameraNear = shadow.camera.near;
  46586. shadowUniforms.shadowCameraFar = shadow.camera.far;
  46587. state.pointShadow[ pointLength ] = shadowUniforms;
  46588. state.pointShadowMap[ pointLength ] = shadowMap;
  46589. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  46590. numPointShadows ++;
  46591. }
  46592. state.point[ pointLength ] = uniforms;
  46593. pointLength ++;
  46594. } else if ( light.isHemisphereLight ) {
  46595. const uniforms = cache.get( light );
  46596. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  46597. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  46598. state.hemi[ hemiLength ] = uniforms;
  46599. hemiLength ++;
  46600. }
  46601. }
  46602. if ( rectAreaLength > 0 ) {
  46603. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  46604. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  46605. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  46606. } else {
  46607. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  46608. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  46609. }
  46610. }
  46611. state.ambient[ 0 ] = r;
  46612. state.ambient[ 1 ] = g;
  46613. state.ambient[ 2 ] = b;
  46614. const hash = state.hash;
  46615. if ( hash.directionalLength !== directionalLength ||
  46616. hash.pointLength !== pointLength ||
  46617. hash.spotLength !== spotLength ||
  46618. hash.rectAreaLength !== rectAreaLength ||
  46619. hash.hemiLength !== hemiLength ||
  46620. hash.numDirectionalShadows !== numDirectionalShadows ||
  46621. hash.numPointShadows !== numPointShadows ||
  46622. hash.numSpotShadows !== numSpotShadows ||
  46623. hash.numSpotMaps !== numSpotMaps ||
  46624. hash.numLightProbes !== numLightProbes ) {
  46625. state.directional.length = directionalLength;
  46626. state.spot.length = spotLength;
  46627. state.rectArea.length = rectAreaLength;
  46628. state.point.length = pointLength;
  46629. state.hemi.length = hemiLength;
  46630. state.directionalShadow.length = numDirectionalShadows;
  46631. state.directionalShadowMap.length = numDirectionalShadows;
  46632. state.pointShadow.length = numPointShadows;
  46633. state.pointShadowMap.length = numPointShadows;
  46634. state.spotShadow.length = numSpotShadows;
  46635. state.spotShadowMap.length = numSpotShadows;
  46636. state.directionalShadowMatrix.length = numDirectionalShadows;
  46637. state.pointShadowMatrix.length = numPointShadows;
  46638. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  46639. state.spotLightMap.length = numSpotMaps;
  46640. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  46641. state.numLightProbes = numLightProbes;
  46642. hash.directionalLength = directionalLength;
  46643. hash.pointLength = pointLength;
  46644. hash.spotLength = spotLength;
  46645. hash.rectAreaLength = rectAreaLength;
  46646. hash.hemiLength = hemiLength;
  46647. hash.numDirectionalShadows = numDirectionalShadows;
  46648. hash.numPointShadows = numPointShadows;
  46649. hash.numSpotShadows = numSpotShadows;
  46650. hash.numSpotMaps = numSpotMaps;
  46651. hash.numLightProbes = numLightProbes;
  46652. state.version = nextVersion ++;
  46653. }
  46654. }
  46655. function setupView( lights, camera ) {
  46656. let directionalLength = 0;
  46657. let pointLength = 0;
  46658. let spotLength = 0;
  46659. let rectAreaLength = 0;
  46660. let hemiLength = 0;
  46661. const viewMatrix = camera.matrixWorldInverse;
  46662. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  46663. const light = lights[ i ];
  46664. if ( light.isDirectionalLight ) {
  46665. const uniforms = state.directional[ directionalLength ];
  46666. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  46667. vector3.setFromMatrixPosition( light.target.matrixWorld );
  46668. uniforms.direction.sub( vector3 );
  46669. uniforms.direction.transformDirection( viewMatrix );
  46670. directionalLength ++;
  46671. } else if ( light.isSpotLight ) {
  46672. const uniforms = state.spot[ spotLength ];
  46673. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  46674. uniforms.position.applyMatrix4( viewMatrix );
  46675. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  46676. vector3.setFromMatrixPosition( light.target.matrixWorld );
  46677. uniforms.direction.sub( vector3 );
  46678. uniforms.direction.transformDirection( viewMatrix );
  46679. spotLength ++;
  46680. } else if ( light.isRectAreaLight ) {
  46681. const uniforms = state.rectArea[ rectAreaLength ];
  46682. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  46683. uniforms.position.applyMatrix4( viewMatrix );
  46684. // extract local rotation of light to derive width/height half vectors
  46685. matrix42.identity();
  46686. matrix4.copy( light.matrixWorld );
  46687. matrix4.premultiply( viewMatrix );
  46688. matrix42.extractRotation( matrix4 );
  46689. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  46690. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  46691. uniforms.halfWidth.applyMatrix4( matrix42 );
  46692. uniforms.halfHeight.applyMatrix4( matrix42 );
  46693. rectAreaLength ++;
  46694. } else if ( light.isPointLight ) {
  46695. const uniforms = state.point[ pointLength ];
  46696. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  46697. uniforms.position.applyMatrix4( viewMatrix );
  46698. pointLength ++;
  46699. } else if ( light.isHemisphereLight ) {
  46700. const uniforms = state.hemi[ hemiLength ];
  46701. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  46702. uniforms.direction.transformDirection( viewMatrix );
  46703. hemiLength ++;
  46704. }
  46705. }
  46706. }
  46707. return {
  46708. setup: setup,
  46709. setupView: setupView,
  46710. state: state
  46711. };
  46712. }
  46713. function WebGLRenderState( extensions ) {
  46714. const lights = new WebGLLights( extensions );
  46715. const lightsArray = [];
  46716. const shadowsArray = [];
  46717. function init( camera ) {
  46718. state.camera = camera;
  46719. lightsArray.length = 0;
  46720. shadowsArray.length = 0;
  46721. }
  46722. function pushLight( light ) {
  46723. lightsArray.push( light );
  46724. }
  46725. function pushShadow( shadowLight ) {
  46726. shadowsArray.push( shadowLight );
  46727. }
  46728. function setupLights() {
  46729. lights.setup( lightsArray );
  46730. }
  46731. function setupLightsView( camera ) {
  46732. lights.setupView( lightsArray, camera );
  46733. }
  46734. const state = {
  46735. lightsArray: lightsArray,
  46736. shadowsArray: shadowsArray,
  46737. camera: null,
  46738. lights: lights,
  46739. transmissionRenderTarget: {}
  46740. };
  46741. return {
  46742. init: init,
  46743. state: state,
  46744. setupLights: setupLights,
  46745. setupLightsView: setupLightsView,
  46746. pushLight: pushLight,
  46747. pushShadow: pushShadow
  46748. };
  46749. }
  46750. function WebGLRenderStates( extensions ) {
  46751. let renderStates = new WeakMap();
  46752. function get( scene, renderCallDepth = 0 ) {
  46753. const renderStateArray = renderStates.get( scene );
  46754. let renderState;
  46755. if ( renderStateArray === undefined ) {
  46756. renderState = new WebGLRenderState( extensions );
  46757. renderStates.set( scene, [ renderState ] );
  46758. } else {
  46759. if ( renderCallDepth >= renderStateArray.length ) {
  46760. renderState = new WebGLRenderState( extensions );
  46761. renderStateArray.push( renderState );
  46762. } else {
  46763. renderState = renderStateArray[ renderCallDepth ];
  46764. }
  46765. }
  46766. return renderState;
  46767. }
  46768. function dispose() {
  46769. renderStates = new WeakMap();
  46770. }
  46771. return {
  46772. get: get,
  46773. dispose: dispose
  46774. };
  46775. }
  46776. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  46777. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\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 = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\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 = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\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( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  46778. function WebGLShadowMap( renderer, objects, capabilities ) {
  46779. let _frustum = new Frustum();
  46780. const _shadowMapSize = new Vector2(),
  46781. _viewportSize = new Vector2(),
  46782. _viewport = new Vector4(),
  46783. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  46784. _distanceMaterial = new MeshDistanceMaterial(),
  46785. _materialCache = {},
  46786. _maxTextureSize = capabilities.maxTextureSize;
  46787. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  46788. const shadowMaterialVertical = new ShaderMaterial( {
  46789. defines: {
  46790. VSM_SAMPLES: 8
  46791. },
  46792. uniforms: {
  46793. shadow_pass: { value: null },
  46794. resolution: { value: new Vector2() },
  46795. radius: { value: 4.0 }
  46796. },
  46797. vertexShader: vertex,
  46798. fragmentShader: fragment
  46799. } );
  46800. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  46801. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  46802. const fullScreenTri = new BufferGeometry();
  46803. fullScreenTri.setAttribute(
  46804. 'position',
  46805. new BufferAttribute(
  46806. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  46807. 3
  46808. )
  46809. );
  46810. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  46811. const scope = this;
  46812. this.enabled = false;
  46813. this.autoUpdate = true;
  46814. this.needsUpdate = false;
  46815. this.type = PCFShadowMap;
  46816. let _previousType = this.type;
  46817. this.render = function ( lights, scene, camera ) {
  46818. if ( scope.enabled === false ) return;
  46819. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  46820. if ( lights.length === 0 ) return;
  46821. const currentRenderTarget = renderer.getRenderTarget();
  46822. const activeCubeFace = renderer.getActiveCubeFace();
  46823. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  46824. const _state = renderer.state;
  46825. // Set GL state for depth map.
  46826. _state.setBlending( NoBlending );
  46827. _state.buffers.color.setClear( 1, 1, 1, 1 );
  46828. _state.buffers.depth.setTest( true );
  46829. _state.setScissorTest( false );
  46830. // check for shadow map type changes
  46831. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  46832. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  46833. // render depth map
  46834. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  46835. const light = lights[ i ];
  46836. const shadow = light.shadow;
  46837. if ( shadow === undefined ) {
  46838. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  46839. continue;
  46840. }
  46841. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  46842. _shadowMapSize.copy( shadow.mapSize );
  46843. const shadowFrameExtents = shadow.getFrameExtents();
  46844. _shadowMapSize.multiply( shadowFrameExtents );
  46845. _viewportSize.copy( shadow.mapSize );
  46846. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  46847. if ( _shadowMapSize.x > _maxTextureSize ) {
  46848. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  46849. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  46850. shadow.mapSize.x = _viewportSize.x;
  46851. }
  46852. if ( _shadowMapSize.y > _maxTextureSize ) {
  46853. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  46854. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  46855. shadow.mapSize.y = _viewportSize.y;
  46856. }
  46857. }
  46858. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  46859. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  46860. if ( shadow.map !== null ) {
  46861. shadow.map.dispose();
  46862. }
  46863. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  46864. shadow.map.texture.name = light.name + '.shadowMap';
  46865. shadow.camera.updateProjectionMatrix();
  46866. }
  46867. renderer.setRenderTarget( shadow.map );
  46868. renderer.clear();
  46869. const viewportCount = shadow.getViewportCount();
  46870. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  46871. const viewport = shadow.getViewport( vp );
  46872. _viewport.set(
  46873. _viewportSize.x * viewport.x,
  46874. _viewportSize.y * viewport.y,
  46875. _viewportSize.x * viewport.z,
  46876. _viewportSize.y * viewport.w
  46877. );
  46878. _state.viewport( _viewport );
  46879. shadow.updateMatrices( light, vp );
  46880. _frustum = shadow.getFrustum();
  46881. renderObject( scene, camera, shadow.camera, light, this.type );
  46882. }
  46883. // do blur pass for VSM
  46884. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  46885. VSMPass( shadow, camera );
  46886. }
  46887. shadow.needsUpdate = false;
  46888. }
  46889. _previousType = this.type;
  46890. scope.needsUpdate = false;
  46891. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  46892. };
  46893. function VSMPass( shadow, camera ) {
  46894. const geometry = objects.update( fullScreenMesh );
  46895. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  46896. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  46897. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  46898. shadowMaterialVertical.needsUpdate = true;
  46899. shadowMaterialHorizontal.needsUpdate = true;
  46900. }
  46901. if ( shadow.mapPass === null ) {
  46902. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  46903. }
  46904. // vertical pass
  46905. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  46906. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  46907. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  46908. renderer.setRenderTarget( shadow.mapPass );
  46909. renderer.clear();
  46910. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  46911. // horizontal pass
  46912. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  46913. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  46914. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  46915. renderer.setRenderTarget( shadow.map );
  46916. renderer.clear();
  46917. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  46918. }
  46919. function getDepthMaterial( object, material, light, type ) {
  46920. let result = null;
  46921. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  46922. if ( customMaterial !== undefined ) {
  46923. result = customMaterial;
  46924. } else {
  46925. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  46926. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  46927. ( material.displacementMap && material.displacementScale !== 0 ) ||
  46928. ( material.alphaMap && material.alphaTest > 0 ) ||
  46929. ( material.map && material.alphaTest > 0 ) ) {
  46930. // in this case we need a unique material instance reflecting the
  46931. // appropriate state
  46932. const keyA = result.uuid, keyB = material.uuid;
  46933. let materialsForVariant = _materialCache[ keyA ];
  46934. if ( materialsForVariant === undefined ) {
  46935. materialsForVariant = {};
  46936. _materialCache[ keyA ] = materialsForVariant;
  46937. }
  46938. let cachedMaterial = materialsForVariant[ keyB ];
  46939. if ( cachedMaterial === undefined ) {
  46940. cachedMaterial = result.clone();
  46941. materialsForVariant[ keyB ] = cachedMaterial;
  46942. material.addEventListener( 'dispose', onMaterialDispose );
  46943. }
  46944. result = cachedMaterial;
  46945. }
  46946. }
  46947. result.visible = material.visible;
  46948. result.wireframe = material.wireframe;
  46949. if ( type === VSMShadowMap ) {
  46950. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  46951. } else {
  46952. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  46953. }
  46954. result.alphaMap = material.alphaMap;
  46955. result.alphaTest = material.alphaTest;
  46956. result.map = material.map;
  46957. result.clipShadows = material.clipShadows;
  46958. result.clippingPlanes = material.clippingPlanes;
  46959. result.clipIntersection = material.clipIntersection;
  46960. result.displacementMap = material.displacementMap;
  46961. result.displacementScale = material.displacementScale;
  46962. result.displacementBias = material.displacementBias;
  46963. result.wireframeLinewidth = material.wireframeLinewidth;
  46964. result.linewidth = material.linewidth;
  46965. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  46966. const materialProperties = renderer.properties.get( result );
  46967. materialProperties.light = light;
  46968. }
  46969. return result;
  46970. }
  46971. function renderObject( object, camera, shadowCamera, light, type ) {
  46972. if ( object.visible === false ) return;
  46973. const visible = object.layers.test( camera.layers );
  46974. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  46975. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  46976. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  46977. const geometry = objects.update( object );
  46978. const material = object.material;
  46979. if ( Array.isArray( material ) ) {
  46980. const groups = geometry.groups;
  46981. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  46982. const group = groups[ k ];
  46983. const groupMaterial = material[ group.materialIndex ];
  46984. if ( groupMaterial && groupMaterial.visible ) {
  46985. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  46986. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  46987. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  46988. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  46989. }
  46990. }
  46991. } else if ( material.visible ) {
  46992. const depthMaterial = getDepthMaterial( object, material, light, type );
  46993. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  46994. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  46995. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  46996. }
  46997. }
  46998. }
  46999. const children = object.children;
  47000. for ( let i = 0, l = children.length; i < l; i ++ ) {
  47001. renderObject( children[ i ], camera, shadowCamera, light, type );
  47002. }
  47003. }
  47004. function onMaterialDispose( event ) {
  47005. const material = event.target;
  47006. material.removeEventListener( 'dispose', onMaterialDispose );
  47007. // make sure to remove the unique distance/depth materials used for shadow map rendering
  47008. for ( const id in _materialCache ) {
  47009. const cache = _materialCache[ id ];
  47010. const uuid = event.target.uuid;
  47011. if ( uuid in cache ) {
  47012. const shadowMaterial = cache[ uuid ];
  47013. shadowMaterial.dispose();
  47014. delete cache[ uuid ];
  47015. }
  47016. }
  47017. }
  47018. }
  47019. const reversedFuncs = {
  47020. [ NeverDepth ]: AlwaysDepth,
  47021. [ LessDepth ]: GreaterDepth,
  47022. [ EqualDepth ]: NotEqualDepth,
  47023. [ LessEqualDepth ]: GreaterEqualDepth,
  47024. [ AlwaysDepth ]: NeverDepth,
  47025. [ GreaterDepth ]: LessDepth,
  47026. [ NotEqualDepth ]: EqualDepth,
  47027. [ GreaterEqualDepth ]: LessEqualDepth,
  47028. };
  47029. function WebGLState( gl, extensions ) {
  47030. function ColorBuffer() {
  47031. let locked = false;
  47032. const color = new Vector4();
  47033. let currentColorMask = null;
  47034. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  47035. return {
  47036. setMask: function ( colorMask ) {
  47037. if ( currentColorMask !== colorMask && ! locked ) {
  47038. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  47039. currentColorMask = colorMask;
  47040. }
  47041. },
  47042. setLocked: function ( lock ) {
  47043. locked = lock;
  47044. },
  47045. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  47046. if ( premultipliedAlpha === true ) {
  47047. r *= a; g *= a; b *= a;
  47048. }
  47049. color.set( r, g, b, a );
  47050. if ( currentColorClear.equals( color ) === false ) {
  47051. gl.clearColor( r, g, b, a );
  47052. currentColorClear.copy( color );
  47053. }
  47054. },
  47055. reset: function () {
  47056. locked = false;
  47057. currentColorMask = null;
  47058. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  47059. }
  47060. };
  47061. }
  47062. function DepthBuffer() {
  47063. let locked = false;
  47064. let reversed = false;
  47065. let currentDepthMask = null;
  47066. let currentDepthFunc = null;
  47067. let currentDepthClear = null;
  47068. return {
  47069. setReversed: function ( value ) {
  47070. if ( reversed !== value ) {
  47071. const ext = extensions.get( 'EXT_clip_control' );
  47072. if ( reversed ) {
  47073. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  47074. } else {
  47075. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  47076. }
  47077. const oldDepth = currentDepthClear;
  47078. currentDepthClear = null;
  47079. this.setClear( oldDepth );
  47080. }
  47081. reversed = value;
  47082. },
  47083. getReversed: function () {
  47084. return reversed;
  47085. },
  47086. setTest: function ( depthTest ) {
  47087. if ( depthTest ) {
  47088. enable( gl.DEPTH_TEST );
  47089. } else {
  47090. disable( gl.DEPTH_TEST );
  47091. }
  47092. },
  47093. setMask: function ( depthMask ) {
  47094. if ( currentDepthMask !== depthMask && ! locked ) {
  47095. gl.depthMask( depthMask );
  47096. currentDepthMask = depthMask;
  47097. }
  47098. },
  47099. setFunc: function ( depthFunc ) {
  47100. if ( reversed ) depthFunc = reversedFuncs[ depthFunc ];
  47101. if ( currentDepthFunc !== depthFunc ) {
  47102. switch ( depthFunc ) {
  47103. case NeverDepth:
  47104. gl.depthFunc( gl.NEVER );
  47105. break;
  47106. case AlwaysDepth:
  47107. gl.depthFunc( gl.ALWAYS );
  47108. break;
  47109. case LessDepth:
  47110. gl.depthFunc( gl.LESS );
  47111. break;
  47112. case LessEqualDepth:
  47113. gl.depthFunc( gl.LEQUAL );
  47114. break;
  47115. case EqualDepth:
  47116. gl.depthFunc( gl.EQUAL );
  47117. break;
  47118. case GreaterEqualDepth:
  47119. gl.depthFunc( gl.GEQUAL );
  47120. break;
  47121. case GreaterDepth:
  47122. gl.depthFunc( gl.GREATER );
  47123. break;
  47124. case NotEqualDepth:
  47125. gl.depthFunc( gl.NOTEQUAL );
  47126. break;
  47127. default:
  47128. gl.depthFunc( gl.LEQUAL );
  47129. }
  47130. currentDepthFunc = depthFunc;
  47131. }
  47132. },
  47133. setLocked: function ( lock ) {
  47134. locked = lock;
  47135. },
  47136. setClear: function ( depth ) {
  47137. if ( currentDepthClear !== depth ) {
  47138. if ( reversed ) {
  47139. depth = 1 - depth;
  47140. }
  47141. gl.clearDepth( depth );
  47142. currentDepthClear = depth;
  47143. }
  47144. },
  47145. reset: function () {
  47146. locked = false;
  47147. currentDepthMask = null;
  47148. currentDepthFunc = null;
  47149. currentDepthClear = null;
  47150. reversed = false;
  47151. }
  47152. };
  47153. }
  47154. function StencilBuffer() {
  47155. let locked = false;
  47156. let currentStencilMask = null;
  47157. let currentStencilFunc = null;
  47158. let currentStencilRef = null;
  47159. let currentStencilFuncMask = null;
  47160. let currentStencilFail = null;
  47161. let currentStencilZFail = null;
  47162. let currentStencilZPass = null;
  47163. let currentStencilClear = null;
  47164. return {
  47165. setTest: function ( stencilTest ) {
  47166. if ( ! locked ) {
  47167. if ( stencilTest ) {
  47168. enable( gl.STENCIL_TEST );
  47169. } else {
  47170. disable( gl.STENCIL_TEST );
  47171. }
  47172. }
  47173. },
  47174. setMask: function ( stencilMask ) {
  47175. if ( currentStencilMask !== stencilMask && ! locked ) {
  47176. gl.stencilMask( stencilMask );
  47177. currentStencilMask = stencilMask;
  47178. }
  47179. },
  47180. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  47181. if ( currentStencilFunc !== stencilFunc ||
  47182. currentStencilRef !== stencilRef ||
  47183. currentStencilFuncMask !== stencilMask ) {
  47184. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  47185. currentStencilFunc = stencilFunc;
  47186. currentStencilRef = stencilRef;
  47187. currentStencilFuncMask = stencilMask;
  47188. }
  47189. },
  47190. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  47191. if ( currentStencilFail !== stencilFail ||
  47192. currentStencilZFail !== stencilZFail ||
  47193. currentStencilZPass !== stencilZPass ) {
  47194. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  47195. currentStencilFail = stencilFail;
  47196. currentStencilZFail = stencilZFail;
  47197. currentStencilZPass = stencilZPass;
  47198. }
  47199. },
  47200. setLocked: function ( lock ) {
  47201. locked = lock;
  47202. },
  47203. setClear: function ( stencil ) {
  47204. if ( currentStencilClear !== stencil ) {
  47205. gl.clearStencil( stencil );
  47206. currentStencilClear = stencil;
  47207. }
  47208. },
  47209. reset: function () {
  47210. locked = false;
  47211. currentStencilMask = null;
  47212. currentStencilFunc = null;
  47213. currentStencilRef = null;
  47214. currentStencilFuncMask = null;
  47215. currentStencilFail = null;
  47216. currentStencilZFail = null;
  47217. currentStencilZPass = null;
  47218. currentStencilClear = null;
  47219. }
  47220. };
  47221. }
  47222. //
  47223. const colorBuffer = new ColorBuffer();
  47224. const depthBuffer = new DepthBuffer();
  47225. const stencilBuffer = new StencilBuffer();
  47226. const uboBindings = new WeakMap();
  47227. const uboProgramMap = new WeakMap();
  47228. let enabledCapabilities = {};
  47229. let currentBoundFramebuffers = {};
  47230. let currentDrawbuffers = new WeakMap();
  47231. let defaultDrawbuffers = [];
  47232. let currentProgram = null;
  47233. let currentBlendingEnabled = false;
  47234. let currentBlending = null;
  47235. let currentBlendEquation = null;
  47236. let currentBlendSrc = null;
  47237. let currentBlendDst = null;
  47238. let currentBlendEquationAlpha = null;
  47239. let currentBlendSrcAlpha = null;
  47240. let currentBlendDstAlpha = null;
  47241. let currentBlendColor = new Color( 0, 0, 0 );
  47242. let currentBlendAlpha = 0;
  47243. let currentPremultipledAlpha = false;
  47244. let currentFlipSided = null;
  47245. let currentCullFace = null;
  47246. let currentLineWidth = null;
  47247. let currentPolygonOffsetFactor = null;
  47248. let currentPolygonOffsetUnits = null;
  47249. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  47250. let lineWidthAvailable = false;
  47251. let version = 0;
  47252. const glVersion = gl.getParameter( gl.VERSION );
  47253. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  47254. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  47255. lineWidthAvailable = ( version >= 1.0 );
  47256. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  47257. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  47258. lineWidthAvailable = ( version >= 2.0 );
  47259. }
  47260. let currentTextureSlot = null;
  47261. let currentBoundTextures = {};
  47262. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  47263. const viewportParam = gl.getParameter( gl.VIEWPORT );
  47264. const currentScissor = new Vector4().fromArray( scissorParam );
  47265. const currentViewport = new Vector4().fromArray( viewportParam );
  47266. function createTexture( type, target, count, dimensions ) {
  47267. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  47268. const texture = gl.createTexture();
  47269. gl.bindTexture( type, texture );
  47270. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  47271. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  47272. for ( let i = 0; i < count; i ++ ) {
  47273. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  47274. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47275. } else {
  47276. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  47277. }
  47278. }
  47279. return texture;
  47280. }
  47281. const emptyTextures = {};
  47282. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  47283. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  47284. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  47285. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  47286. // init
  47287. colorBuffer.setClear( 0, 0, 0, 1 );
  47288. depthBuffer.setClear( 1 );
  47289. stencilBuffer.setClear( 0 );
  47290. enable( gl.DEPTH_TEST );
  47291. depthBuffer.setFunc( LessEqualDepth );
  47292. setFlipSided( false );
  47293. setCullFace( CullFaceBack );
  47294. enable( gl.CULL_FACE );
  47295. setBlending( NoBlending );
  47296. //
  47297. function enable( id ) {
  47298. if ( enabledCapabilities[ id ] !== true ) {
  47299. gl.enable( id );
  47300. enabledCapabilities[ id ] = true;
  47301. }
  47302. }
  47303. function disable( id ) {
  47304. if ( enabledCapabilities[ id ] !== false ) {
  47305. gl.disable( id );
  47306. enabledCapabilities[ id ] = false;
  47307. }
  47308. }
  47309. function bindFramebuffer( target, framebuffer ) {
  47310. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  47311. gl.bindFramebuffer( target, framebuffer );
  47312. currentBoundFramebuffers[ target ] = framebuffer;
  47313. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  47314. if ( target === gl.DRAW_FRAMEBUFFER ) {
  47315. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  47316. }
  47317. if ( target === gl.FRAMEBUFFER ) {
  47318. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  47319. }
  47320. return true;
  47321. }
  47322. return false;
  47323. }
  47324. function drawBuffers( renderTarget, framebuffer ) {
  47325. let drawBuffers = defaultDrawbuffers;
  47326. let needsUpdate = false;
  47327. if ( renderTarget ) {
  47328. drawBuffers = currentDrawbuffers.get( framebuffer );
  47329. if ( drawBuffers === undefined ) {
  47330. drawBuffers = [];
  47331. currentDrawbuffers.set( framebuffer, drawBuffers );
  47332. }
  47333. const textures = renderTarget.textures;
  47334. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  47335. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  47336. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  47337. }
  47338. drawBuffers.length = textures.length;
  47339. needsUpdate = true;
  47340. }
  47341. } else {
  47342. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  47343. drawBuffers[ 0 ] = gl.BACK;
  47344. needsUpdate = true;
  47345. }
  47346. }
  47347. if ( needsUpdate ) {
  47348. gl.drawBuffers( drawBuffers );
  47349. }
  47350. }
  47351. function useProgram( program ) {
  47352. if ( currentProgram !== program ) {
  47353. gl.useProgram( program );
  47354. currentProgram = program;
  47355. return true;
  47356. }
  47357. return false;
  47358. }
  47359. const equationToGL = {
  47360. [ AddEquation ]: gl.FUNC_ADD,
  47361. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  47362. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  47363. };
  47364. equationToGL[ MinEquation ] = gl.MIN;
  47365. equationToGL[ MaxEquation ] = gl.MAX;
  47366. const factorToGL = {
  47367. [ ZeroFactor ]: gl.ZERO,
  47368. [ OneFactor ]: gl.ONE,
  47369. [ SrcColorFactor ]: gl.SRC_COLOR,
  47370. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  47371. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  47372. [ DstColorFactor ]: gl.DST_COLOR,
  47373. [ DstAlphaFactor ]: gl.DST_ALPHA,
  47374. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  47375. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  47376. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  47377. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  47378. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  47379. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  47380. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  47381. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  47382. };
  47383. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  47384. if ( blending === NoBlending ) {
  47385. if ( currentBlendingEnabled === true ) {
  47386. disable( gl.BLEND );
  47387. currentBlendingEnabled = false;
  47388. }
  47389. return;
  47390. }
  47391. if ( currentBlendingEnabled === false ) {
  47392. enable( gl.BLEND );
  47393. currentBlendingEnabled = true;
  47394. }
  47395. if ( blending !== CustomBlending ) {
  47396. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  47397. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  47398. gl.blendEquation( gl.FUNC_ADD );
  47399. currentBlendEquation = AddEquation;
  47400. currentBlendEquationAlpha = AddEquation;
  47401. }
  47402. if ( premultipliedAlpha ) {
  47403. switch ( blending ) {
  47404. case NormalBlending:
  47405. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47406. break;
  47407. case AdditiveBlending:
  47408. gl.blendFunc( gl.ONE, gl.ONE );
  47409. break;
  47410. case SubtractiveBlending:
  47411. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47412. break;
  47413. case MultiplyBlending:
  47414. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  47415. break;
  47416. default:
  47417. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  47418. break;
  47419. }
  47420. } else {
  47421. switch ( blending ) {
  47422. case NormalBlending:
  47423. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  47424. break;
  47425. case AdditiveBlending:
  47426. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  47427. break;
  47428. case SubtractiveBlending:
  47429. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  47430. break;
  47431. case MultiplyBlending:
  47432. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  47433. break;
  47434. default:
  47435. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  47436. break;
  47437. }
  47438. }
  47439. currentBlendSrc = null;
  47440. currentBlendDst = null;
  47441. currentBlendSrcAlpha = null;
  47442. currentBlendDstAlpha = null;
  47443. currentBlendColor.set( 0, 0, 0 );
  47444. currentBlendAlpha = 0;
  47445. currentBlending = blending;
  47446. currentPremultipledAlpha = premultipliedAlpha;
  47447. }
  47448. return;
  47449. }
  47450. // custom blending
  47451. blendEquationAlpha = blendEquationAlpha || blendEquation;
  47452. blendSrcAlpha = blendSrcAlpha || blendSrc;
  47453. blendDstAlpha = blendDstAlpha || blendDst;
  47454. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  47455. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  47456. currentBlendEquation = blendEquation;
  47457. currentBlendEquationAlpha = blendEquationAlpha;
  47458. }
  47459. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  47460. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  47461. currentBlendSrc = blendSrc;
  47462. currentBlendDst = blendDst;
  47463. currentBlendSrcAlpha = blendSrcAlpha;
  47464. currentBlendDstAlpha = blendDstAlpha;
  47465. }
  47466. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  47467. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  47468. currentBlendColor.copy( blendColor );
  47469. currentBlendAlpha = blendAlpha;
  47470. }
  47471. currentBlending = blending;
  47472. currentPremultipledAlpha = false;
  47473. }
  47474. function setMaterial( material, frontFaceCW ) {
  47475. material.side === DoubleSide
  47476. ? disable( gl.CULL_FACE )
  47477. : enable( gl.CULL_FACE );
  47478. let flipSided = ( material.side === BackSide );
  47479. if ( frontFaceCW ) flipSided = ! flipSided;
  47480. setFlipSided( flipSided );
  47481. ( material.blending === NormalBlending && material.transparent === false )
  47482. ? setBlending( NoBlending )
  47483. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  47484. depthBuffer.setFunc( material.depthFunc );
  47485. depthBuffer.setTest( material.depthTest );
  47486. depthBuffer.setMask( material.depthWrite );
  47487. colorBuffer.setMask( material.colorWrite );
  47488. const stencilWrite = material.stencilWrite;
  47489. stencilBuffer.setTest( stencilWrite );
  47490. if ( stencilWrite ) {
  47491. stencilBuffer.setMask( material.stencilWriteMask );
  47492. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  47493. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  47494. }
  47495. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  47496. material.alphaToCoverage === true
  47497. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  47498. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  47499. }
  47500. //
  47501. function setFlipSided( flipSided ) {
  47502. if ( currentFlipSided !== flipSided ) {
  47503. if ( flipSided ) {
  47504. gl.frontFace( gl.CW );
  47505. } else {
  47506. gl.frontFace( gl.CCW );
  47507. }
  47508. currentFlipSided = flipSided;
  47509. }
  47510. }
  47511. function setCullFace( cullFace ) {
  47512. if ( cullFace !== CullFaceNone ) {
  47513. enable( gl.CULL_FACE );
  47514. if ( cullFace !== currentCullFace ) {
  47515. if ( cullFace === CullFaceBack ) {
  47516. gl.cullFace( gl.BACK );
  47517. } else if ( cullFace === CullFaceFront ) {
  47518. gl.cullFace( gl.FRONT );
  47519. } else {
  47520. gl.cullFace( gl.FRONT_AND_BACK );
  47521. }
  47522. }
  47523. } else {
  47524. disable( gl.CULL_FACE );
  47525. }
  47526. currentCullFace = cullFace;
  47527. }
  47528. function setLineWidth( width ) {
  47529. if ( width !== currentLineWidth ) {
  47530. if ( lineWidthAvailable ) gl.lineWidth( width );
  47531. currentLineWidth = width;
  47532. }
  47533. }
  47534. function setPolygonOffset( polygonOffset, factor, units ) {
  47535. if ( polygonOffset ) {
  47536. enable( gl.POLYGON_OFFSET_FILL );
  47537. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  47538. gl.polygonOffset( factor, units );
  47539. currentPolygonOffsetFactor = factor;
  47540. currentPolygonOffsetUnits = units;
  47541. }
  47542. } else {
  47543. disable( gl.POLYGON_OFFSET_FILL );
  47544. }
  47545. }
  47546. function setScissorTest( scissorTest ) {
  47547. if ( scissorTest ) {
  47548. enable( gl.SCISSOR_TEST );
  47549. } else {
  47550. disable( gl.SCISSOR_TEST );
  47551. }
  47552. }
  47553. // texture
  47554. function activeTexture( webglSlot ) {
  47555. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  47556. if ( currentTextureSlot !== webglSlot ) {
  47557. gl.activeTexture( webglSlot );
  47558. currentTextureSlot = webglSlot;
  47559. }
  47560. }
  47561. function bindTexture( webglType, webglTexture, webglSlot ) {
  47562. if ( webglSlot === undefined ) {
  47563. if ( currentTextureSlot === null ) {
  47564. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  47565. } else {
  47566. webglSlot = currentTextureSlot;
  47567. }
  47568. }
  47569. let boundTexture = currentBoundTextures[ webglSlot ];
  47570. if ( boundTexture === undefined ) {
  47571. boundTexture = { type: undefined, texture: undefined };
  47572. currentBoundTextures[ webglSlot ] = boundTexture;
  47573. }
  47574. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  47575. if ( currentTextureSlot !== webglSlot ) {
  47576. gl.activeTexture( webglSlot );
  47577. currentTextureSlot = webglSlot;
  47578. }
  47579. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  47580. boundTexture.type = webglType;
  47581. boundTexture.texture = webglTexture;
  47582. }
  47583. }
  47584. function unbindTexture() {
  47585. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  47586. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  47587. gl.bindTexture( boundTexture.type, null );
  47588. boundTexture.type = undefined;
  47589. boundTexture.texture = undefined;
  47590. }
  47591. }
  47592. function compressedTexImage2D() {
  47593. try {
  47594. gl.compressedTexImage2D( ...arguments );
  47595. } catch ( error ) {
  47596. console.error( 'THREE.WebGLState:', error );
  47597. }
  47598. }
  47599. function compressedTexImage3D() {
  47600. try {
  47601. gl.compressedTexImage3D( ...arguments );
  47602. } catch ( error ) {
  47603. console.error( 'THREE.WebGLState:', error );
  47604. }
  47605. }
  47606. function texSubImage2D() {
  47607. try {
  47608. gl.texSubImage2D( ...arguments );
  47609. } catch ( error ) {
  47610. console.error( 'THREE.WebGLState:', error );
  47611. }
  47612. }
  47613. function texSubImage3D() {
  47614. try {
  47615. gl.texSubImage3D( ...arguments );
  47616. } catch ( error ) {
  47617. console.error( 'THREE.WebGLState:', error );
  47618. }
  47619. }
  47620. function compressedTexSubImage2D() {
  47621. try {
  47622. gl.compressedTexSubImage2D( ...arguments );
  47623. } catch ( error ) {
  47624. console.error( 'THREE.WebGLState:', error );
  47625. }
  47626. }
  47627. function compressedTexSubImage3D() {
  47628. try {
  47629. gl.compressedTexSubImage3D( ...arguments );
  47630. } catch ( error ) {
  47631. console.error( 'THREE.WebGLState:', error );
  47632. }
  47633. }
  47634. function texStorage2D() {
  47635. try {
  47636. gl.texStorage2D( ...arguments );
  47637. } catch ( error ) {
  47638. console.error( 'THREE.WebGLState:', error );
  47639. }
  47640. }
  47641. function texStorage3D() {
  47642. try {
  47643. gl.texStorage3D( ...arguments );
  47644. } catch ( error ) {
  47645. console.error( 'THREE.WebGLState:', error );
  47646. }
  47647. }
  47648. function texImage2D() {
  47649. try {
  47650. gl.texImage2D( ...arguments );
  47651. } catch ( error ) {
  47652. console.error( 'THREE.WebGLState:', error );
  47653. }
  47654. }
  47655. function texImage3D() {
  47656. try {
  47657. gl.texImage3D( ...arguments );
  47658. } catch ( error ) {
  47659. console.error( 'THREE.WebGLState:', error );
  47660. }
  47661. }
  47662. //
  47663. function scissor( scissor ) {
  47664. if ( currentScissor.equals( scissor ) === false ) {
  47665. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  47666. currentScissor.copy( scissor );
  47667. }
  47668. }
  47669. function viewport( viewport ) {
  47670. if ( currentViewport.equals( viewport ) === false ) {
  47671. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  47672. currentViewport.copy( viewport );
  47673. }
  47674. }
  47675. function updateUBOMapping( uniformsGroup, program ) {
  47676. let mapping = uboProgramMap.get( program );
  47677. if ( mapping === undefined ) {
  47678. mapping = new WeakMap();
  47679. uboProgramMap.set( program, mapping );
  47680. }
  47681. let blockIndex = mapping.get( uniformsGroup );
  47682. if ( blockIndex === undefined ) {
  47683. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  47684. mapping.set( uniformsGroup, blockIndex );
  47685. }
  47686. }
  47687. function uniformBlockBinding( uniformsGroup, program ) {
  47688. const mapping = uboProgramMap.get( program );
  47689. const blockIndex = mapping.get( uniformsGroup );
  47690. if ( uboBindings.get( program ) !== blockIndex ) {
  47691. // bind shader specific block index to global block point
  47692. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  47693. uboBindings.set( program, blockIndex );
  47694. }
  47695. }
  47696. //
  47697. function reset() {
  47698. // reset state
  47699. gl.disable( gl.BLEND );
  47700. gl.disable( gl.CULL_FACE );
  47701. gl.disable( gl.DEPTH_TEST );
  47702. gl.disable( gl.POLYGON_OFFSET_FILL );
  47703. gl.disable( gl.SCISSOR_TEST );
  47704. gl.disable( gl.STENCIL_TEST );
  47705. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  47706. gl.blendEquation( gl.FUNC_ADD );
  47707. gl.blendFunc( gl.ONE, gl.ZERO );
  47708. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  47709. gl.blendColor( 0, 0, 0, 0 );
  47710. gl.colorMask( true, true, true, true );
  47711. gl.clearColor( 0, 0, 0, 0 );
  47712. gl.depthMask( true );
  47713. gl.depthFunc( gl.LESS );
  47714. depthBuffer.setReversed( false );
  47715. gl.clearDepth( 1 );
  47716. gl.stencilMask( 0xffffffff );
  47717. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  47718. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  47719. gl.clearStencil( 0 );
  47720. gl.cullFace( gl.BACK );
  47721. gl.frontFace( gl.CCW );
  47722. gl.polygonOffset( 0, 0 );
  47723. gl.activeTexture( gl.TEXTURE0 );
  47724. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  47725. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  47726. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  47727. gl.useProgram( null );
  47728. gl.lineWidth( 1 );
  47729. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  47730. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  47731. // reset internals
  47732. enabledCapabilities = {};
  47733. currentTextureSlot = null;
  47734. currentBoundTextures = {};
  47735. currentBoundFramebuffers = {};
  47736. currentDrawbuffers = new WeakMap();
  47737. defaultDrawbuffers = [];
  47738. currentProgram = null;
  47739. currentBlendingEnabled = false;
  47740. currentBlending = null;
  47741. currentBlendEquation = null;
  47742. currentBlendSrc = null;
  47743. currentBlendDst = null;
  47744. currentBlendEquationAlpha = null;
  47745. currentBlendSrcAlpha = null;
  47746. currentBlendDstAlpha = null;
  47747. currentBlendColor = new Color( 0, 0, 0 );
  47748. currentBlendAlpha = 0;
  47749. currentPremultipledAlpha = false;
  47750. currentFlipSided = null;
  47751. currentCullFace = null;
  47752. currentLineWidth = null;
  47753. currentPolygonOffsetFactor = null;
  47754. currentPolygonOffsetUnits = null;
  47755. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  47756. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  47757. colorBuffer.reset();
  47758. depthBuffer.reset();
  47759. stencilBuffer.reset();
  47760. }
  47761. return {
  47762. buffers: {
  47763. color: colorBuffer,
  47764. depth: depthBuffer,
  47765. stencil: stencilBuffer
  47766. },
  47767. enable: enable,
  47768. disable: disable,
  47769. bindFramebuffer: bindFramebuffer,
  47770. drawBuffers: drawBuffers,
  47771. useProgram: useProgram,
  47772. setBlending: setBlending,
  47773. setMaterial: setMaterial,
  47774. setFlipSided: setFlipSided,
  47775. setCullFace: setCullFace,
  47776. setLineWidth: setLineWidth,
  47777. setPolygonOffset: setPolygonOffset,
  47778. setScissorTest: setScissorTest,
  47779. activeTexture: activeTexture,
  47780. bindTexture: bindTexture,
  47781. unbindTexture: unbindTexture,
  47782. compressedTexImage2D: compressedTexImage2D,
  47783. compressedTexImage3D: compressedTexImage3D,
  47784. texImage2D: texImage2D,
  47785. texImage3D: texImage3D,
  47786. updateUBOMapping: updateUBOMapping,
  47787. uniformBlockBinding: uniformBlockBinding,
  47788. texStorage2D: texStorage2D,
  47789. texStorage3D: texStorage3D,
  47790. texSubImage2D: texSubImage2D,
  47791. texSubImage3D: texSubImage3D,
  47792. compressedTexSubImage2D: compressedTexSubImage2D,
  47793. compressedTexSubImage3D: compressedTexSubImage3D,
  47794. scissor: scissor,
  47795. viewport: viewport,
  47796. reset: reset
  47797. };
  47798. }
  47799. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  47800. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  47801. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  47802. const _imageDimensions = new Vector2();
  47803. const _videoTextures = new WeakMap();
  47804. let _canvas;
  47805. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  47806. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  47807. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  47808. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  47809. let useOffscreenCanvas = false;
  47810. try {
  47811. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  47812. // eslint-disable-next-line compat/compat
  47813. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  47814. } catch ( err ) {
  47815. // Ignore any errors
  47816. }
  47817. function createCanvas( width, height ) {
  47818. // Use OffscreenCanvas when available. Specially needed in web workers
  47819. return useOffscreenCanvas ?
  47820. // eslint-disable-next-line compat/compat
  47821. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  47822. }
  47823. function resizeImage( image, needsNewCanvas, maxSize ) {
  47824. let scale = 1;
  47825. const dimensions = getDimensions( image );
  47826. // handle case if texture exceeds max size
  47827. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  47828. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  47829. }
  47830. // only perform resize if necessary
  47831. if ( scale < 1 ) {
  47832. // only perform resize for certain image types
  47833. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  47834. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  47835. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  47836. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  47837. const width = Math.floor( scale * dimensions.width );
  47838. const height = Math.floor( scale * dimensions.height );
  47839. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  47840. // cube textures can't reuse the same canvas
  47841. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  47842. canvas.width = width;
  47843. canvas.height = height;
  47844. const context = canvas.getContext( '2d' );
  47845. context.drawImage( image, 0, 0, width, height );
  47846. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  47847. return canvas;
  47848. } else {
  47849. if ( 'data' in image ) {
  47850. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  47851. }
  47852. return image;
  47853. }
  47854. }
  47855. return image;
  47856. }
  47857. function textureNeedsGenerateMipmaps( texture ) {
  47858. return texture.generateMipmaps;
  47859. }
  47860. function generateMipmap( target ) {
  47861. _gl.generateMipmap( target );
  47862. }
  47863. function getTargetType( texture ) {
  47864. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  47865. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  47866. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  47867. return _gl.TEXTURE_2D;
  47868. }
  47869. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  47870. if ( internalFormatName !== null ) {
  47871. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  47872. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  47873. }
  47874. let internalFormat = glFormat;
  47875. if ( glFormat === _gl.RED ) {
  47876. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  47877. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  47878. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  47879. }
  47880. if ( glFormat === _gl.RED_INTEGER ) {
  47881. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  47882. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  47883. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  47884. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  47885. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  47886. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  47887. }
  47888. if ( glFormat === _gl.RG ) {
  47889. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  47890. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  47891. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  47892. }
  47893. if ( glFormat === _gl.RG_INTEGER ) {
  47894. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  47895. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  47896. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  47897. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  47898. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  47899. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  47900. }
  47901. if ( glFormat === _gl.RGB_INTEGER ) {
  47902. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  47903. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  47904. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  47905. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  47906. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  47907. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  47908. }
  47909. if ( glFormat === _gl.RGBA_INTEGER ) {
  47910. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  47911. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  47912. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  47913. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  47914. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  47915. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  47916. }
  47917. if ( glFormat === _gl.RGB ) {
  47918. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  47919. }
  47920. if ( glFormat === _gl.RGBA ) {
  47921. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  47922. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  47923. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  47924. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  47925. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  47926. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  47927. }
  47928. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  47929. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  47930. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  47931. extensions.get( 'EXT_color_buffer_float' );
  47932. }
  47933. return internalFormat;
  47934. }
  47935. function getInternalDepthFormat( useStencil, depthType ) {
  47936. let glInternalFormat;
  47937. if ( useStencil ) {
  47938. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  47939. glInternalFormat = _gl.DEPTH24_STENCIL8;
  47940. } else if ( depthType === FloatType ) {
  47941. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  47942. } else if ( depthType === UnsignedShortType ) {
  47943. glInternalFormat = _gl.DEPTH24_STENCIL8;
  47944. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  47945. }
  47946. } else {
  47947. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  47948. glInternalFormat = _gl.DEPTH_COMPONENT24;
  47949. } else if ( depthType === FloatType ) {
  47950. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  47951. } else if ( depthType === UnsignedShortType ) {
  47952. glInternalFormat = _gl.DEPTH_COMPONENT16;
  47953. }
  47954. }
  47955. return glInternalFormat;
  47956. }
  47957. function getMipLevels( texture, image ) {
  47958. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  47959. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  47960. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  47961. // user-defined mipmaps
  47962. return texture.mipmaps.length;
  47963. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  47964. return image.mipmaps.length;
  47965. } else {
  47966. // texture without mipmaps (only base level)
  47967. return 1;
  47968. }
  47969. }
  47970. //
  47971. function onTextureDispose( event ) {
  47972. const texture = event.target;
  47973. texture.removeEventListener( 'dispose', onTextureDispose );
  47974. deallocateTexture( texture );
  47975. if ( texture.isVideoTexture ) {
  47976. _videoTextures.delete( texture );
  47977. }
  47978. }
  47979. function onRenderTargetDispose( event ) {
  47980. const renderTarget = event.target;
  47981. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  47982. deallocateRenderTarget( renderTarget );
  47983. }
  47984. //
  47985. function deallocateTexture( texture ) {
  47986. const textureProperties = properties.get( texture );
  47987. if ( textureProperties.__webglInit === undefined ) return;
  47988. // check if it's necessary to remove the WebGLTexture object
  47989. const source = texture.source;
  47990. const webglTextures = _sources.get( source );
  47991. if ( webglTextures ) {
  47992. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  47993. webglTexture.usedTimes --;
  47994. // the WebGLTexture object is not used anymore, remove it
  47995. if ( webglTexture.usedTimes === 0 ) {
  47996. deleteTexture( texture );
  47997. }
  47998. // remove the weak map entry if no WebGLTexture uses the source anymore
  47999. if ( Object.keys( webglTextures ).length === 0 ) {
  48000. _sources.delete( source );
  48001. }
  48002. }
  48003. properties.remove( texture );
  48004. }
  48005. function deleteTexture( texture ) {
  48006. const textureProperties = properties.get( texture );
  48007. _gl.deleteTexture( textureProperties.__webglTexture );
  48008. const source = texture.source;
  48009. const webglTextures = _sources.get( source );
  48010. delete webglTextures[ textureProperties.__cacheKey ];
  48011. info.memory.textures --;
  48012. }
  48013. function deallocateRenderTarget( renderTarget ) {
  48014. const renderTargetProperties = properties.get( renderTarget );
  48015. if ( renderTarget.depthTexture ) {
  48016. renderTarget.depthTexture.dispose();
  48017. properties.remove( renderTarget.depthTexture );
  48018. }
  48019. if ( renderTarget.isWebGLCubeRenderTarget ) {
  48020. for ( let i = 0; i < 6; i ++ ) {
  48021. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  48022. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  48023. } else {
  48024. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  48025. }
  48026. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  48027. }
  48028. } else {
  48029. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  48030. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  48031. } else {
  48032. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  48033. }
  48034. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  48035. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  48036. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  48037. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  48038. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48039. }
  48040. }
  48041. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  48042. }
  48043. const textures = renderTarget.textures;
  48044. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48045. const attachmentProperties = properties.get( textures[ i ] );
  48046. if ( attachmentProperties.__webglTexture ) {
  48047. _gl.deleteTexture( attachmentProperties.__webglTexture );
  48048. info.memory.textures --;
  48049. }
  48050. properties.remove( textures[ i ] );
  48051. }
  48052. properties.remove( renderTarget );
  48053. }
  48054. //
  48055. let textureUnits = 0;
  48056. function resetTextureUnits() {
  48057. textureUnits = 0;
  48058. }
  48059. function allocateTextureUnit() {
  48060. const textureUnit = textureUnits;
  48061. if ( textureUnit >= capabilities.maxTextures ) {
  48062. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  48063. }
  48064. textureUnits += 1;
  48065. return textureUnit;
  48066. }
  48067. function getTextureCacheKey( texture ) {
  48068. const array = [];
  48069. array.push( texture.wrapS );
  48070. array.push( texture.wrapT );
  48071. array.push( texture.wrapR || 0 );
  48072. array.push( texture.magFilter );
  48073. array.push( texture.minFilter );
  48074. array.push( texture.anisotropy );
  48075. array.push( texture.internalFormat );
  48076. array.push( texture.format );
  48077. array.push( texture.type );
  48078. array.push( texture.generateMipmaps );
  48079. array.push( texture.premultiplyAlpha );
  48080. array.push( texture.flipY );
  48081. array.push( texture.unpackAlignment );
  48082. array.push( texture.colorSpace );
  48083. return array.join();
  48084. }
  48085. //
  48086. function setTexture2D( texture, slot ) {
  48087. const textureProperties = properties.get( texture );
  48088. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  48089. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  48090. const image = texture.image;
  48091. if ( image === null ) {
  48092. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  48093. } else if ( image.complete === false ) {
  48094. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  48095. } else {
  48096. uploadTexture( textureProperties, texture, slot );
  48097. return;
  48098. }
  48099. }
  48100. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48101. }
  48102. function setTexture2DArray( texture, slot ) {
  48103. const textureProperties = properties.get( texture );
  48104. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  48105. uploadTexture( textureProperties, texture, slot );
  48106. return;
  48107. }
  48108. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48109. }
  48110. function setTexture3D( texture, slot ) {
  48111. const textureProperties = properties.get( texture );
  48112. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  48113. uploadTexture( textureProperties, texture, slot );
  48114. return;
  48115. }
  48116. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48117. }
  48118. function setTextureCube( texture, slot ) {
  48119. const textureProperties = properties.get( texture );
  48120. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  48121. uploadCubeTexture( textureProperties, texture, slot );
  48122. return;
  48123. }
  48124. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48125. }
  48126. const wrappingToGL = {
  48127. [ RepeatWrapping ]: _gl.REPEAT,
  48128. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  48129. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  48130. };
  48131. const filterToGL = {
  48132. [ NearestFilter ]: _gl.NEAREST,
  48133. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  48134. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  48135. [ LinearFilter ]: _gl.LINEAR,
  48136. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  48137. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  48138. };
  48139. const compareToGL = {
  48140. [ NeverCompare ]: _gl.NEVER,
  48141. [ AlwaysCompare ]: _gl.ALWAYS,
  48142. [ LessCompare ]: _gl.LESS,
  48143. [ LessEqualCompare ]: _gl.LEQUAL,
  48144. [ EqualCompare ]: _gl.EQUAL,
  48145. [ GreaterEqualCompare ]: _gl.GEQUAL,
  48146. [ GreaterCompare ]: _gl.GREATER,
  48147. [ NotEqualCompare ]: _gl.NOTEQUAL
  48148. };
  48149. function setTextureParameters( textureType, texture ) {
  48150. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  48151. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  48152. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  48153. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  48154. }
  48155. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  48156. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  48157. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  48158. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  48159. }
  48160. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  48161. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  48162. if ( texture.compareFunction ) {
  48163. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  48164. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  48165. }
  48166. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  48167. if ( texture.magFilter === NearestFilter ) return;
  48168. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  48169. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  48170. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  48171. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  48172. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  48173. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  48174. }
  48175. }
  48176. }
  48177. function initTexture( textureProperties, texture ) {
  48178. let forceUpload = false;
  48179. if ( textureProperties.__webglInit === undefined ) {
  48180. textureProperties.__webglInit = true;
  48181. texture.addEventListener( 'dispose', onTextureDispose );
  48182. }
  48183. // create Source <-> WebGLTextures mapping if necessary
  48184. const source = texture.source;
  48185. let webglTextures = _sources.get( source );
  48186. if ( webglTextures === undefined ) {
  48187. webglTextures = {};
  48188. _sources.set( source, webglTextures );
  48189. }
  48190. // check if there is already a WebGLTexture object for the given texture parameters
  48191. const textureCacheKey = getTextureCacheKey( texture );
  48192. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  48193. // if not, create a new instance of WebGLTexture
  48194. if ( webglTextures[ textureCacheKey ] === undefined ) {
  48195. // create new entry
  48196. webglTextures[ textureCacheKey ] = {
  48197. texture: _gl.createTexture(),
  48198. usedTimes: 0
  48199. };
  48200. info.memory.textures ++;
  48201. // when a new instance of WebGLTexture was created, a texture upload is required
  48202. // even if the image contents are identical
  48203. forceUpload = true;
  48204. }
  48205. webglTextures[ textureCacheKey ].usedTimes ++;
  48206. // every time the texture cache key changes, it's necessary to check if an instance of
  48207. // WebGLTexture can be deleted in order to avoid a memory leak.
  48208. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  48209. if ( webglTexture !== undefined ) {
  48210. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  48211. if ( webglTexture.usedTimes === 0 ) {
  48212. deleteTexture( texture );
  48213. }
  48214. }
  48215. // store references to cache key and WebGLTexture object
  48216. textureProperties.__cacheKey = textureCacheKey;
  48217. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  48218. }
  48219. return forceUpload;
  48220. }
  48221. function uploadTexture( textureProperties, texture, slot ) {
  48222. let textureType = _gl.TEXTURE_2D;
  48223. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  48224. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  48225. const forceUpload = initTexture( textureProperties, texture );
  48226. const source = texture.source;
  48227. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48228. const sourceProperties = properties.get( source );
  48229. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  48230. state.activeTexture( _gl.TEXTURE0 + slot );
  48231. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  48232. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  48233. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  48234. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  48235. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  48236. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  48237. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  48238. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  48239. image = verifyColorSpace( texture, image );
  48240. const glFormat = utils.convert( texture.format, texture.colorSpace );
  48241. const glType = utils.convert( texture.type );
  48242. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  48243. setTextureParameters( textureType, texture );
  48244. let mipmap;
  48245. const mipmaps = texture.mipmaps;
  48246. const useTexStorage = ( texture.isVideoTexture !== true );
  48247. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  48248. const dataReady = source.dataReady;
  48249. const levels = getMipLevels( texture, image );
  48250. if ( texture.isDepthTexture ) {
  48251. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  48252. //
  48253. if ( allocateMemory ) {
  48254. if ( useTexStorage ) {
  48255. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  48256. } else {
  48257. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  48258. }
  48259. }
  48260. } else if ( texture.isDataTexture ) {
  48261. // use manually created mipmaps if available
  48262. // if there are no manual mipmaps
  48263. // set 0 level mipmap and then use GL to generate other mipmap levels
  48264. if ( mipmaps.length > 0 ) {
  48265. if ( useTexStorage && allocateMemory ) {
  48266. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  48267. }
  48268. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48269. mipmap = mipmaps[ i ];
  48270. if ( useTexStorage ) {
  48271. if ( dataReady ) {
  48272. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  48273. }
  48274. } else {
  48275. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  48276. }
  48277. }
  48278. texture.generateMipmaps = false;
  48279. } else {
  48280. if ( useTexStorage ) {
  48281. if ( allocateMemory ) {
  48282. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  48283. }
  48284. if ( dataReady ) {
  48285. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  48286. }
  48287. } else {
  48288. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  48289. }
  48290. }
  48291. } else if ( texture.isCompressedTexture ) {
  48292. if ( texture.isCompressedArrayTexture ) {
  48293. if ( useTexStorage && allocateMemory ) {
  48294. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  48295. }
  48296. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48297. mipmap = mipmaps[ i ];
  48298. if ( texture.format !== RGBAFormat ) {
  48299. if ( glFormat !== null ) {
  48300. if ( useTexStorage ) {
  48301. if ( dataReady ) {
  48302. if ( texture.layerUpdates.size > 0 ) {
  48303. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  48304. for ( const layerIndex of texture.layerUpdates ) {
  48305. const layerData = mipmap.data.subarray(
  48306. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  48307. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  48308. );
  48309. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  48310. }
  48311. texture.clearLayerUpdates();
  48312. } else {
  48313. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  48314. }
  48315. }
  48316. } else {
  48317. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  48318. }
  48319. } else {
  48320. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  48321. }
  48322. } else {
  48323. if ( useTexStorage ) {
  48324. if ( dataReady ) {
  48325. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  48326. }
  48327. } else {
  48328. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  48329. }
  48330. }
  48331. }
  48332. } else {
  48333. if ( useTexStorage && allocateMemory ) {
  48334. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  48335. }
  48336. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48337. mipmap = mipmaps[ i ];
  48338. if ( texture.format !== RGBAFormat ) {
  48339. if ( glFormat !== null ) {
  48340. if ( useTexStorage ) {
  48341. if ( dataReady ) {
  48342. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  48343. }
  48344. } else {
  48345. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  48346. }
  48347. } else {
  48348. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  48349. }
  48350. } else {
  48351. if ( useTexStorage ) {
  48352. if ( dataReady ) {
  48353. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  48354. }
  48355. } else {
  48356. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  48357. }
  48358. }
  48359. }
  48360. }
  48361. } else if ( texture.isDataArrayTexture ) {
  48362. if ( useTexStorage ) {
  48363. if ( allocateMemory ) {
  48364. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  48365. }
  48366. if ( dataReady ) {
  48367. if ( texture.layerUpdates.size > 0 ) {
  48368. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  48369. for ( const layerIndex of texture.layerUpdates ) {
  48370. const layerData = image.data.subarray(
  48371. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  48372. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  48373. );
  48374. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  48375. }
  48376. texture.clearLayerUpdates();
  48377. } else {
  48378. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48379. }
  48380. }
  48381. } else {
  48382. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  48383. }
  48384. } else if ( texture.isData3DTexture ) {
  48385. if ( useTexStorage ) {
  48386. if ( allocateMemory ) {
  48387. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  48388. }
  48389. if ( dataReady ) {
  48390. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  48391. }
  48392. } else {
  48393. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  48394. }
  48395. } else if ( texture.isFramebufferTexture ) {
  48396. if ( allocateMemory ) {
  48397. if ( useTexStorage ) {
  48398. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  48399. } else {
  48400. let width = image.width, height = image.height;
  48401. for ( let i = 0; i < levels; i ++ ) {
  48402. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  48403. width >>= 1;
  48404. height >>= 1;
  48405. }
  48406. }
  48407. }
  48408. } else {
  48409. // regular Texture (image, video, canvas)
  48410. // use manually created mipmaps if available
  48411. // if there are no manual mipmaps
  48412. // set 0 level mipmap and then use GL to generate other mipmap levels
  48413. if ( mipmaps.length > 0 ) {
  48414. if ( useTexStorage && allocateMemory ) {
  48415. const dimensions = getDimensions( mipmaps[ 0 ] );
  48416. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  48417. }
  48418. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48419. mipmap = mipmaps[ i ];
  48420. if ( useTexStorage ) {
  48421. if ( dataReady ) {
  48422. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  48423. }
  48424. } else {
  48425. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  48426. }
  48427. }
  48428. texture.generateMipmaps = false;
  48429. } else {
  48430. if ( useTexStorage ) {
  48431. if ( allocateMemory ) {
  48432. const dimensions = getDimensions( image );
  48433. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  48434. }
  48435. if ( dataReady ) {
  48436. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  48437. }
  48438. } else {
  48439. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  48440. }
  48441. }
  48442. }
  48443. if ( textureNeedsGenerateMipmaps( texture ) ) {
  48444. generateMipmap( textureType );
  48445. }
  48446. sourceProperties.__version = source.version;
  48447. if ( texture.onUpdate ) texture.onUpdate( texture );
  48448. }
  48449. textureProperties.__version = texture.version;
  48450. }
  48451. function uploadCubeTexture( textureProperties, texture, slot ) {
  48452. if ( texture.image.length !== 6 ) return;
  48453. const forceUpload = initTexture( textureProperties, texture );
  48454. const source = texture.source;
  48455. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  48456. const sourceProperties = properties.get( source );
  48457. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  48458. state.activeTexture( _gl.TEXTURE0 + slot );
  48459. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  48460. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  48461. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  48462. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  48463. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  48464. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  48465. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  48466. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  48467. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  48468. const cubeImage = [];
  48469. for ( let i = 0; i < 6; i ++ ) {
  48470. if ( ! isCompressed && ! isDataTexture ) {
  48471. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  48472. } else {
  48473. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  48474. }
  48475. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  48476. }
  48477. const image = cubeImage[ 0 ],
  48478. glFormat = utils.convert( texture.format, texture.colorSpace ),
  48479. glType = utils.convert( texture.type ),
  48480. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  48481. const useTexStorage = ( texture.isVideoTexture !== true );
  48482. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  48483. const dataReady = source.dataReady;
  48484. let levels = getMipLevels( texture, image );
  48485. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  48486. let mipmaps;
  48487. if ( isCompressed ) {
  48488. if ( useTexStorage && allocateMemory ) {
  48489. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  48490. }
  48491. for ( let i = 0; i < 6; i ++ ) {
  48492. mipmaps = cubeImage[ i ].mipmaps;
  48493. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48494. const mipmap = mipmaps[ j ];
  48495. if ( texture.format !== RGBAFormat ) {
  48496. if ( glFormat !== null ) {
  48497. if ( useTexStorage ) {
  48498. if ( dataReady ) {
  48499. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  48500. }
  48501. } else {
  48502. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  48503. }
  48504. } else {
  48505. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  48506. }
  48507. } else {
  48508. if ( useTexStorage ) {
  48509. if ( dataReady ) {
  48510. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  48511. }
  48512. } else {
  48513. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  48514. }
  48515. }
  48516. }
  48517. }
  48518. } else {
  48519. mipmaps = texture.mipmaps;
  48520. if ( useTexStorage && allocateMemory ) {
  48521. // TODO: Uniformly handle mipmap definitions
  48522. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  48523. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  48524. if ( mipmaps.length > 0 ) levels ++;
  48525. const dimensions = getDimensions( cubeImage[ 0 ] );
  48526. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  48527. }
  48528. for ( let i = 0; i < 6; i ++ ) {
  48529. if ( isDataTexture ) {
  48530. if ( useTexStorage ) {
  48531. if ( dataReady ) {
  48532. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  48533. }
  48534. } else {
  48535. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  48536. }
  48537. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48538. const mipmap = mipmaps[ j ];
  48539. const mipmapImage = mipmap.image[ i ].image;
  48540. if ( useTexStorage ) {
  48541. if ( dataReady ) {
  48542. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  48543. }
  48544. } else {
  48545. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  48546. }
  48547. }
  48548. } else {
  48549. if ( useTexStorage ) {
  48550. if ( dataReady ) {
  48551. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  48552. }
  48553. } else {
  48554. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  48555. }
  48556. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48557. const mipmap = mipmaps[ j ];
  48558. if ( useTexStorage ) {
  48559. if ( dataReady ) {
  48560. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  48561. }
  48562. } else {
  48563. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  48564. }
  48565. }
  48566. }
  48567. }
  48568. }
  48569. if ( textureNeedsGenerateMipmaps( texture ) ) {
  48570. // We assume images for cube map have the same size.
  48571. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  48572. }
  48573. sourceProperties.__version = source.version;
  48574. if ( texture.onUpdate ) texture.onUpdate( texture );
  48575. }
  48576. textureProperties.__version = texture.version;
  48577. }
  48578. // Render targets
  48579. // Setup storage for target texture and bind it to correct framebuffer
  48580. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  48581. const glFormat = utils.convert( texture.format, texture.colorSpace );
  48582. const glType = utils.convert( texture.type );
  48583. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  48584. const renderTargetProperties = properties.get( renderTarget );
  48585. const textureProperties = properties.get( texture );
  48586. textureProperties.__renderTarget = renderTarget;
  48587. if ( ! renderTargetProperties.__hasExternalTextures ) {
  48588. const width = Math.max( 1, renderTarget.width >> level );
  48589. const height = Math.max( 1, renderTarget.height >> level );
  48590. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  48591. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  48592. } else {
  48593. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  48594. }
  48595. }
  48596. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  48597. if ( useMultisampledRTT( renderTarget ) ) {
  48598. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  48599. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  48600. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  48601. }
  48602. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  48603. }
  48604. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  48605. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  48606. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  48607. if ( renderTarget.depthBuffer ) {
  48608. // retrieve the depth attachment types
  48609. const depthTexture = renderTarget.depthTexture;
  48610. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  48611. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  48612. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  48613. // set up the attachment
  48614. const samples = getRenderTargetSamples( renderTarget );
  48615. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  48616. if ( isUseMultisampledRTT ) {
  48617. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  48618. } else if ( isMultisample ) {
  48619. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  48620. } else {
  48621. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  48622. }
  48623. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  48624. } else {
  48625. const textures = renderTarget.textures;
  48626. for ( let i = 0; i < textures.length; i ++ ) {
  48627. const texture = textures[ i ];
  48628. const glFormat = utils.convert( texture.format, texture.colorSpace );
  48629. const glType = utils.convert( texture.type );
  48630. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  48631. const samples = getRenderTargetSamples( renderTarget );
  48632. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  48633. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  48634. } else if ( useMultisampledRTT( renderTarget ) ) {
  48635. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  48636. } else {
  48637. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  48638. }
  48639. }
  48640. }
  48641. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  48642. }
  48643. // Setup resources for a Depth Texture for a FBO (needs an extension)
  48644. function setupDepthTexture( framebuffer, renderTarget ) {
  48645. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  48646. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  48647. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  48648. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  48649. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  48650. }
  48651. const textureProperties = properties.get( renderTarget.depthTexture );
  48652. textureProperties.__renderTarget = renderTarget;
  48653. // upload an empty depth texture with framebuffer size
  48654. if ( ! textureProperties.__webglTexture ||
  48655. renderTarget.depthTexture.image.width !== renderTarget.width ||
  48656. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  48657. renderTarget.depthTexture.image.width = renderTarget.width;
  48658. renderTarget.depthTexture.image.height = renderTarget.height;
  48659. renderTarget.depthTexture.needsUpdate = true;
  48660. }
  48661. setTexture2D( renderTarget.depthTexture, 0 );
  48662. const webglDepthTexture = textureProperties.__webglTexture;
  48663. const samples = getRenderTargetSamples( renderTarget );
  48664. if ( renderTarget.depthTexture.format === DepthFormat ) {
  48665. if ( useMultisampledRTT( renderTarget ) ) {
  48666. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  48667. } else {
  48668. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  48669. }
  48670. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  48671. if ( useMultisampledRTT( renderTarget ) ) {
  48672. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  48673. } else {
  48674. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  48675. }
  48676. } else {
  48677. throw new Error( 'Unknown depthTexture format' );
  48678. }
  48679. }
  48680. // Setup GL resources for a non-texture depth buffer
  48681. function setupDepthRenderbuffer( renderTarget ) {
  48682. const renderTargetProperties = properties.get( renderTarget );
  48683. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  48684. // if the bound depth texture has changed
  48685. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  48686. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  48687. const depthTexture = renderTarget.depthTexture;
  48688. if ( renderTargetProperties.__depthDisposeCallback ) {
  48689. renderTargetProperties.__depthDisposeCallback();
  48690. }
  48691. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  48692. if ( depthTexture ) {
  48693. const disposeEvent = () => {
  48694. delete renderTargetProperties.__boundDepthTexture;
  48695. delete renderTargetProperties.__depthDisposeCallback;
  48696. depthTexture.removeEventListener( 'dispose', disposeEvent );
  48697. };
  48698. depthTexture.addEventListener( 'dispose', disposeEvent );
  48699. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  48700. }
  48701. renderTargetProperties.__boundDepthTexture = depthTexture;
  48702. }
  48703. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  48704. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  48705. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  48706. } else {
  48707. if ( isCube ) {
  48708. renderTargetProperties.__webglDepthbuffer = [];
  48709. for ( let i = 0; i < 6; i ++ ) {
  48710. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  48711. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  48712. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  48713. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  48714. } else {
  48715. // attach buffer if it's been created already
  48716. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  48717. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  48718. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  48719. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  48720. }
  48721. }
  48722. } else {
  48723. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  48724. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  48725. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  48726. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  48727. } else {
  48728. // attach buffer if it's been created already
  48729. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  48730. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  48731. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  48732. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  48733. }
  48734. }
  48735. }
  48736. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  48737. }
  48738. // rebind framebuffer with external textures
  48739. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  48740. const renderTargetProperties = properties.get( renderTarget );
  48741. if ( colorTexture !== undefined ) {
  48742. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  48743. }
  48744. if ( depthTexture !== undefined ) {
  48745. setupDepthRenderbuffer( renderTarget );
  48746. }
  48747. }
  48748. // Set up GL resources for the render target
  48749. function setupRenderTarget( renderTarget ) {
  48750. const texture = renderTarget.texture;
  48751. const renderTargetProperties = properties.get( renderTarget );
  48752. const textureProperties = properties.get( texture );
  48753. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  48754. const textures = renderTarget.textures;
  48755. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  48756. const isMultipleRenderTargets = ( textures.length > 1 );
  48757. if ( ! isMultipleRenderTargets ) {
  48758. if ( textureProperties.__webglTexture === undefined ) {
  48759. textureProperties.__webglTexture = _gl.createTexture();
  48760. }
  48761. textureProperties.__version = texture.version;
  48762. info.memory.textures ++;
  48763. }
  48764. // Setup framebuffer
  48765. if ( isCube ) {
  48766. renderTargetProperties.__webglFramebuffer = [];
  48767. for ( let i = 0; i < 6; i ++ ) {
  48768. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  48769. renderTargetProperties.__webglFramebuffer[ i ] = [];
  48770. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  48771. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  48772. }
  48773. } else {
  48774. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  48775. }
  48776. }
  48777. } else {
  48778. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  48779. renderTargetProperties.__webglFramebuffer = [];
  48780. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  48781. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  48782. }
  48783. } else {
  48784. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  48785. }
  48786. if ( isMultipleRenderTargets ) {
  48787. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48788. const attachmentProperties = properties.get( textures[ i ] );
  48789. if ( attachmentProperties.__webglTexture === undefined ) {
  48790. attachmentProperties.__webglTexture = _gl.createTexture();
  48791. info.memory.textures ++;
  48792. }
  48793. }
  48794. }
  48795. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  48796. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  48797. renderTargetProperties.__webglColorRenderbuffer = [];
  48798. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  48799. for ( let i = 0; i < textures.length; i ++ ) {
  48800. const texture = textures[ i ];
  48801. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  48802. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48803. const glFormat = utils.convert( texture.format, texture.colorSpace );
  48804. const glType = utils.convert( texture.type );
  48805. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  48806. const samples = getRenderTargetSamples( renderTarget );
  48807. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  48808. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48809. }
  48810. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  48811. if ( renderTarget.depthBuffer ) {
  48812. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  48813. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  48814. }
  48815. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  48816. }
  48817. }
  48818. // Setup color buffer
  48819. if ( isCube ) {
  48820. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  48821. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  48822. for ( let i = 0; i < 6; i ++ ) {
  48823. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  48824. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  48825. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  48826. }
  48827. } else {
  48828. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  48829. }
  48830. }
  48831. if ( textureNeedsGenerateMipmaps( texture ) ) {
  48832. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  48833. }
  48834. state.unbindTexture();
  48835. } else if ( isMultipleRenderTargets ) {
  48836. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48837. const attachment = textures[ i ];
  48838. const attachmentProperties = properties.get( attachment );
  48839. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  48840. setTextureParameters( _gl.TEXTURE_2D, attachment );
  48841. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  48842. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  48843. generateMipmap( _gl.TEXTURE_2D );
  48844. }
  48845. }
  48846. state.unbindTexture();
  48847. } else {
  48848. let glTextureType = _gl.TEXTURE_2D;
  48849. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  48850. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  48851. }
  48852. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  48853. setTextureParameters( glTextureType, texture );
  48854. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  48855. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  48856. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  48857. }
  48858. } else {
  48859. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  48860. }
  48861. if ( textureNeedsGenerateMipmaps( texture ) ) {
  48862. generateMipmap( glTextureType );
  48863. }
  48864. state.unbindTexture();
  48865. }
  48866. // Setup depth and stencil buffers
  48867. if ( renderTarget.depthBuffer ) {
  48868. setupDepthRenderbuffer( renderTarget );
  48869. }
  48870. }
  48871. function updateRenderTargetMipmap( renderTarget ) {
  48872. const textures = renderTarget.textures;
  48873. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48874. const texture = textures[ i ];
  48875. if ( textureNeedsGenerateMipmaps( texture ) ) {
  48876. const targetType = getTargetType( renderTarget );
  48877. const webglTexture = properties.get( texture ).__webglTexture;
  48878. state.bindTexture( targetType, webglTexture );
  48879. generateMipmap( targetType );
  48880. state.unbindTexture();
  48881. }
  48882. }
  48883. }
  48884. const invalidationArrayRead = [];
  48885. const invalidationArrayDraw = [];
  48886. function updateMultisampleRenderTarget( renderTarget ) {
  48887. if ( renderTarget.samples > 0 ) {
  48888. if ( useMultisampledRTT( renderTarget ) === false ) {
  48889. const textures = renderTarget.textures;
  48890. const width = renderTarget.width;
  48891. const height = renderTarget.height;
  48892. let mask = _gl.COLOR_BUFFER_BIT;
  48893. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  48894. const renderTargetProperties = properties.get( renderTarget );
  48895. const isMultipleRenderTargets = ( textures.length > 1 );
  48896. // If MRT we need to remove FBO attachments
  48897. if ( isMultipleRenderTargets ) {
  48898. for ( let i = 0; i < textures.length; i ++ ) {
  48899. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  48900. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  48901. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  48902. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  48903. }
  48904. }
  48905. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  48906. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  48907. for ( let i = 0; i < textures.length; i ++ ) {
  48908. if ( renderTarget.resolveDepthBuffer ) {
  48909. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  48910. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  48911. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  48912. }
  48913. if ( isMultipleRenderTargets ) {
  48914. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48915. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  48916. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  48917. }
  48918. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  48919. if ( supportsInvalidateFramebuffer === true ) {
  48920. invalidationArrayRead.length = 0;
  48921. invalidationArrayDraw.length = 0;
  48922. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  48923. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  48924. invalidationArrayRead.push( depthStyle );
  48925. invalidationArrayDraw.push( depthStyle );
  48926. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  48927. }
  48928. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  48929. }
  48930. }
  48931. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  48932. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  48933. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  48934. if ( isMultipleRenderTargets ) {
  48935. for ( let i = 0; i < textures.length; i ++ ) {
  48936. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  48937. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  48938. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  48939. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  48940. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  48941. }
  48942. }
  48943. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  48944. } else {
  48945. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  48946. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  48947. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  48948. }
  48949. }
  48950. }
  48951. }
  48952. function getRenderTargetSamples( renderTarget ) {
  48953. return Math.min( capabilities.maxSamples, renderTarget.samples );
  48954. }
  48955. function useMultisampledRTT( renderTarget ) {
  48956. const renderTargetProperties = properties.get( renderTarget );
  48957. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  48958. }
  48959. function updateVideoTexture( texture ) {
  48960. const frame = info.render.frame;
  48961. // Check the last frame we updated the VideoTexture
  48962. if ( _videoTextures.get( texture ) !== frame ) {
  48963. _videoTextures.set( texture, frame );
  48964. texture.update();
  48965. }
  48966. }
  48967. function verifyColorSpace( texture, image ) {
  48968. const colorSpace = texture.colorSpace;
  48969. const format = texture.format;
  48970. const type = texture.type;
  48971. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  48972. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  48973. // sRGB
  48974. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  48975. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  48976. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  48977. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  48978. }
  48979. } else {
  48980. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  48981. }
  48982. }
  48983. return image;
  48984. }
  48985. function getDimensions( image ) {
  48986. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  48987. // if intrinsic data are not available, fallback to width/height
  48988. _imageDimensions.width = image.naturalWidth || image.width;
  48989. _imageDimensions.height = image.naturalHeight || image.height;
  48990. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  48991. _imageDimensions.width = image.displayWidth;
  48992. _imageDimensions.height = image.displayHeight;
  48993. } else {
  48994. _imageDimensions.width = image.width;
  48995. _imageDimensions.height = image.height;
  48996. }
  48997. return _imageDimensions;
  48998. }
  48999. //
  49000. this.allocateTextureUnit = allocateTextureUnit;
  49001. this.resetTextureUnits = resetTextureUnits;
  49002. this.setTexture2D = setTexture2D;
  49003. this.setTexture2DArray = setTexture2DArray;
  49004. this.setTexture3D = setTexture3D;
  49005. this.setTextureCube = setTextureCube;
  49006. this.rebindTextures = rebindTextures;
  49007. this.setupRenderTarget = setupRenderTarget;
  49008. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  49009. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  49010. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  49011. this.setupFrameBufferTexture = setupFrameBufferTexture;
  49012. this.useMultisampledRTT = useMultisampledRTT;
  49013. }
  49014. function WebGLUtils( gl, extensions ) {
  49015. function convert( p, colorSpace = NoColorSpace ) {
  49016. let extension;
  49017. const transfer = ColorManagement.getTransfer( colorSpace );
  49018. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  49019. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  49020. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  49021. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  49022. if ( p === ByteType ) return gl.BYTE;
  49023. if ( p === ShortType ) return gl.SHORT;
  49024. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  49025. if ( p === IntType ) return gl.INT;
  49026. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  49027. if ( p === FloatType ) return gl.FLOAT;
  49028. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  49029. if ( p === AlphaFormat ) return gl.ALPHA;
  49030. if ( p === RGBFormat ) return gl.RGB;
  49031. if ( p === RGBAFormat ) return gl.RGBA;
  49032. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  49033. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  49034. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  49035. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  49036. // WebGL2 formats.
  49037. if ( p === RedFormat ) return gl.RED;
  49038. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  49039. if ( p === RGFormat ) return gl.RG;
  49040. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  49041. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  49042. // S3TC
  49043. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  49044. if ( transfer === SRGBTransfer ) {
  49045. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  49046. if ( extension !== null ) {
  49047. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  49048. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  49049. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  49050. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  49051. } else {
  49052. return null;
  49053. }
  49054. } else {
  49055. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  49056. if ( extension !== null ) {
  49057. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  49058. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49059. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49060. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49061. } else {
  49062. return null;
  49063. }
  49064. }
  49065. }
  49066. // PVRTC
  49067. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  49068. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  49069. if ( extension !== null ) {
  49070. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  49071. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  49072. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  49073. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  49074. } else {
  49075. return null;
  49076. }
  49077. }
  49078. // ETC
  49079. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  49080. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  49081. if ( extension !== null ) {
  49082. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  49083. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  49084. } else {
  49085. return null;
  49086. }
  49087. }
  49088. // ASTC
  49089. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  49090. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  49091. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  49092. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  49093. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  49094. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  49095. if ( extension !== null ) {
  49096. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  49097. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  49098. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  49099. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  49100. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  49101. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  49102. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  49103. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  49104. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  49105. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  49106. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  49107. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  49108. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  49109. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  49110. } else {
  49111. return null;
  49112. }
  49113. }
  49114. // BPTC
  49115. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  49116. extension = extensions.get( 'EXT_texture_compression_bptc' );
  49117. if ( extension !== null ) {
  49118. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  49119. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  49120. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  49121. } else {
  49122. return null;
  49123. }
  49124. }
  49125. // RGTC
  49126. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  49127. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  49128. if ( extension !== null ) {
  49129. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  49130. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  49131. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  49132. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  49133. } else {
  49134. return null;
  49135. }
  49136. }
  49137. //
  49138. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  49139. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  49140. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  49141. }
  49142. return { convert: convert };
  49143. }
  49144. const _occlusion_vertex = `
  49145. void main() {
  49146. gl_Position = vec4( position, 1.0 );
  49147. }`;
  49148. const _occlusion_fragment = `
  49149. uniform sampler2DArray depthColor;
  49150. uniform float depthWidth;
  49151. uniform float depthHeight;
  49152. void main() {
  49153. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  49154. if ( coord.x >= 1.0 ) {
  49155. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  49156. } else {
  49157. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  49158. }
  49159. }`;
  49160. /**
  49161. * A XR module that manages the access to the Depth Sensing API.
  49162. */
  49163. class WebXRDepthSensing {
  49164. /**
  49165. * Constructs a new depth sensing module.
  49166. */
  49167. constructor() {
  49168. /**
  49169. * A texture representing the depth of the user's environment.
  49170. *
  49171. * @type {?Texture}
  49172. */
  49173. this.texture = null;
  49174. /**
  49175. * A plane mesh for visualizing the depth texture.
  49176. *
  49177. * @type {?Mesh}
  49178. */
  49179. this.mesh = null;
  49180. /**
  49181. * The depth near value.
  49182. *
  49183. * @type {number}
  49184. */
  49185. this.depthNear = 0;
  49186. /**
  49187. * The depth near far.
  49188. *
  49189. * @type {number}
  49190. */
  49191. this.depthFar = 0;
  49192. }
  49193. /**
  49194. * Inits the depth sensing module
  49195. *
  49196. * @param {WebGLRenderer} renderer - The renderer.
  49197. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  49198. * @param {XRRenderState} renderState - The XR render state.
  49199. */
  49200. init( renderer, depthData, renderState ) {
  49201. if ( this.texture === null ) {
  49202. const texture = new Texture();
  49203. const texProps = renderer.properties.get( texture );
  49204. texProps.__webglTexture = depthData.texture;
  49205. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  49206. this.depthNear = depthData.depthNear;
  49207. this.depthFar = depthData.depthFar;
  49208. }
  49209. this.texture = texture;
  49210. }
  49211. }
  49212. /**
  49213. * Returns a plane mesh that visualizes the depth texture.
  49214. *
  49215. * @param {ArrayCamera} cameraXR - The XR camera.
  49216. * @return {?Mesh} The plane mesh.
  49217. */
  49218. getMesh( cameraXR ) {
  49219. if ( this.texture !== null ) {
  49220. if ( this.mesh === null ) {
  49221. const viewport = cameraXR.cameras[ 0 ].viewport;
  49222. const material = new ShaderMaterial( {
  49223. vertexShader: _occlusion_vertex,
  49224. fragmentShader: _occlusion_fragment,
  49225. uniforms: {
  49226. depthColor: { value: this.texture },
  49227. depthWidth: { value: viewport.z },
  49228. depthHeight: { value: viewport.w }
  49229. }
  49230. } );
  49231. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  49232. }
  49233. }
  49234. return this.mesh;
  49235. }
  49236. /**
  49237. * Resets the module
  49238. */
  49239. reset() {
  49240. this.texture = null;
  49241. this.mesh = null;
  49242. }
  49243. /**
  49244. * Returns a texture representing the depth of the user's environment.
  49245. *
  49246. * @return {?Texture} The depth texture.
  49247. */
  49248. getDepthTexture() {
  49249. return this.texture;
  49250. }
  49251. }
  49252. /**
  49253. * This class represents an abstraction of the WebXR Device API and is
  49254. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  49255. * interface that allows users to enable/disable XR and perform XR related
  49256. * tasks like for instance retrieving controllers.
  49257. *
  49258. * @augments EventDispatcher
  49259. * @hideconstructor
  49260. */
  49261. class WebXRManager extends EventDispatcher {
  49262. /**
  49263. * Constructs a new WebGL renderer.
  49264. *
  49265. * @param {WebGLRenderer} renderer - The renderer.
  49266. * @param {WebGL2RenderingContext} gl - The rendering context.
  49267. */
  49268. constructor( renderer, gl ) {
  49269. super();
  49270. const scope = this;
  49271. let session = null;
  49272. let framebufferScaleFactor = 1.0;
  49273. let referenceSpace = null;
  49274. let referenceSpaceType = 'local-floor';
  49275. // Set default foveation to maximum.
  49276. let foveation = 1.0;
  49277. let customReferenceSpace = null;
  49278. let pose = null;
  49279. let glBinding = null;
  49280. let glProjLayer = null;
  49281. let glBaseLayer = null;
  49282. let xrFrame = null;
  49283. const depthSensing = new WebXRDepthSensing();
  49284. const attributes = gl.getContextAttributes();
  49285. let initialRenderTarget = null;
  49286. let newRenderTarget = null;
  49287. const controllers = [];
  49288. const controllerInputSources = [];
  49289. const currentSize = new Vector2();
  49290. let currentPixelRatio = null;
  49291. //
  49292. const cameraL = new PerspectiveCamera();
  49293. cameraL.viewport = new Vector4();
  49294. const cameraR = new PerspectiveCamera();
  49295. cameraR.viewport = new Vector4();
  49296. const cameras = [ cameraL, cameraR ];
  49297. const cameraXR = new ArrayCamera();
  49298. let _currentDepthNear = null;
  49299. let _currentDepthFar = null;
  49300. //
  49301. /**
  49302. * Whether the manager's XR camera should be automatically updated or not.
  49303. *
  49304. * @type {boolean}
  49305. * @default true
  49306. */
  49307. this.cameraAutoUpdate = true;
  49308. /**
  49309. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  49310. * if you are going to use XR in your app.
  49311. *
  49312. * @type {boolean}
  49313. * @default false
  49314. */
  49315. this.enabled = false;
  49316. /**
  49317. * Whether XR presentation is active or not.
  49318. *
  49319. * @type {boolean}
  49320. * @readonly
  49321. * @default false
  49322. */
  49323. this.isPresenting = false;
  49324. /**
  49325. * Returns a group representing the `target ray` space of the XR controller.
  49326. * Use this space for visualizing 3D objects that support the user in pointing
  49327. * tasks like UI interaction.
  49328. *
  49329. * @param {number} index - The index of the controller.
  49330. * @return {Group} A group representing the `target ray` space.
  49331. */
  49332. this.getController = function ( index ) {
  49333. let controller = controllers[ index ];
  49334. if ( controller === undefined ) {
  49335. controller = new WebXRController();
  49336. controllers[ index ] = controller;
  49337. }
  49338. return controller.getTargetRaySpace();
  49339. };
  49340. /**
  49341. * Returns a group representing the `grip` space of the XR controller.
  49342. * Use this space for visualizing 3D objects that support the user in pointing
  49343. * tasks like UI interaction.
  49344. *
  49345. * Note: If you want to show something in the user's hand AND offer a
  49346. * pointing ray at the same time, you'll want to attached the handheld object
  49347. * to the group returned by `getControllerGrip()` and the ray to the
  49348. * group returned by `getController()`. The idea is to have two
  49349. * different groups in two different coordinate spaces for the same WebXR
  49350. * controller.
  49351. *
  49352. * @param {number} index - The index of the controller.
  49353. * @return {Group} A group representing the `grip` space.
  49354. */
  49355. this.getControllerGrip = function ( index ) {
  49356. let controller = controllers[ index ];
  49357. if ( controller === undefined ) {
  49358. controller = new WebXRController();
  49359. controllers[ index ] = controller;
  49360. }
  49361. return controller.getGripSpace();
  49362. };
  49363. /**
  49364. * Returns a group representing the `hand` space of the XR controller.
  49365. * Use this space for visualizing 3D objects that support the user in pointing
  49366. * tasks like UI interaction.
  49367. *
  49368. * @param {number} index - The index of the controller.
  49369. * @return {Group} A group representing the `hand` space.
  49370. */
  49371. this.getHand = function ( index ) {
  49372. let controller = controllers[ index ];
  49373. if ( controller === undefined ) {
  49374. controller = new WebXRController();
  49375. controllers[ index ] = controller;
  49376. }
  49377. return controller.getHandSpace();
  49378. };
  49379. //
  49380. function onSessionEvent( event ) {
  49381. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  49382. if ( controllerIndex === - 1 ) {
  49383. return;
  49384. }
  49385. const controller = controllers[ controllerIndex ];
  49386. if ( controller !== undefined ) {
  49387. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  49388. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  49389. }
  49390. }
  49391. function onSessionEnd() {
  49392. session.removeEventListener( 'select', onSessionEvent );
  49393. session.removeEventListener( 'selectstart', onSessionEvent );
  49394. session.removeEventListener( 'selectend', onSessionEvent );
  49395. session.removeEventListener( 'squeeze', onSessionEvent );
  49396. session.removeEventListener( 'squeezestart', onSessionEvent );
  49397. session.removeEventListener( 'squeezeend', onSessionEvent );
  49398. session.removeEventListener( 'end', onSessionEnd );
  49399. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  49400. for ( let i = 0; i < controllers.length; i ++ ) {
  49401. const inputSource = controllerInputSources[ i ];
  49402. if ( inputSource === null ) continue;
  49403. controllerInputSources[ i ] = null;
  49404. controllers[ i ].disconnect( inputSource );
  49405. }
  49406. _currentDepthNear = null;
  49407. _currentDepthFar = null;
  49408. depthSensing.reset();
  49409. // restore framebuffer/rendering state
  49410. renderer.setRenderTarget( initialRenderTarget );
  49411. glBaseLayer = null;
  49412. glProjLayer = null;
  49413. glBinding = null;
  49414. session = null;
  49415. newRenderTarget = null;
  49416. //
  49417. animation.stop();
  49418. scope.isPresenting = false;
  49419. renderer.setPixelRatio( currentPixelRatio );
  49420. renderer.setSize( currentSize.width, currentSize.height, false );
  49421. scope.dispatchEvent( { type: 'sessionend' } );
  49422. }
  49423. /**
  49424. * Sets the framebuffer scale factor.
  49425. *
  49426. * This method can not be used during a XR session.
  49427. *
  49428. * @param {number} value - The framebuffer scale factor.
  49429. */
  49430. this.setFramebufferScaleFactor = function ( value ) {
  49431. framebufferScaleFactor = value;
  49432. if ( scope.isPresenting === true ) {
  49433. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  49434. }
  49435. };
  49436. /**
  49437. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  49438. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  49439. * improve tracking. Default is `local-floor`.
  49440. *
  49441. * This method can not be used during a XR session.
  49442. *
  49443. * @param {string} value - The reference space type.
  49444. */
  49445. this.setReferenceSpaceType = function ( value ) {
  49446. referenceSpaceType = value;
  49447. if ( scope.isPresenting === true ) {
  49448. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  49449. }
  49450. };
  49451. /**
  49452. * Returns the XR reference space.
  49453. *
  49454. * @return {XRReferenceSpace} The XR reference space.
  49455. */
  49456. this.getReferenceSpace = function () {
  49457. return customReferenceSpace || referenceSpace;
  49458. };
  49459. /**
  49460. * Sets a custom XR reference space.
  49461. *
  49462. * @param {XRReferenceSpace} space - The XR reference space.
  49463. */
  49464. this.setReferenceSpace = function ( space ) {
  49465. customReferenceSpace = space;
  49466. };
  49467. /**
  49468. * Returns the current base layer.
  49469. *
  49470. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  49471. */
  49472. this.getBaseLayer = function () {
  49473. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  49474. };
  49475. /**
  49476. * Returns the current XR binding.
  49477. *
  49478. * @return {?XRWebGLBinding} The XR binding.
  49479. */
  49480. this.getBinding = function () {
  49481. return glBinding;
  49482. };
  49483. /**
  49484. * Returns the current XR frame.
  49485. *
  49486. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  49487. */
  49488. this.getFrame = function () {
  49489. return xrFrame;
  49490. };
  49491. /**
  49492. * Returns the current XR session.
  49493. *
  49494. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  49495. */
  49496. this.getSession = function () {
  49497. return session;
  49498. };
  49499. /**
  49500. * After a XR session has been requested usually with one of the `*Button` modules, it
  49501. * is injected into the renderer with this method. This method triggers the start of
  49502. * the actual XR rendering.
  49503. *
  49504. * @async
  49505. * @param {XRSession} value - The XR session to set.
  49506. * @return {Promise} A Promise that resolves when the session has been set.
  49507. */
  49508. this.setSession = async function ( value ) {
  49509. session = value;
  49510. if ( session !== null ) {
  49511. initialRenderTarget = renderer.getRenderTarget();
  49512. session.addEventListener( 'select', onSessionEvent );
  49513. session.addEventListener( 'selectstart', onSessionEvent );
  49514. session.addEventListener( 'selectend', onSessionEvent );
  49515. session.addEventListener( 'squeeze', onSessionEvent );
  49516. session.addEventListener( 'squeezestart', onSessionEvent );
  49517. session.addEventListener( 'squeezeend', onSessionEvent );
  49518. session.addEventListener( 'end', onSessionEnd );
  49519. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  49520. if ( attributes.xrCompatible !== true ) {
  49521. await gl.makeXRCompatible();
  49522. }
  49523. currentPixelRatio = renderer.getPixelRatio();
  49524. renderer.getSize( currentSize );
  49525. // Check that the browser implements the necessary APIs to use an
  49526. // XRProjectionLayer rather than an XRWebGLLayer
  49527. const useLayers = typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype;
  49528. if ( ! useLayers ) {
  49529. const layerInit = {
  49530. antialias: attributes.antialias,
  49531. alpha: true,
  49532. depth: attributes.depth,
  49533. stencil: attributes.stencil,
  49534. framebufferScaleFactor: framebufferScaleFactor
  49535. };
  49536. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  49537. session.updateRenderState( { baseLayer: glBaseLayer } );
  49538. renderer.setPixelRatio( 1 );
  49539. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  49540. newRenderTarget = new WebGLRenderTarget(
  49541. glBaseLayer.framebufferWidth,
  49542. glBaseLayer.framebufferHeight,
  49543. {
  49544. format: RGBAFormat,
  49545. type: UnsignedByteType,
  49546. colorSpace: renderer.outputColorSpace,
  49547. stencilBuffer: attributes.stencil,
  49548. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  49549. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  49550. }
  49551. );
  49552. } else {
  49553. let depthFormat = null;
  49554. let depthType = null;
  49555. let glDepthFormat = null;
  49556. if ( attributes.depth ) {
  49557. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  49558. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  49559. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  49560. }
  49561. const projectionlayerInit = {
  49562. colorFormat: gl.RGBA8,
  49563. depthFormat: glDepthFormat,
  49564. scaleFactor: framebufferScaleFactor
  49565. };
  49566. glBinding = new XRWebGLBinding( session, gl );
  49567. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  49568. session.updateRenderState( { layers: [ glProjLayer ] } );
  49569. renderer.setPixelRatio( 1 );
  49570. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  49571. newRenderTarget = new WebGLRenderTarget(
  49572. glProjLayer.textureWidth,
  49573. glProjLayer.textureHeight,
  49574. {
  49575. format: RGBAFormat,
  49576. type: UnsignedByteType,
  49577. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  49578. stencilBuffer: attributes.stencil,
  49579. colorSpace: renderer.outputColorSpace,
  49580. samples: attributes.antialias ? 4 : 0,
  49581. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  49582. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  49583. } );
  49584. }
  49585. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  49586. this.setFoveation( foveation );
  49587. customReferenceSpace = null;
  49588. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  49589. animation.setContext( session );
  49590. animation.start();
  49591. scope.isPresenting = true;
  49592. scope.dispatchEvent( { type: 'sessionstart' } );
  49593. }
  49594. };
  49595. /**
  49596. * Returns the environment blend mode from the current XR session.
  49597. *
  49598. * @return {?('opaque'|'additive'|'alpha-blend')} The environment blend mode. Returns `null` when used outside of a XR session.
  49599. */
  49600. this.getEnvironmentBlendMode = function () {
  49601. if ( session !== null ) {
  49602. return session.environmentBlendMode;
  49603. }
  49604. };
  49605. /**
  49606. * Returns the current depth texture computed via depth sensing.
  49607. *
  49608. * @return {?Texture} The depth texture.
  49609. */
  49610. this.getDepthTexture = function () {
  49611. return depthSensing.getDepthTexture();
  49612. };
  49613. function onInputSourcesChange( event ) {
  49614. // Notify disconnected
  49615. for ( let i = 0; i < event.removed.length; i ++ ) {
  49616. const inputSource = event.removed[ i ];
  49617. const index = controllerInputSources.indexOf( inputSource );
  49618. if ( index >= 0 ) {
  49619. controllerInputSources[ index ] = null;
  49620. controllers[ index ].disconnect( inputSource );
  49621. }
  49622. }
  49623. // Notify connected
  49624. for ( let i = 0; i < event.added.length; i ++ ) {
  49625. const inputSource = event.added[ i ];
  49626. let controllerIndex = controllerInputSources.indexOf( inputSource );
  49627. if ( controllerIndex === - 1 ) {
  49628. // Assign input source a controller that currently has no input source
  49629. for ( let i = 0; i < controllers.length; i ++ ) {
  49630. if ( i >= controllerInputSources.length ) {
  49631. controllerInputSources.push( inputSource );
  49632. controllerIndex = i;
  49633. break;
  49634. } else if ( controllerInputSources[ i ] === null ) {
  49635. controllerInputSources[ i ] = inputSource;
  49636. controllerIndex = i;
  49637. break;
  49638. }
  49639. }
  49640. // If all controllers do currently receive input we ignore new ones
  49641. if ( controllerIndex === - 1 ) break;
  49642. }
  49643. const controller = controllers[ controllerIndex ];
  49644. if ( controller ) {
  49645. controller.connect( inputSource );
  49646. }
  49647. }
  49648. }
  49649. //
  49650. const cameraLPos = new Vector3();
  49651. const cameraRPos = new Vector3();
  49652. /**
  49653. * Assumes 2 cameras that are parallel and share an X-axis, and that
  49654. * the cameras' projection and world matrices have already been set.
  49655. * And that near and far planes are identical for both cameras.
  49656. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  49657. *
  49658. * @param {ArrayCamera} camera - The camera to update.
  49659. * @param {PerspectiveCamera} cameraL - The left camera.
  49660. * @param {PerspectiveCamera} cameraR - The right camera.
  49661. */
  49662. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  49663. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  49664. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  49665. const ipd = cameraLPos.distanceTo( cameraRPos );
  49666. const projL = cameraL.projectionMatrix.elements;
  49667. const projR = cameraR.projectionMatrix.elements;
  49668. // VR systems will have identical far and near planes, and
  49669. // most likely identical top and bottom frustum extents.
  49670. // Use the left camera for these values.
  49671. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  49672. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  49673. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  49674. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  49675. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  49676. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  49677. const left = near * leftFov;
  49678. const right = near * rightFov;
  49679. // Calculate the new camera's position offset from the
  49680. // left camera. xOffset should be roughly half `ipd`.
  49681. const zOffset = ipd / ( - leftFov + rightFov );
  49682. const xOffset = zOffset * - leftFov;
  49683. // TODO: Better way to apply this offset?
  49684. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  49685. camera.translateX( xOffset );
  49686. camera.translateZ( zOffset );
  49687. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  49688. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  49689. // Check if the projection uses an infinite far plane.
  49690. if ( projL[ 10 ] === - 1.0 ) {
  49691. // Use the projection matrix from the left eye.
  49692. // The camera offset is sufficient to include the view volumes
  49693. // of both eyes (assuming symmetric projections).
  49694. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  49695. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  49696. } else {
  49697. // Find the union of the frustum values of the cameras and scale
  49698. // the values so that the near plane's position does not change in world space,
  49699. // although must now be relative to the new union camera.
  49700. const near2 = near + zOffset;
  49701. const far2 = far + zOffset;
  49702. const left2 = left - xOffset;
  49703. const right2 = right + ( ipd - xOffset );
  49704. const top2 = topFov * far / far2 * near2;
  49705. const bottom2 = bottomFov * far / far2 * near2;
  49706. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  49707. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  49708. }
  49709. }
  49710. function updateCamera( camera, parent ) {
  49711. if ( parent === null ) {
  49712. camera.matrixWorld.copy( camera.matrix );
  49713. } else {
  49714. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  49715. }
  49716. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  49717. }
  49718. /**
  49719. * Updates the state of the XR camera. Use this method on app level if you
  49720. * set cameraAutoUpdate` to `false`. The method requires the non-XR
  49721. * camera of the scene as a parameter. The passed in camera's transformation
  49722. * is automatically adjusted to the position of the XR camera when calling
  49723. * this method.
  49724. *
  49725. * @param {Camera} camera - The camera.
  49726. */
  49727. this.updateCamera = function ( camera ) {
  49728. if ( session === null ) return;
  49729. let depthNear = camera.near;
  49730. let depthFar = camera.far;
  49731. if ( depthSensing.texture !== null ) {
  49732. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  49733. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  49734. }
  49735. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  49736. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  49737. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  49738. // Note that the new renderState won't apply until the next frame. See #18320
  49739. session.updateRenderState( {
  49740. depthNear: cameraXR.near,
  49741. depthFar: cameraXR.far
  49742. } );
  49743. _currentDepthNear = cameraXR.near;
  49744. _currentDepthFar = cameraXR.far;
  49745. }
  49746. cameraL.layers.mask = camera.layers.mask | 0b010;
  49747. cameraR.layers.mask = camera.layers.mask | 0b100;
  49748. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  49749. const parent = camera.parent;
  49750. const cameras = cameraXR.cameras;
  49751. updateCamera( cameraXR, parent );
  49752. for ( let i = 0; i < cameras.length; i ++ ) {
  49753. updateCamera( cameras[ i ], parent );
  49754. }
  49755. // update projection matrix for proper view frustum culling
  49756. if ( cameras.length === 2 ) {
  49757. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  49758. } else {
  49759. // assume single camera setup (AR)
  49760. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  49761. }
  49762. // update user camera and its children
  49763. updateUserCamera( camera, cameraXR, parent );
  49764. };
  49765. function updateUserCamera( camera, cameraXR, parent ) {
  49766. if ( parent === null ) {
  49767. camera.matrix.copy( cameraXR.matrixWorld );
  49768. } else {
  49769. camera.matrix.copy( parent.matrixWorld );
  49770. camera.matrix.invert();
  49771. camera.matrix.multiply( cameraXR.matrixWorld );
  49772. }
  49773. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  49774. camera.updateMatrixWorld( true );
  49775. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  49776. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  49777. if ( camera.isPerspectiveCamera ) {
  49778. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  49779. camera.zoom = 1;
  49780. }
  49781. }
  49782. /**
  49783. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  49784. * of the active XR session. For each view it holds a separate camera object.
  49785. *
  49786. * The camera's `fov` is currently not used and does not reflect the fov of
  49787. * the XR camera. If you need the fov on app level, you have to compute in
  49788. * manually from the XR camera's projection matrices.
  49789. *
  49790. * @return {ArrayCamera} The XR camera.
  49791. */
  49792. this.getCamera = function () {
  49793. return cameraXR;
  49794. };
  49795. /**
  49796. * Returns the amount of foveation used by the XR compositor for the projection layer.
  49797. *
  49798. * @return {number} The amount of foveation.
  49799. */
  49800. this.getFoveation = function () {
  49801. if ( glProjLayer === null && glBaseLayer === null ) {
  49802. return undefined;
  49803. }
  49804. return foveation;
  49805. };
  49806. /**
  49807. * Sets the foveation value.
  49808. *
  49809. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  49810. * and `1` means maximum foveation (the edges render at lower resolution).
  49811. */
  49812. this.setFoveation = function ( value ) {
  49813. // 0 = no foveation = full resolution
  49814. // 1 = maximum foveation = the edges render at lower resolution
  49815. foveation = value;
  49816. if ( glProjLayer !== null ) {
  49817. glProjLayer.fixedFoveation = value;
  49818. }
  49819. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  49820. glBaseLayer.fixedFoveation = value;
  49821. }
  49822. };
  49823. /**
  49824. * Returns `true` if depth sensing is supported.
  49825. *
  49826. * @return {boolean} Whether depth sensing is supported or not.
  49827. */
  49828. this.hasDepthSensing = function () {
  49829. return depthSensing.texture !== null;
  49830. };
  49831. /**
  49832. * Returns the depth sensing mesh.
  49833. *
  49834. * @return {Mesh} The depth sensing mesh.
  49835. */
  49836. this.getDepthSensingMesh = function () {
  49837. return depthSensing.getMesh( cameraXR );
  49838. };
  49839. // Animation Loop
  49840. let onAnimationFrameCallback = null;
  49841. function onAnimationFrame( time, frame ) {
  49842. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  49843. xrFrame = frame;
  49844. if ( pose !== null ) {
  49845. const views = pose.views;
  49846. if ( glBaseLayer !== null ) {
  49847. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  49848. renderer.setRenderTarget( newRenderTarget );
  49849. }
  49850. let cameraXRNeedsUpdate = false;
  49851. // check if it's necessary to rebuild cameraXR's camera list
  49852. if ( views.length !== cameraXR.cameras.length ) {
  49853. cameraXR.cameras.length = 0;
  49854. cameraXRNeedsUpdate = true;
  49855. }
  49856. for ( let i = 0; i < views.length; i ++ ) {
  49857. const view = views[ i ];
  49858. let viewport = null;
  49859. if ( glBaseLayer !== null ) {
  49860. viewport = glBaseLayer.getViewport( view );
  49861. } else {
  49862. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  49863. viewport = glSubImage.viewport;
  49864. // For side-by-side projection, we only produce a single texture for both eyes.
  49865. if ( i === 0 ) {
  49866. renderer.setRenderTargetTextures(
  49867. newRenderTarget,
  49868. glSubImage.colorTexture,
  49869. glSubImage.depthStencilTexture );
  49870. renderer.setRenderTarget( newRenderTarget );
  49871. }
  49872. }
  49873. let camera = cameras[ i ];
  49874. if ( camera === undefined ) {
  49875. camera = new PerspectiveCamera();
  49876. camera.layers.enable( i );
  49877. camera.viewport = new Vector4();
  49878. cameras[ i ] = camera;
  49879. }
  49880. camera.matrix.fromArray( view.transform.matrix );
  49881. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  49882. camera.projectionMatrix.fromArray( view.projectionMatrix );
  49883. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  49884. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  49885. if ( i === 0 ) {
  49886. cameraXR.matrix.copy( camera.matrix );
  49887. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  49888. }
  49889. if ( cameraXRNeedsUpdate === true ) {
  49890. cameraXR.cameras.push( camera );
  49891. }
  49892. }
  49893. //
  49894. const enabledFeatures = session.enabledFeatures;
  49895. const gpuDepthSensingEnabled = enabledFeatures &&
  49896. enabledFeatures.includes( 'depth-sensing' ) &&
  49897. session.depthUsage == 'gpu-optimized';
  49898. if ( gpuDepthSensingEnabled && glBinding ) {
  49899. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  49900. if ( depthData && depthData.isValid && depthData.texture ) {
  49901. depthSensing.init( renderer, depthData, session.renderState );
  49902. }
  49903. }
  49904. }
  49905. //
  49906. for ( let i = 0; i < controllers.length; i ++ ) {
  49907. const inputSource = controllerInputSources[ i ];
  49908. const controller = controllers[ i ];
  49909. if ( inputSource !== null && controller !== undefined ) {
  49910. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  49911. }
  49912. }
  49913. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  49914. if ( frame.detectedPlanes ) {
  49915. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  49916. }
  49917. xrFrame = null;
  49918. }
  49919. const animation = new WebGLAnimation();
  49920. animation.setAnimationLoop( onAnimationFrame );
  49921. this.setAnimationLoop = function ( callback ) {
  49922. onAnimationFrameCallback = callback;
  49923. };
  49924. this.dispose = function () {};
  49925. }
  49926. }
  49927. const _e1 = /*@__PURE__*/ new Euler();
  49928. const _m1 = /*@__PURE__*/ new Matrix4();
  49929. function WebGLMaterials( renderer, properties ) {
  49930. function refreshTransformUniform( map, uniform ) {
  49931. if ( map.matrixAutoUpdate === true ) {
  49932. map.updateMatrix();
  49933. }
  49934. uniform.value.copy( map.matrix );
  49935. }
  49936. function refreshFogUniforms( uniforms, fog ) {
  49937. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  49938. if ( fog.isFog ) {
  49939. uniforms.fogNear.value = fog.near;
  49940. uniforms.fogFar.value = fog.far;
  49941. } else if ( fog.isFogExp2 ) {
  49942. uniforms.fogDensity.value = fog.density;
  49943. }
  49944. }
  49945. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  49946. if ( material.isMeshBasicMaterial ) {
  49947. refreshUniformsCommon( uniforms, material );
  49948. } else if ( material.isMeshLambertMaterial ) {
  49949. refreshUniformsCommon( uniforms, material );
  49950. } else if ( material.isMeshToonMaterial ) {
  49951. refreshUniformsCommon( uniforms, material );
  49952. refreshUniformsToon( uniforms, material );
  49953. } else if ( material.isMeshPhongMaterial ) {
  49954. refreshUniformsCommon( uniforms, material );
  49955. refreshUniformsPhong( uniforms, material );
  49956. } else if ( material.isMeshStandardMaterial ) {
  49957. refreshUniformsCommon( uniforms, material );
  49958. refreshUniformsStandard( uniforms, material );
  49959. if ( material.isMeshPhysicalMaterial ) {
  49960. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  49961. }
  49962. } else if ( material.isMeshMatcapMaterial ) {
  49963. refreshUniformsCommon( uniforms, material );
  49964. refreshUniformsMatcap( uniforms, material );
  49965. } else if ( material.isMeshDepthMaterial ) {
  49966. refreshUniformsCommon( uniforms, material );
  49967. } else if ( material.isMeshDistanceMaterial ) {
  49968. refreshUniformsCommon( uniforms, material );
  49969. refreshUniformsDistance( uniforms, material );
  49970. } else if ( material.isMeshNormalMaterial ) {
  49971. refreshUniformsCommon( uniforms, material );
  49972. } else if ( material.isLineBasicMaterial ) {
  49973. refreshUniformsLine( uniforms, material );
  49974. if ( material.isLineDashedMaterial ) {
  49975. refreshUniformsDash( uniforms, material );
  49976. }
  49977. } else if ( material.isPointsMaterial ) {
  49978. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  49979. } else if ( material.isSpriteMaterial ) {
  49980. refreshUniformsSprites( uniforms, material );
  49981. } else if ( material.isShadowMaterial ) {
  49982. uniforms.color.value.copy( material.color );
  49983. uniforms.opacity.value = material.opacity;
  49984. } else if ( material.isShaderMaterial ) {
  49985. material.uniformsNeedUpdate = false; // #15581
  49986. }
  49987. }
  49988. function refreshUniformsCommon( uniforms, material ) {
  49989. uniforms.opacity.value = material.opacity;
  49990. if ( material.color ) {
  49991. uniforms.diffuse.value.copy( material.color );
  49992. }
  49993. if ( material.emissive ) {
  49994. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  49995. }
  49996. if ( material.map ) {
  49997. uniforms.map.value = material.map;
  49998. refreshTransformUniform( material.map, uniforms.mapTransform );
  49999. }
  50000. if ( material.alphaMap ) {
  50001. uniforms.alphaMap.value = material.alphaMap;
  50002. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  50003. }
  50004. if ( material.bumpMap ) {
  50005. uniforms.bumpMap.value = material.bumpMap;
  50006. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  50007. uniforms.bumpScale.value = material.bumpScale;
  50008. if ( material.side === BackSide ) {
  50009. uniforms.bumpScale.value *= - 1;
  50010. }
  50011. }
  50012. if ( material.normalMap ) {
  50013. uniforms.normalMap.value = material.normalMap;
  50014. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  50015. uniforms.normalScale.value.copy( material.normalScale );
  50016. if ( material.side === BackSide ) {
  50017. uniforms.normalScale.value.negate();
  50018. }
  50019. }
  50020. if ( material.displacementMap ) {
  50021. uniforms.displacementMap.value = material.displacementMap;
  50022. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  50023. uniforms.displacementScale.value = material.displacementScale;
  50024. uniforms.displacementBias.value = material.displacementBias;
  50025. }
  50026. if ( material.emissiveMap ) {
  50027. uniforms.emissiveMap.value = material.emissiveMap;
  50028. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  50029. }
  50030. if ( material.specularMap ) {
  50031. uniforms.specularMap.value = material.specularMap;
  50032. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  50033. }
  50034. if ( material.alphaTest > 0 ) {
  50035. uniforms.alphaTest.value = material.alphaTest;
  50036. }
  50037. const materialProperties = properties.get( material );
  50038. const envMap = materialProperties.envMap;
  50039. const envMapRotation = materialProperties.envMapRotation;
  50040. if ( envMap ) {
  50041. uniforms.envMap.value = envMap;
  50042. _e1.copy( envMapRotation );
  50043. // accommodate left-handed frame
  50044. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  50045. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  50046. // environment maps which are not cube render targets or PMREMs follow a different convention
  50047. _e1.y *= - 1;
  50048. _e1.z *= - 1;
  50049. }
  50050. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  50051. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  50052. uniforms.reflectivity.value = material.reflectivity;
  50053. uniforms.ior.value = material.ior;
  50054. uniforms.refractionRatio.value = material.refractionRatio;
  50055. }
  50056. if ( material.lightMap ) {
  50057. uniforms.lightMap.value = material.lightMap;
  50058. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  50059. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  50060. }
  50061. if ( material.aoMap ) {
  50062. uniforms.aoMap.value = material.aoMap;
  50063. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  50064. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  50065. }
  50066. }
  50067. function refreshUniformsLine( uniforms, material ) {
  50068. uniforms.diffuse.value.copy( material.color );
  50069. uniforms.opacity.value = material.opacity;
  50070. if ( material.map ) {
  50071. uniforms.map.value = material.map;
  50072. refreshTransformUniform( material.map, uniforms.mapTransform );
  50073. }
  50074. }
  50075. function refreshUniformsDash( uniforms, material ) {
  50076. uniforms.dashSize.value = material.dashSize;
  50077. uniforms.totalSize.value = material.dashSize + material.gapSize;
  50078. uniforms.scale.value = material.scale;
  50079. }
  50080. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  50081. uniforms.diffuse.value.copy( material.color );
  50082. uniforms.opacity.value = material.opacity;
  50083. uniforms.size.value = material.size * pixelRatio;
  50084. uniforms.scale.value = height * 0.5;
  50085. if ( material.map ) {
  50086. uniforms.map.value = material.map;
  50087. refreshTransformUniform( material.map, uniforms.uvTransform );
  50088. }
  50089. if ( material.alphaMap ) {
  50090. uniforms.alphaMap.value = material.alphaMap;
  50091. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  50092. }
  50093. if ( material.alphaTest > 0 ) {
  50094. uniforms.alphaTest.value = material.alphaTest;
  50095. }
  50096. }
  50097. function refreshUniformsSprites( uniforms, material ) {
  50098. uniforms.diffuse.value.copy( material.color );
  50099. uniforms.opacity.value = material.opacity;
  50100. uniforms.rotation.value = material.rotation;
  50101. if ( material.map ) {
  50102. uniforms.map.value = material.map;
  50103. refreshTransformUniform( material.map, uniforms.mapTransform );
  50104. }
  50105. if ( material.alphaMap ) {
  50106. uniforms.alphaMap.value = material.alphaMap;
  50107. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  50108. }
  50109. if ( material.alphaTest > 0 ) {
  50110. uniforms.alphaTest.value = material.alphaTest;
  50111. }
  50112. }
  50113. function refreshUniformsPhong( uniforms, material ) {
  50114. uniforms.specular.value.copy( material.specular );
  50115. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  50116. }
  50117. function refreshUniformsToon( uniforms, material ) {
  50118. if ( material.gradientMap ) {
  50119. uniforms.gradientMap.value = material.gradientMap;
  50120. }
  50121. }
  50122. function refreshUniformsStandard( uniforms, material ) {
  50123. uniforms.metalness.value = material.metalness;
  50124. if ( material.metalnessMap ) {
  50125. uniforms.metalnessMap.value = material.metalnessMap;
  50126. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  50127. }
  50128. uniforms.roughness.value = material.roughness;
  50129. if ( material.roughnessMap ) {
  50130. uniforms.roughnessMap.value = material.roughnessMap;
  50131. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  50132. }
  50133. if ( material.envMap ) {
  50134. //uniforms.envMap.value = material.envMap; // part of uniforms common
  50135. uniforms.envMapIntensity.value = material.envMapIntensity;
  50136. }
  50137. }
  50138. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  50139. uniforms.ior.value = material.ior; // also part of uniforms common
  50140. if ( material.sheen > 0 ) {
  50141. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  50142. uniforms.sheenRoughness.value = material.sheenRoughness;
  50143. if ( material.sheenColorMap ) {
  50144. uniforms.sheenColorMap.value = material.sheenColorMap;
  50145. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  50146. }
  50147. if ( material.sheenRoughnessMap ) {
  50148. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  50149. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  50150. }
  50151. }
  50152. if ( material.clearcoat > 0 ) {
  50153. uniforms.clearcoat.value = material.clearcoat;
  50154. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  50155. if ( material.clearcoatMap ) {
  50156. uniforms.clearcoatMap.value = material.clearcoatMap;
  50157. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  50158. }
  50159. if ( material.clearcoatRoughnessMap ) {
  50160. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  50161. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  50162. }
  50163. if ( material.clearcoatNormalMap ) {
  50164. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  50165. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  50166. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  50167. if ( material.side === BackSide ) {
  50168. uniforms.clearcoatNormalScale.value.negate();
  50169. }
  50170. }
  50171. }
  50172. if ( material.dispersion > 0 ) {
  50173. uniforms.dispersion.value = material.dispersion;
  50174. }
  50175. if ( material.iridescence > 0 ) {
  50176. uniforms.iridescence.value = material.iridescence;
  50177. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  50178. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  50179. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  50180. if ( material.iridescenceMap ) {
  50181. uniforms.iridescenceMap.value = material.iridescenceMap;
  50182. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  50183. }
  50184. if ( material.iridescenceThicknessMap ) {
  50185. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  50186. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  50187. }
  50188. }
  50189. if ( material.transmission > 0 ) {
  50190. uniforms.transmission.value = material.transmission;
  50191. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  50192. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  50193. if ( material.transmissionMap ) {
  50194. uniforms.transmissionMap.value = material.transmissionMap;
  50195. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  50196. }
  50197. uniforms.thickness.value = material.thickness;
  50198. if ( material.thicknessMap ) {
  50199. uniforms.thicknessMap.value = material.thicknessMap;
  50200. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  50201. }
  50202. uniforms.attenuationDistance.value = material.attenuationDistance;
  50203. uniforms.attenuationColor.value.copy( material.attenuationColor );
  50204. }
  50205. if ( material.anisotropy > 0 ) {
  50206. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  50207. if ( material.anisotropyMap ) {
  50208. uniforms.anisotropyMap.value = material.anisotropyMap;
  50209. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  50210. }
  50211. }
  50212. uniforms.specularIntensity.value = material.specularIntensity;
  50213. uniforms.specularColor.value.copy( material.specularColor );
  50214. if ( material.specularColorMap ) {
  50215. uniforms.specularColorMap.value = material.specularColorMap;
  50216. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  50217. }
  50218. if ( material.specularIntensityMap ) {
  50219. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  50220. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  50221. }
  50222. }
  50223. function refreshUniformsMatcap( uniforms, material ) {
  50224. if ( material.matcap ) {
  50225. uniforms.matcap.value = material.matcap;
  50226. }
  50227. }
  50228. function refreshUniformsDistance( uniforms, material ) {
  50229. const light = properties.get( material ).light;
  50230. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  50231. uniforms.nearDistance.value = light.shadow.camera.near;
  50232. uniforms.farDistance.value = light.shadow.camera.far;
  50233. }
  50234. return {
  50235. refreshFogUniforms: refreshFogUniforms,
  50236. refreshMaterialUniforms: refreshMaterialUniforms
  50237. };
  50238. }
  50239. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  50240. let buffers = {};
  50241. let updateList = {};
  50242. let allocatedBindingPoints = [];
  50243. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  50244. function bind( uniformsGroup, program ) {
  50245. const webglProgram = program.program;
  50246. state.uniformBlockBinding( uniformsGroup, webglProgram );
  50247. }
  50248. function update( uniformsGroup, program ) {
  50249. let buffer = buffers[ uniformsGroup.id ];
  50250. if ( buffer === undefined ) {
  50251. prepareUniformsGroup( uniformsGroup );
  50252. buffer = createBuffer( uniformsGroup );
  50253. buffers[ uniformsGroup.id ] = buffer;
  50254. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  50255. }
  50256. // ensure to update the binding points/block indices mapping for this program
  50257. const webglProgram = program.program;
  50258. state.updateUBOMapping( uniformsGroup, webglProgram );
  50259. // update UBO once per frame
  50260. const frame = info.render.frame;
  50261. if ( updateList[ uniformsGroup.id ] !== frame ) {
  50262. updateBufferData( uniformsGroup );
  50263. updateList[ uniformsGroup.id ] = frame;
  50264. }
  50265. }
  50266. function createBuffer( uniformsGroup ) {
  50267. // the setup of an UBO is independent of a particular shader program but global
  50268. const bindingPointIndex = allocateBindingPointIndex();
  50269. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  50270. const buffer = gl.createBuffer();
  50271. const size = uniformsGroup.__size;
  50272. const usage = uniformsGroup.usage;
  50273. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  50274. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  50275. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  50276. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  50277. return buffer;
  50278. }
  50279. function allocateBindingPointIndex() {
  50280. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  50281. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  50282. allocatedBindingPoints.push( i );
  50283. return i;
  50284. }
  50285. }
  50286. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  50287. return 0;
  50288. }
  50289. function updateBufferData( uniformsGroup ) {
  50290. const buffer = buffers[ uniformsGroup.id ];
  50291. const uniforms = uniformsGroup.uniforms;
  50292. const cache = uniformsGroup.__cache;
  50293. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  50294. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  50295. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  50296. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  50297. const uniform = uniformArray[ j ];
  50298. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  50299. const offset = uniform.__offset;
  50300. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  50301. let arrayOffset = 0;
  50302. for ( let k = 0; k < values.length; k ++ ) {
  50303. const value = values[ k ];
  50304. const info = getUniformSize( value );
  50305. // TODO add integer and struct support
  50306. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50307. uniform.__data[ 0 ] = value;
  50308. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  50309. } else if ( value.isMatrix3 ) {
  50310. // manually converting 3x3 to 3x4
  50311. uniform.__data[ 0 ] = value.elements[ 0 ];
  50312. uniform.__data[ 1 ] = value.elements[ 1 ];
  50313. uniform.__data[ 2 ] = value.elements[ 2 ];
  50314. uniform.__data[ 3 ] = 0;
  50315. uniform.__data[ 4 ] = value.elements[ 3 ];
  50316. uniform.__data[ 5 ] = value.elements[ 4 ];
  50317. uniform.__data[ 6 ] = value.elements[ 5 ];
  50318. uniform.__data[ 7 ] = 0;
  50319. uniform.__data[ 8 ] = value.elements[ 6 ];
  50320. uniform.__data[ 9 ] = value.elements[ 7 ];
  50321. uniform.__data[ 10 ] = value.elements[ 8 ];
  50322. uniform.__data[ 11 ] = 0;
  50323. } else {
  50324. value.toArray( uniform.__data, arrayOffset );
  50325. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  50326. }
  50327. }
  50328. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  50329. }
  50330. }
  50331. }
  50332. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  50333. }
  50334. function hasUniformChanged( uniform, index, indexArray, cache ) {
  50335. const value = uniform.value;
  50336. const indexString = index + '_' + indexArray;
  50337. if ( cache[ indexString ] === undefined ) {
  50338. // cache entry does not exist so far
  50339. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50340. cache[ indexString ] = value;
  50341. } else {
  50342. cache[ indexString ] = value.clone();
  50343. }
  50344. return true;
  50345. } else {
  50346. const cachedObject = cache[ indexString ];
  50347. // compare current value with cached entry
  50348. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50349. if ( cachedObject !== value ) {
  50350. cache[ indexString ] = value;
  50351. return true;
  50352. }
  50353. } else {
  50354. if ( cachedObject.equals( value ) === false ) {
  50355. cachedObject.copy( value );
  50356. return true;
  50357. }
  50358. }
  50359. }
  50360. return false;
  50361. }
  50362. function prepareUniformsGroup( uniformsGroup ) {
  50363. // determine total buffer size according to the STD140 layout
  50364. // Hint: STD140 is the only supported layout in WebGL 2
  50365. const uniforms = uniformsGroup.uniforms;
  50366. let offset = 0; // global buffer offset in bytes
  50367. const chunkSize = 16; // size of a chunk in bytes
  50368. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  50369. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  50370. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  50371. const uniform = uniformArray[ j ];
  50372. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  50373. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  50374. const value = values[ k ];
  50375. const info = getUniformSize( value );
  50376. const chunkOffset = offset % chunkSize; // offset in the current chunk
  50377. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  50378. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  50379. offset += chunkPadding;
  50380. // Check for chunk overflow
  50381. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  50382. // Add padding and adjust offset
  50383. offset += ( chunkSize - chunkStart );
  50384. }
  50385. // the following two properties will be used for partial buffer updates
  50386. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  50387. uniform.__offset = offset;
  50388. // Update the global offset
  50389. offset += info.storage;
  50390. }
  50391. }
  50392. }
  50393. // ensure correct final padding
  50394. const chunkOffset = offset % chunkSize;
  50395. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  50396. //
  50397. uniformsGroup.__size = offset;
  50398. uniformsGroup.__cache = {};
  50399. return this;
  50400. }
  50401. function getUniformSize( value ) {
  50402. const info = {
  50403. boundary: 0, // bytes
  50404. storage: 0 // bytes
  50405. };
  50406. // determine sizes according to STD140
  50407. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  50408. // float/int/bool
  50409. info.boundary = 4;
  50410. info.storage = 4;
  50411. } else if ( value.isVector2 ) {
  50412. // vec2
  50413. info.boundary = 8;
  50414. info.storage = 8;
  50415. } else if ( value.isVector3 || value.isColor ) {
  50416. // vec3
  50417. info.boundary = 16;
  50418. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  50419. } else if ( value.isVector4 ) {
  50420. // vec4
  50421. info.boundary = 16;
  50422. info.storage = 16;
  50423. } else if ( value.isMatrix3 ) {
  50424. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  50425. info.boundary = 48;
  50426. info.storage = 48;
  50427. } else if ( value.isMatrix4 ) {
  50428. // mat4
  50429. info.boundary = 64;
  50430. info.storage = 64;
  50431. } else if ( value.isTexture ) {
  50432. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  50433. } else {
  50434. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  50435. }
  50436. return info;
  50437. }
  50438. function onUniformsGroupsDispose( event ) {
  50439. const uniformsGroup = event.target;
  50440. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  50441. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  50442. allocatedBindingPoints.splice( index, 1 );
  50443. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  50444. delete buffers[ uniformsGroup.id ];
  50445. delete updateList[ uniformsGroup.id ];
  50446. }
  50447. function dispose() {
  50448. for ( const id in buffers ) {
  50449. gl.deleteBuffer( buffers[ id ] );
  50450. }
  50451. allocatedBindingPoints = [];
  50452. buffers = {};
  50453. updateList = {};
  50454. }
  50455. return {
  50456. bind: bind,
  50457. update: update,
  50458. dispose: dispose
  50459. };
  50460. }
  50461. /**
  50462. * This renderer uses WebGL 2 to display scenes.
  50463. *
  50464. * WebGL 1 is not supported since `r163`.
  50465. */
  50466. class WebGLRenderer {
  50467. /**
  50468. * Constructs a new WebGL renderer.
  50469. *
  50470. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  50471. */
  50472. constructor( parameters = {} ) {
  50473. const {
  50474. canvas = createCanvasElement(),
  50475. context = null,
  50476. depth = true,
  50477. stencil = false,
  50478. alpha = false,
  50479. antialias = false,
  50480. premultipliedAlpha = true,
  50481. preserveDrawingBuffer = false,
  50482. powerPreference = 'default',
  50483. failIfMajorPerformanceCaveat = false,
  50484. reverseDepthBuffer = false,
  50485. } = parameters;
  50486. /**
  50487. * This flag can be used for type testing.
  50488. *
  50489. * @type {boolean}
  50490. * @readonly
  50491. * @default true
  50492. */
  50493. this.isWebGLRenderer = true;
  50494. let _alpha;
  50495. if ( context !== null ) {
  50496. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  50497. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  50498. }
  50499. _alpha = context.getContextAttributes().alpha;
  50500. } else {
  50501. _alpha = alpha;
  50502. }
  50503. const uintClearColor = new Uint32Array( 4 );
  50504. const intClearColor = new Int32Array( 4 );
  50505. let currentRenderList = null;
  50506. let currentRenderState = null;
  50507. // render() can be called from within a callback triggered by another render.
  50508. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  50509. const renderListStack = [];
  50510. const renderStateStack = [];
  50511. // public properties
  50512. /**
  50513. * A canvas where the renderer draws its output.This is automatically created by the renderer
  50514. * in the constructor (if not provided already); you just need to add it to your page like so:
  50515. * ```js
  50516. * document.body.appendChild( renderer.domElement );
  50517. * ```
  50518. *
  50519. * @type {DOMElement}
  50520. */
  50521. this.domElement = canvas;
  50522. /**
  50523. * A object with debug configuration settings.
  50524. *
  50525. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  50526. * checked for errors during compilation and linkage process. It may be useful to disable
  50527. * this check in production for performance gain. It is strongly recommended to keep these
  50528. * checks enabled during development. If the shader does not compile and link - it will not
  50529. * work and associated material will not render.
  50530. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  50531. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  50532. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  50533. * Assigning a custom function disables the default error reporting.
  50534. *
  50535. * @type {Object}
  50536. */
  50537. this.debug = {
  50538. /**
  50539. * Enables error checking and reporting when shader programs are being compiled.
  50540. * @type {boolean}
  50541. */
  50542. checkShaderErrors: true,
  50543. /**
  50544. * Callback for custom error reporting.
  50545. * @type {?Function}
  50546. */
  50547. onShaderError: null
  50548. };
  50549. // clearing
  50550. /**
  50551. * Whether the renderer should automatically clear its output before rendering a frame or not.
  50552. *
  50553. * @type {boolean}
  50554. * @default true
  50555. */
  50556. this.autoClear = true;
  50557. /**
  50558. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  50559. * the color buffer or not.
  50560. *
  50561. * @type {boolean}
  50562. * @default true
  50563. */
  50564. this.autoClearColor = true;
  50565. /**
  50566. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  50567. * the depth buffer or not.
  50568. *
  50569. * @type {boolean}
  50570. * @default true
  50571. */
  50572. this.autoClearDepth = true;
  50573. /**
  50574. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  50575. * the stencil buffer or not.
  50576. *
  50577. * @type {boolean}
  50578. * @default true
  50579. */
  50580. this.autoClearStencil = true;
  50581. // scene graph
  50582. /**
  50583. * Whether the renderer should sort objects or not.
  50584. *
  50585. * Note: Sorting is used to attempt to properly render objects that have some
  50586. * degree of transparency. By definition, sorting objects may not work in all
  50587. * cases. Depending on the needs of application, it may be necessary to turn
  50588. * off sorting and use other methods to deal with transparency rendering e.g.
  50589. * manually determining each object's rendering order.
  50590. *
  50591. * @type {boolean}
  50592. * @default true
  50593. */
  50594. this.sortObjects = true;
  50595. // user-defined clipping
  50596. /**
  50597. * User-defined clipping planes specified in world space. These planes apply globally.
  50598. * Points in space whose dot product with the plane is negative are cut away.
  50599. *
  50600. * @type {Array<Plane>}
  50601. */
  50602. this.clippingPlanes = [];
  50603. /**
  50604. * Whether the renderer respects object-level clipping planes or not.
  50605. *
  50606. * @type {boolean}
  50607. * @default false
  50608. */
  50609. this.localClippingEnabled = false;
  50610. // tone mapping
  50611. /**
  50612. * The tone mapping technique of the renderer.
  50613. *
  50614. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  50615. * @default NoToneMapping
  50616. */
  50617. this.toneMapping = NoToneMapping;
  50618. /**
  50619. * Exposure level of tone mapping.
  50620. *
  50621. * @type {number}
  50622. * @default 1
  50623. */
  50624. this.toneMappingExposure = 1.0;
  50625. // transmission
  50626. /**
  50627. * The normalized resolution scale for the transmission render target, measured in percentage
  50628. * of viewport dimensions. Lowering this value can result in significant performance improvements
  50629. * when using {@link MeshPhysicalMaterial#transmission}.
  50630. *
  50631. * @type {number}
  50632. * @default 1
  50633. */
  50634. this.transmissionResolutionScale = 1.0;
  50635. // internal properties
  50636. const _this = this;
  50637. let _isContextLost = false;
  50638. // internal state cache
  50639. this._outputColorSpace = SRGBColorSpace;
  50640. let _currentActiveCubeFace = 0;
  50641. let _currentActiveMipmapLevel = 0;
  50642. let _currentRenderTarget = null;
  50643. let _currentMaterialId = - 1;
  50644. let _currentCamera = null;
  50645. const _currentViewport = new Vector4();
  50646. const _currentScissor = new Vector4();
  50647. let _currentScissorTest = null;
  50648. const _currentClearColor = new Color( 0x000000 );
  50649. let _currentClearAlpha = 0;
  50650. //
  50651. let _width = canvas.width;
  50652. let _height = canvas.height;
  50653. let _pixelRatio = 1;
  50654. let _opaqueSort = null;
  50655. let _transparentSort = null;
  50656. const _viewport = new Vector4( 0, 0, _width, _height );
  50657. const _scissor = new Vector4( 0, 0, _width, _height );
  50658. let _scissorTest = false;
  50659. // frustum
  50660. const _frustum = new Frustum();
  50661. // clipping
  50662. let _clippingEnabled = false;
  50663. let _localClippingEnabled = false;
  50664. // camera matrices cache
  50665. const _currentProjectionMatrix = new Matrix4();
  50666. const _projScreenMatrix = new Matrix4();
  50667. const _vector3 = new Vector3();
  50668. const _vector4 = new Vector4();
  50669. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  50670. let _renderBackground = false;
  50671. function getTargetPixelRatio() {
  50672. return _currentRenderTarget === null ? _pixelRatio : 1;
  50673. }
  50674. // initialize
  50675. let _gl = context;
  50676. function getContext( contextName, contextAttributes ) {
  50677. return canvas.getContext( contextName, contextAttributes );
  50678. }
  50679. try {
  50680. const contextAttributes = {
  50681. alpha: true,
  50682. depth,
  50683. stencil,
  50684. antialias,
  50685. premultipliedAlpha,
  50686. preserveDrawingBuffer,
  50687. powerPreference,
  50688. failIfMajorPerformanceCaveat,
  50689. };
  50690. // OffscreenCanvas does not have setAttribute, see #22811
  50691. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  50692. // event listeners must be registered before WebGL context is created, see #12753
  50693. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  50694. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  50695. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  50696. if ( _gl === null ) {
  50697. const contextName = 'webgl2';
  50698. _gl = getContext( contextName, contextAttributes );
  50699. if ( _gl === null ) {
  50700. if ( getContext( contextName ) ) {
  50701. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  50702. } else {
  50703. throw new Error( 'Error creating WebGL context.' );
  50704. }
  50705. }
  50706. }
  50707. } catch ( error ) {
  50708. console.error( 'THREE.WebGLRenderer: ' + error.message );
  50709. throw error;
  50710. }
  50711. let extensions, capabilities, state, info;
  50712. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  50713. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  50714. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  50715. let utils, bindingStates, uniformsGroups;
  50716. function initGLContext() {
  50717. extensions = new WebGLExtensions( _gl );
  50718. extensions.init();
  50719. utils = new WebGLUtils( _gl, extensions );
  50720. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  50721. state = new WebGLState( _gl, extensions );
  50722. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  50723. state.buffers.depth.setReversed( true );
  50724. }
  50725. info = new WebGLInfo( _gl );
  50726. properties = new WebGLProperties();
  50727. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  50728. cubemaps = new WebGLCubeMaps( _this );
  50729. cubeuvmaps = new WebGLCubeUVMaps( _this );
  50730. attributes = new WebGLAttributes( _gl );
  50731. bindingStates = new WebGLBindingStates( _gl, attributes );
  50732. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  50733. objects = new WebGLObjects( _gl, geometries, attributes, info );
  50734. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  50735. clipping = new WebGLClipping( properties );
  50736. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  50737. materials = new WebGLMaterials( _this, properties );
  50738. renderLists = new WebGLRenderLists();
  50739. renderStates = new WebGLRenderStates( extensions );
  50740. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  50741. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  50742. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  50743. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  50744. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  50745. info.programs = programCache.programs;
  50746. /**
  50747. * Holds details about the capabilities of the current rendering context.
  50748. *
  50749. * @name WebGLRenderer#capabilities
  50750. * @type {WebGLRenderer~Capabilities}
  50751. */
  50752. _this.capabilities = capabilities;
  50753. /**
  50754. * Provides methods for retrieving and testing WebGL extensions.
  50755. *
  50756. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  50757. * and return the extension object if available.
  50758. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  50759. *
  50760. * @name WebGLRenderer#extensions
  50761. * @type {Object}
  50762. */
  50763. _this.extensions = extensions;
  50764. /**
  50765. * Used to track properties of other objects like native WebGL objects.
  50766. *
  50767. * @name WebGLRenderer#properties
  50768. * @type {Object}
  50769. */
  50770. _this.properties = properties;
  50771. /**
  50772. * Manages the render lists of the renderer.
  50773. *
  50774. * @name WebGLRenderer#renderLists
  50775. * @type {Object}
  50776. */
  50777. _this.renderLists = renderLists;
  50778. /**
  50779. * Interface for managing shadows.
  50780. *
  50781. * @name WebGLRenderer#shadowMap
  50782. * @type {WebGLRenderer~ShadowMap}
  50783. */
  50784. _this.shadowMap = shadowMap;
  50785. /**
  50786. * Interface for managing the WebGL state.
  50787. *
  50788. * @name WebGLRenderer#state
  50789. * @type {Object}
  50790. */
  50791. _this.state = state;
  50792. /**
  50793. * Holds a series of statistical information about the GPU memory
  50794. * and the rendering process. Useful for debugging and monitoring.
  50795. *
  50796. * By default these data are reset at each render call but when having
  50797. * multiple render passes per frame (e.g. when using post processing) it can
  50798. * be preferred to reset with a custom pattern. First, set `autoReset` to
  50799. * `false`.
  50800. * ```js
  50801. * renderer.info.autoReset = false;
  50802. * ```
  50803. * Call `reset()` whenever you have finished to render a single frame.
  50804. * ```js
  50805. * renderer.info.reset();
  50806. * ```
  50807. *
  50808. * @name WebGLRenderer#info
  50809. * @type {WebGLRenderer~Info}
  50810. */
  50811. _this.info = info;
  50812. }
  50813. initGLContext();
  50814. // xr
  50815. const xr = new WebXRManager( _this, _gl );
  50816. /**
  50817. * A reference to the XR manager.
  50818. *
  50819. * @type {WebXRManager}
  50820. */
  50821. this.xr = xr;
  50822. /**
  50823. * Returns the rendering context.
  50824. *
  50825. * @return {WebGL2RenderingContext} The rendering context.
  50826. */
  50827. this.getContext = function () {
  50828. return _gl;
  50829. };
  50830. /**
  50831. * Returns the rendering context attributes.
  50832. *
  50833. * @return {WebGLContextAttributes} The rendering context attributes.
  50834. */
  50835. this.getContextAttributes = function () {
  50836. return _gl.getContextAttributes();
  50837. };
  50838. /**
  50839. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  50840. */
  50841. this.forceContextLoss = function () {
  50842. const extension = extensions.get( 'WEBGL_lose_context' );
  50843. if ( extension ) extension.loseContext();
  50844. };
  50845. /**
  50846. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  50847. */
  50848. this.forceContextRestore = function () {
  50849. const extension = extensions.get( 'WEBGL_lose_context' );
  50850. if ( extension ) extension.restoreContext();
  50851. };
  50852. /**
  50853. * Returns the pixel ratio.
  50854. *
  50855. * @return {number} The pixel ratio.
  50856. */
  50857. this.getPixelRatio = function () {
  50858. return _pixelRatio;
  50859. };
  50860. /**
  50861. * Sets the given pixel ratio and resizes the canvas if necessary.
  50862. *
  50863. * @param {number} value - The pixel ratio.
  50864. */
  50865. this.setPixelRatio = function ( value ) {
  50866. if ( value === undefined ) return;
  50867. _pixelRatio = value;
  50868. this.setSize( _width, _height, false );
  50869. };
  50870. /**
  50871. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  50872. *
  50873. * @param {Vector2} target - The method writes the result in this target object.
  50874. * @return {Vector2} The renderer's size in logical pixels.
  50875. */
  50876. this.getSize = function ( target ) {
  50877. return target.set( _width, _height );
  50878. };
  50879. /**
  50880. * Resizes the output canvas to (width, height) with device pixel ratio taken
  50881. * into account, and also sets the viewport to fit that size, starting in (0,
  50882. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  50883. *
  50884. * @param {number} width - The width in logical pixels.
  50885. * @param {number} height - The height in logical pixels.
  50886. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  50887. */
  50888. this.setSize = function ( width, height, updateStyle = true ) {
  50889. if ( xr.isPresenting ) {
  50890. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  50891. return;
  50892. }
  50893. _width = width;
  50894. _height = height;
  50895. canvas.width = Math.floor( width * _pixelRatio );
  50896. canvas.height = Math.floor( height * _pixelRatio );
  50897. if ( updateStyle === true ) {
  50898. canvas.style.width = width + 'px';
  50899. canvas.style.height = height + 'px';
  50900. }
  50901. this.setViewport( 0, 0, width, height );
  50902. };
  50903. /**
  50904. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  50905. *
  50906. * @param {Vector2} target - The method writes the result in this target object.
  50907. * @return {Vector2} The drawing buffer size.
  50908. */
  50909. this.getDrawingBufferSize = function ( target ) {
  50910. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  50911. };
  50912. /**
  50913. * This method allows to define the drawing buffer size by specifying
  50914. * width, height and pixel ratio all at once. The size of the drawing
  50915. * buffer is computed with this formula:
  50916. * ```js
  50917. * size.x = width * pixelRatio;
  50918. * size.y = height * pixelRatio;
  50919. * ```
  50920. *
  50921. * @param {number} width - The width in logical pixels.
  50922. * @param {number} height - The height in logical pixels.
  50923. * @param {number} pixelRatio - The pixel ratio.
  50924. */
  50925. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  50926. _width = width;
  50927. _height = height;
  50928. _pixelRatio = pixelRatio;
  50929. canvas.width = Math.floor( width * pixelRatio );
  50930. canvas.height = Math.floor( height * pixelRatio );
  50931. this.setViewport( 0, 0, width, height );
  50932. };
  50933. /**
  50934. * Returns the current viewport definition.
  50935. *
  50936. * @param {Vector2} target - The method writes the result in this target object.
  50937. * @return {Vector2} The current viewport definition.
  50938. */
  50939. this.getCurrentViewport = function ( target ) {
  50940. return target.copy( _currentViewport );
  50941. };
  50942. /**
  50943. * Returns the viewport definition.
  50944. *
  50945. * @param {Vector4} target - The method writes the result in this target object.
  50946. * @return {Vector4} The viewport definition.
  50947. */
  50948. this.getViewport = function ( target ) {
  50949. return target.copy( _viewport );
  50950. };
  50951. /**
  50952. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  50953. *
  50954. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  50955. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  50956. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  50957. * @param {number} width - The width of the viewport in logical pixel unit.
  50958. * @param {number} height - The height of the viewport in logical pixel unit.
  50959. */
  50960. this.setViewport = function ( x, y, width, height ) {
  50961. if ( x.isVector4 ) {
  50962. _viewport.set( x.x, x.y, x.z, x.w );
  50963. } else {
  50964. _viewport.set( x, y, width, height );
  50965. }
  50966. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  50967. };
  50968. /**
  50969. * Returns the scissor region.
  50970. *
  50971. * @param {Vector4} target - The method writes the result in this target object.
  50972. * @return {Vector4} The scissor region.
  50973. */
  50974. this.getScissor = function ( target ) {
  50975. return target.copy( _scissor );
  50976. };
  50977. /**
  50978. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  50979. *
  50980. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  50981. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  50982. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  50983. * @param {number} width - The width of the scissor region in logical pixel unit.
  50984. * @param {number} height - The height of the scissor region in logical pixel unit.
  50985. */
  50986. this.setScissor = function ( x, y, width, height ) {
  50987. if ( x.isVector4 ) {
  50988. _scissor.set( x.x, x.y, x.z, x.w );
  50989. } else {
  50990. _scissor.set( x, y, width, height );
  50991. }
  50992. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  50993. };
  50994. /**
  50995. * Returns `true` if the scissor test is enabled.
  50996. *
  50997. * @return {boolean} Whether the scissor test is enabled or not.
  50998. */
  50999. this.getScissorTest = function () {
  51000. return _scissorTest;
  51001. };
  51002. /**
  51003. * Enable or disable the scissor test. When this is enabled, only the pixels
  51004. * within the defined scissor area will be affected by further renderer
  51005. * actions.
  51006. *
  51007. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  51008. */
  51009. this.setScissorTest = function ( boolean ) {
  51010. state.setScissorTest( _scissorTest = boolean );
  51011. };
  51012. /**
  51013. * Sets a custom opaque sort function for the render lists. Pass `null`
  51014. * to use the default `painterSortStable` function.
  51015. *
  51016. * @param {?Function} method - The opaque sort function.
  51017. */
  51018. this.setOpaqueSort = function ( method ) {
  51019. _opaqueSort = method;
  51020. };
  51021. /**
  51022. * Sets a custom transparent sort function for the render lists. Pass `null`
  51023. * to use the default `reversePainterSortStable` function.
  51024. *
  51025. * @param {?Function} method - The opaque sort function.
  51026. */
  51027. this.setTransparentSort = function ( method ) {
  51028. _transparentSort = method;
  51029. };
  51030. // Clearing
  51031. /**
  51032. * Returns the clear color.
  51033. *
  51034. * @param {Color} target - The method writes the result in this target object.
  51035. * @return {Color} The clear color.
  51036. */
  51037. this.getClearColor = function ( target ) {
  51038. return target.copy( background.getClearColor() );
  51039. };
  51040. /**
  51041. * Sets the clear color and alpha.
  51042. *
  51043. * @param {Color} color - The clear color.
  51044. * @param {number} [alpha=1] - The clear alpha.
  51045. */
  51046. this.setClearColor = function () {
  51047. background.setClearColor( ...arguments );
  51048. };
  51049. /**
  51050. * Returns the clear alpha. Ranges within `[0,1]`.
  51051. *
  51052. * @return {number} The clear alpha.
  51053. */
  51054. this.getClearAlpha = function () {
  51055. return background.getClearAlpha();
  51056. };
  51057. /**
  51058. * Sets the clear alpha.
  51059. *
  51060. * @param {number} alpha - The clear alpha.
  51061. */
  51062. this.setClearAlpha = function () {
  51063. background.setClearAlpha( ...arguments );
  51064. };
  51065. /**
  51066. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  51067. * This method initializes the buffers to the current clear color values.
  51068. *
  51069. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  51070. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  51071. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  51072. */
  51073. this.clear = function ( color = true, depth = true, stencil = true ) {
  51074. let bits = 0;
  51075. if ( color ) {
  51076. // check if we're trying to clear an integer target
  51077. let isIntegerFormat = false;
  51078. if ( _currentRenderTarget !== null ) {
  51079. const targetFormat = _currentRenderTarget.texture.format;
  51080. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  51081. targetFormat === RGIntegerFormat ||
  51082. targetFormat === RedIntegerFormat;
  51083. }
  51084. // use the appropriate clear functions to clear the target if it's a signed
  51085. // or unsigned integer target
  51086. if ( isIntegerFormat ) {
  51087. const targetType = _currentRenderTarget.texture.type;
  51088. const isUnsignedType = targetType === UnsignedByteType ||
  51089. targetType === UnsignedIntType ||
  51090. targetType === UnsignedShortType ||
  51091. targetType === UnsignedInt248Type ||
  51092. targetType === UnsignedShort4444Type ||
  51093. targetType === UnsignedShort5551Type;
  51094. const clearColor = background.getClearColor();
  51095. const a = background.getClearAlpha();
  51096. const r = clearColor.r;
  51097. const g = clearColor.g;
  51098. const b = clearColor.b;
  51099. if ( isUnsignedType ) {
  51100. uintClearColor[ 0 ] = r;
  51101. uintClearColor[ 1 ] = g;
  51102. uintClearColor[ 2 ] = b;
  51103. uintClearColor[ 3 ] = a;
  51104. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  51105. } else {
  51106. intClearColor[ 0 ] = r;
  51107. intClearColor[ 1 ] = g;
  51108. intClearColor[ 2 ] = b;
  51109. intClearColor[ 3 ] = a;
  51110. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  51111. }
  51112. } else {
  51113. bits |= _gl.COLOR_BUFFER_BIT;
  51114. }
  51115. }
  51116. if ( depth ) {
  51117. bits |= _gl.DEPTH_BUFFER_BIT;
  51118. }
  51119. if ( stencil ) {
  51120. bits |= _gl.STENCIL_BUFFER_BIT;
  51121. this.state.buffers.stencil.setMask( 0xffffffff );
  51122. }
  51123. _gl.clear( bits );
  51124. };
  51125. /**
  51126. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  51127. */
  51128. this.clearColor = function () {
  51129. this.clear( true, false, false );
  51130. };
  51131. /**
  51132. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  51133. */
  51134. this.clearDepth = function () {
  51135. this.clear( false, true, false );
  51136. };
  51137. /**
  51138. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  51139. */
  51140. this.clearStencil = function () {
  51141. this.clear( false, false, true );
  51142. };
  51143. /**
  51144. * Frees the GPU-related resources allocated by this instance. Call this
  51145. * method whenever this instance is no longer used in your app.
  51146. */
  51147. this.dispose = function () {
  51148. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  51149. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  51150. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51151. background.dispose();
  51152. renderLists.dispose();
  51153. renderStates.dispose();
  51154. properties.dispose();
  51155. cubemaps.dispose();
  51156. cubeuvmaps.dispose();
  51157. objects.dispose();
  51158. bindingStates.dispose();
  51159. uniformsGroups.dispose();
  51160. programCache.dispose();
  51161. xr.dispose();
  51162. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  51163. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  51164. animation.stop();
  51165. };
  51166. // Events
  51167. function onContextLost( event ) {
  51168. event.preventDefault();
  51169. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  51170. _isContextLost = true;
  51171. }
  51172. function onContextRestore( /* event */ ) {
  51173. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  51174. _isContextLost = false;
  51175. const infoAutoReset = info.autoReset;
  51176. const shadowMapEnabled = shadowMap.enabled;
  51177. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  51178. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  51179. const shadowMapType = shadowMap.type;
  51180. initGLContext();
  51181. info.autoReset = infoAutoReset;
  51182. shadowMap.enabled = shadowMapEnabled;
  51183. shadowMap.autoUpdate = shadowMapAutoUpdate;
  51184. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  51185. shadowMap.type = shadowMapType;
  51186. }
  51187. function onContextCreationError( event ) {
  51188. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  51189. }
  51190. function onMaterialDispose( event ) {
  51191. const material = event.target;
  51192. material.removeEventListener( 'dispose', onMaterialDispose );
  51193. deallocateMaterial( material );
  51194. }
  51195. // Buffer deallocation
  51196. function deallocateMaterial( material ) {
  51197. releaseMaterialProgramReferences( material );
  51198. properties.remove( material );
  51199. }
  51200. function releaseMaterialProgramReferences( material ) {
  51201. const programs = properties.get( material ).programs;
  51202. if ( programs !== undefined ) {
  51203. programs.forEach( function ( program ) {
  51204. programCache.releaseProgram( program );
  51205. } );
  51206. if ( material.isShaderMaterial ) {
  51207. programCache.releaseShaderCache( material );
  51208. }
  51209. }
  51210. }
  51211. // Buffer rendering
  51212. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  51213. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  51214. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  51215. const program = setProgram( camera, scene, geometry, material, object );
  51216. state.setMaterial( material, frontFaceCW );
  51217. //
  51218. let index = geometry.index;
  51219. let rangeFactor = 1;
  51220. if ( material.wireframe === true ) {
  51221. index = geometries.getWireframeAttribute( geometry );
  51222. if ( index === undefined ) return;
  51223. rangeFactor = 2;
  51224. }
  51225. //
  51226. const drawRange = geometry.drawRange;
  51227. const position = geometry.attributes.position;
  51228. let drawStart = drawRange.start * rangeFactor;
  51229. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  51230. if ( group !== null ) {
  51231. drawStart = Math.max( drawStart, group.start * rangeFactor );
  51232. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  51233. }
  51234. if ( index !== null ) {
  51235. drawStart = Math.max( drawStart, 0 );
  51236. drawEnd = Math.min( drawEnd, index.count );
  51237. } else if ( position !== undefined && position !== null ) {
  51238. drawStart = Math.max( drawStart, 0 );
  51239. drawEnd = Math.min( drawEnd, position.count );
  51240. }
  51241. const drawCount = drawEnd - drawStart;
  51242. if ( drawCount < 0 || drawCount === Infinity ) return;
  51243. //
  51244. bindingStates.setup( object, material, program, geometry, index );
  51245. let attribute;
  51246. let renderer = bufferRenderer;
  51247. if ( index !== null ) {
  51248. attribute = attributes.get( index );
  51249. renderer = indexedBufferRenderer;
  51250. renderer.setIndex( attribute );
  51251. }
  51252. //
  51253. if ( object.isMesh ) {
  51254. if ( material.wireframe === true ) {
  51255. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  51256. renderer.setMode( _gl.LINES );
  51257. } else {
  51258. renderer.setMode( _gl.TRIANGLES );
  51259. }
  51260. } else if ( object.isLine ) {
  51261. let lineWidth = material.linewidth;
  51262. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  51263. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  51264. if ( object.isLineSegments ) {
  51265. renderer.setMode( _gl.LINES );
  51266. } else if ( object.isLineLoop ) {
  51267. renderer.setMode( _gl.LINE_LOOP );
  51268. } else {
  51269. renderer.setMode( _gl.LINE_STRIP );
  51270. }
  51271. } else if ( object.isPoints ) {
  51272. renderer.setMode( _gl.POINTS );
  51273. } else if ( object.isSprite ) {
  51274. renderer.setMode( _gl.TRIANGLES );
  51275. }
  51276. if ( object.isBatchedMesh ) {
  51277. if ( object._multiDrawInstances !== null ) {
  51278. // @deprecated, r174
  51279. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  51280. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  51281. } else {
  51282. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  51283. const starts = object._multiDrawStarts;
  51284. const counts = object._multiDrawCounts;
  51285. const drawCount = object._multiDrawCount;
  51286. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  51287. const uniforms = properties.get( material ).currentProgram.getUniforms();
  51288. for ( let i = 0; i < drawCount; i ++ ) {
  51289. uniforms.setValue( _gl, '_gl_DrawID', i );
  51290. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  51291. }
  51292. } else {
  51293. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  51294. }
  51295. }
  51296. } else if ( object.isInstancedMesh ) {
  51297. renderer.renderInstances( drawStart, drawCount, object.count );
  51298. } else if ( geometry.isInstancedBufferGeometry ) {
  51299. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  51300. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  51301. renderer.renderInstances( drawStart, drawCount, instanceCount );
  51302. } else {
  51303. renderer.render( drawStart, drawCount );
  51304. }
  51305. };
  51306. // Compile
  51307. function prepareMaterial( material, scene, object ) {
  51308. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  51309. material.side = BackSide;
  51310. material.needsUpdate = true;
  51311. getProgram( material, scene, object );
  51312. material.side = FrontSide;
  51313. material.needsUpdate = true;
  51314. getProgram( material, scene, object );
  51315. material.side = DoubleSide;
  51316. } else {
  51317. getProgram( material, scene, object );
  51318. }
  51319. }
  51320. /**
  51321. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  51322. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  51323. * optional parameter for applying the target scene.
  51324. *
  51325. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  51326. *
  51327. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  51328. * @param {Camera} camera - The camera.
  51329. * @param {?Scene} [targetScene=null] - The target scene.
  51330. * @return {?Set} The precompiled materials.
  51331. */
  51332. this.compile = function ( scene, camera, targetScene = null ) {
  51333. if ( targetScene === null ) targetScene = scene;
  51334. currentRenderState = renderStates.get( targetScene );
  51335. currentRenderState.init( camera );
  51336. renderStateStack.push( currentRenderState );
  51337. // gather lights from both the target scene and the new object that will be added to the scene.
  51338. targetScene.traverseVisible( function ( object ) {
  51339. if ( object.isLight && object.layers.test( camera.layers ) ) {
  51340. currentRenderState.pushLight( object );
  51341. if ( object.castShadow ) {
  51342. currentRenderState.pushShadow( object );
  51343. }
  51344. }
  51345. } );
  51346. if ( scene !== targetScene ) {
  51347. scene.traverseVisible( function ( object ) {
  51348. if ( object.isLight && object.layers.test( camera.layers ) ) {
  51349. currentRenderState.pushLight( object );
  51350. if ( object.castShadow ) {
  51351. currentRenderState.pushShadow( object );
  51352. }
  51353. }
  51354. } );
  51355. }
  51356. currentRenderState.setupLights();
  51357. // Only initialize materials in the new scene, not the targetScene.
  51358. const materials = new Set();
  51359. scene.traverse( function ( object ) {
  51360. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  51361. return;
  51362. }
  51363. const material = object.material;
  51364. if ( material ) {
  51365. if ( Array.isArray( material ) ) {
  51366. for ( let i = 0; i < material.length; i ++ ) {
  51367. const material2 = material[ i ];
  51368. prepareMaterial( material2, targetScene, object );
  51369. materials.add( material2 );
  51370. }
  51371. } else {
  51372. prepareMaterial( material, targetScene, object );
  51373. materials.add( material );
  51374. }
  51375. }
  51376. } );
  51377. currentRenderState = renderStateStack.pop();
  51378. return materials;
  51379. };
  51380. // compileAsync
  51381. /**
  51382. * Asynchronous version of {@link WebGLRenderer#compile}.
  51383. *
  51384. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  51385. * it is recommended to use this version of `compile()` whenever possible.
  51386. *
  51387. * @async
  51388. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  51389. * @param {Camera} camera - The camera.
  51390. * @param {?Scene} [targetScene=null] - The target scene.
  51391. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  51392. */
  51393. this.compileAsync = function ( scene, camera, targetScene = null ) {
  51394. const materials = this.compile( scene, camera, targetScene );
  51395. // Wait for all the materials in the new object to indicate that they're
  51396. // ready to be used before resolving the promise.
  51397. return new Promise( ( resolve ) => {
  51398. function checkMaterialsReady() {
  51399. materials.forEach( function ( material ) {
  51400. const materialProperties = properties.get( material );
  51401. const program = materialProperties.currentProgram;
  51402. if ( program.isReady() ) {
  51403. // remove any programs that report they're ready to use from the list
  51404. materials.delete( material );
  51405. }
  51406. } );
  51407. // once the list of compiling materials is empty, call the callback
  51408. if ( materials.size === 0 ) {
  51409. resolve( scene );
  51410. return;
  51411. }
  51412. // if some materials are still not ready, wait a bit and check again
  51413. setTimeout( checkMaterialsReady, 10 );
  51414. }
  51415. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  51416. // If we can check the compilation status of the materials without
  51417. // blocking then do so right away.
  51418. checkMaterialsReady();
  51419. } else {
  51420. // Otherwise start by waiting a bit to give the materials we just
  51421. // initialized a chance to finish.
  51422. setTimeout( checkMaterialsReady, 10 );
  51423. }
  51424. } );
  51425. };
  51426. // Animation Loop
  51427. let onAnimationFrameCallback = null;
  51428. function onAnimationFrame( time ) {
  51429. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  51430. }
  51431. function onXRSessionStart() {
  51432. animation.stop();
  51433. }
  51434. function onXRSessionEnd() {
  51435. animation.start();
  51436. }
  51437. const animation = new WebGLAnimation();
  51438. animation.setAnimationLoop( onAnimationFrame );
  51439. if ( typeof self !== 'undefined' ) animation.setContext( self );
  51440. this.setAnimationLoop = function ( callback ) {
  51441. onAnimationFrameCallback = callback;
  51442. xr.setAnimationLoop( callback );
  51443. ( callback === null ) ? animation.stop() : animation.start();
  51444. };
  51445. xr.addEventListener( 'sessionstart', onXRSessionStart );
  51446. xr.addEventListener( 'sessionend', onXRSessionEnd );
  51447. // Rendering
  51448. /**
  51449. * Renders the given scene (or other type of 3D object) using the given camera.
  51450. *
  51451. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  51452. * or to the canvas as usual.
  51453. *
  51454. * By default render buffers are cleared before rendering but you can prevent
  51455. * this by setting the property `autoClear` to `false`. If you want to prevent
  51456. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  51457. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  51458. *
  51459. * @param {Object3D} scene - The scene to render.
  51460. * @param {Camera} camera - The camera.
  51461. */
  51462. this.render = function ( scene, camera ) {
  51463. if ( camera !== undefined && camera.isCamera !== true ) {
  51464. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  51465. return;
  51466. }
  51467. if ( _isContextLost === true ) return;
  51468. // update scene graph
  51469. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  51470. // update camera matrices and frustum
  51471. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  51472. if ( xr.enabled === true && xr.isPresenting === true ) {
  51473. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  51474. camera = xr.getCamera(); // use XR camera for rendering
  51475. }
  51476. //
  51477. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  51478. currentRenderState = renderStates.get( scene, renderStateStack.length );
  51479. currentRenderState.init( camera );
  51480. renderStateStack.push( currentRenderState );
  51481. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  51482. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  51483. _localClippingEnabled = this.localClippingEnabled;
  51484. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  51485. currentRenderList = renderLists.get( scene, renderListStack.length );
  51486. currentRenderList.init();
  51487. renderListStack.push( currentRenderList );
  51488. if ( xr.enabled === true && xr.isPresenting === true ) {
  51489. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  51490. if ( depthSensingMesh !== null ) {
  51491. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  51492. }
  51493. }
  51494. projectObject( scene, camera, 0, _this.sortObjects );
  51495. currentRenderList.finish();
  51496. if ( _this.sortObjects === true ) {
  51497. currentRenderList.sort( _opaqueSort, _transparentSort );
  51498. }
  51499. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  51500. if ( _renderBackground ) {
  51501. background.addToRenderList( currentRenderList, scene );
  51502. }
  51503. //
  51504. this.info.render.frame ++;
  51505. if ( _clippingEnabled === true ) clipping.beginShadows();
  51506. const shadowsArray = currentRenderState.state.shadowsArray;
  51507. shadowMap.render( shadowsArray, scene, camera );
  51508. if ( _clippingEnabled === true ) clipping.endShadows();
  51509. //
  51510. if ( this.info.autoReset === true ) this.info.reset();
  51511. // render scene
  51512. const opaqueObjects = currentRenderList.opaque;
  51513. const transmissiveObjects = currentRenderList.transmissive;
  51514. currentRenderState.setupLights();
  51515. if ( camera.isArrayCamera ) {
  51516. const cameras = camera.cameras;
  51517. if ( transmissiveObjects.length > 0 ) {
  51518. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  51519. const camera2 = cameras[ i ];
  51520. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  51521. }
  51522. }
  51523. if ( _renderBackground ) background.render( scene );
  51524. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  51525. const camera2 = cameras[ i ];
  51526. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  51527. }
  51528. } else {
  51529. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  51530. if ( _renderBackground ) background.render( scene );
  51531. renderScene( currentRenderList, scene, camera );
  51532. }
  51533. //
  51534. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  51535. // resolve multisample renderbuffers to a single-sample texture if necessary
  51536. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  51537. // Generate mipmap if we're using any kind of mipmap filtering
  51538. textures.updateRenderTargetMipmap( _currentRenderTarget );
  51539. }
  51540. //
  51541. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  51542. // _gl.finish();
  51543. bindingStates.resetDefaultState();
  51544. _currentMaterialId = - 1;
  51545. _currentCamera = null;
  51546. renderStateStack.pop();
  51547. if ( renderStateStack.length > 0 ) {
  51548. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  51549. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  51550. } else {
  51551. currentRenderState = null;
  51552. }
  51553. renderListStack.pop();
  51554. if ( renderListStack.length > 0 ) {
  51555. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  51556. } else {
  51557. currentRenderList = null;
  51558. }
  51559. };
  51560. function projectObject( object, camera, groupOrder, sortObjects ) {
  51561. if ( object.visible === false ) return;
  51562. const visible = object.layers.test( camera.layers );
  51563. if ( visible ) {
  51564. if ( object.isGroup ) {
  51565. groupOrder = object.renderOrder;
  51566. } else if ( object.isLOD ) {
  51567. if ( object.autoUpdate === true ) object.update( camera );
  51568. } else if ( object.isLight ) {
  51569. currentRenderState.pushLight( object );
  51570. if ( object.castShadow ) {
  51571. currentRenderState.pushShadow( object );
  51572. }
  51573. } else if ( object.isSprite ) {
  51574. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  51575. if ( sortObjects ) {
  51576. _vector4.setFromMatrixPosition( object.matrixWorld )
  51577. .applyMatrix4( _projScreenMatrix );
  51578. }
  51579. const geometry = objects.update( object );
  51580. const material = object.material;
  51581. if ( material.visible ) {
  51582. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  51583. }
  51584. }
  51585. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  51586. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  51587. const geometry = objects.update( object );
  51588. const material = object.material;
  51589. if ( sortObjects ) {
  51590. if ( object.boundingSphere !== undefined ) {
  51591. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  51592. _vector4.copy( object.boundingSphere.center );
  51593. } else {
  51594. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  51595. _vector4.copy( geometry.boundingSphere.center );
  51596. }
  51597. _vector4
  51598. .applyMatrix4( object.matrixWorld )
  51599. .applyMatrix4( _projScreenMatrix );
  51600. }
  51601. if ( Array.isArray( material ) ) {
  51602. const groups = geometry.groups;
  51603. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  51604. const group = groups[ i ];
  51605. const groupMaterial = material[ group.materialIndex ];
  51606. if ( groupMaterial && groupMaterial.visible ) {
  51607. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  51608. }
  51609. }
  51610. } else if ( material.visible ) {
  51611. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  51612. }
  51613. }
  51614. }
  51615. }
  51616. const children = object.children;
  51617. for ( let i = 0, l = children.length; i < l; i ++ ) {
  51618. projectObject( children[ i ], camera, groupOrder, sortObjects );
  51619. }
  51620. }
  51621. function renderScene( currentRenderList, scene, camera, viewport ) {
  51622. const opaqueObjects = currentRenderList.opaque;
  51623. const transmissiveObjects = currentRenderList.transmissive;
  51624. const transparentObjects = currentRenderList.transparent;
  51625. currentRenderState.setupLightsView( camera );
  51626. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  51627. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  51628. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  51629. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  51630. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  51631. // Ensure depth buffer writing is enabled so it can be cleared on next render
  51632. state.buffers.depth.setTest( true );
  51633. state.buffers.depth.setMask( true );
  51634. state.buffers.color.setMask( true );
  51635. state.setPolygonOffset( false );
  51636. }
  51637. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  51638. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  51639. if ( overrideMaterial !== null ) {
  51640. return;
  51641. }
  51642. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  51643. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  51644. generateMipmaps: true,
  51645. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  51646. minFilter: LinearMipmapLinearFilter,
  51647. samples: 4,
  51648. stencilBuffer: stencil,
  51649. resolveDepthBuffer: false,
  51650. resolveStencilBuffer: false,
  51651. colorSpace: ColorManagement.workingColorSpace,
  51652. } );
  51653. // debug
  51654. /*
  51655. const geometry = new PlaneGeometry();
  51656. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  51657. const mesh = new Mesh( geometry, material );
  51658. scene.add( mesh );
  51659. */
  51660. }
  51661. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  51662. const activeViewport = camera.viewport || _currentViewport;
  51663. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  51664. //
  51665. const currentRenderTarget = _this.getRenderTarget();
  51666. _this.setRenderTarget( transmissionRenderTarget );
  51667. _this.getClearColor( _currentClearColor );
  51668. _currentClearAlpha = _this.getClearAlpha();
  51669. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  51670. _this.clear();
  51671. if ( _renderBackground ) background.render( scene );
  51672. // Turn off the features which can affect the frag color for opaque objects pass.
  51673. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  51674. const currentToneMapping = _this.toneMapping;
  51675. _this.toneMapping = NoToneMapping;
  51676. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  51677. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  51678. const currentCameraViewport = camera.viewport;
  51679. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  51680. currentRenderState.setupLightsView( camera );
  51681. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  51682. renderObjects( opaqueObjects, scene, camera );
  51683. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  51684. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  51685. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  51686. let renderTargetNeedsUpdate = false;
  51687. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  51688. const renderItem = transmissiveObjects[ i ];
  51689. const object = renderItem.object;
  51690. const geometry = renderItem.geometry;
  51691. const material = renderItem.material;
  51692. const group = renderItem.group;
  51693. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  51694. const currentSide = material.side;
  51695. material.side = BackSide;
  51696. material.needsUpdate = true;
  51697. renderObject( object, scene, camera, geometry, material, group );
  51698. material.side = currentSide;
  51699. material.needsUpdate = true;
  51700. renderTargetNeedsUpdate = true;
  51701. }
  51702. }
  51703. if ( renderTargetNeedsUpdate === true ) {
  51704. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  51705. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  51706. }
  51707. }
  51708. _this.setRenderTarget( currentRenderTarget );
  51709. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  51710. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  51711. _this.toneMapping = currentToneMapping;
  51712. }
  51713. function renderObjects( renderList, scene, camera ) {
  51714. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  51715. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  51716. const renderItem = renderList[ i ];
  51717. const object = renderItem.object;
  51718. const geometry = renderItem.geometry;
  51719. const group = renderItem.group;
  51720. let material = renderItem.material;
  51721. if ( material.allowOverride === true && overrideMaterial !== null ) {
  51722. material = overrideMaterial;
  51723. }
  51724. if ( object.layers.test( camera.layers ) ) {
  51725. renderObject( object, scene, camera, geometry, material, group );
  51726. }
  51727. }
  51728. }
  51729. function renderObject( object, scene, camera, geometry, material, group ) {
  51730. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  51731. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  51732. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  51733. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  51734. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  51735. material.side = BackSide;
  51736. material.needsUpdate = true;
  51737. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  51738. material.side = FrontSide;
  51739. material.needsUpdate = true;
  51740. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  51741. material.side = DoubleSide;
  51742. } else {
  51743. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  51744. }
  51745. object.onAfterRender( _this, scene, camera, geometry, material, group );
  51746. }
  51747. function getProgram( material, scene, object ) {
  51748. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  51749. const materialProperties = properties.get( material );
  51750. const lights = currentRenderState.state.lights;
  51751. const shadowsArray = currentRenderState.state.shadowsArray;
  51752. const lightsStateVersion = lights.state.version;
  51753. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  51754. const programCacheKey = programCache.getProgramCacheKey( parameters );
  51755. let programs = materialProperties.programs;
  51756. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  51757. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  51758. materialProperties.fog = scene.fog;
  51759. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  51760. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  51761. if ( programs === undefined ) {
  51762. // new material
  51763. material.addEventListener( 'dispose', onMaterialDispose );
  51764. programs = new Map();
  51765. materialProperties.programs = programs;
  51766. }
  51767. let program = programs.get( programCacheKey );
  51768. if ( program !== undefined ) {
  51769. // early out if program and light state is identical
  51770. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  51771. updateCommonMaterialProperties( material, parameters );
  51772. return program;
  51773. }
  51774. } else {
  51775. parameters.uniforms = programCache.getUniforms( material );
  51776. material.onBeforeCompile( parameters, _this );
  51777. program = programCache.acquireProgram( parameters, programCacheKey );
  51778. programs.set( programCacheKey, program );
  51779. materialProperties.uniforms = parameters.uniforms;
  51780. }
  51781. const uniforms = materialProperties.uniforms;
  51782. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  51783. uniforms.clippingPlanes = clipping.uniform;
  51784. }
  51785. updateCommonMaterialProperties( material, parameters );
  51786. // store the light setup it was created for
  51787. materialProperties.needsLights = materialNeedsLights( material );
  51788. materialProperties.lightsStateVersion = lightsStateVersion;
  51789. if ( materialProperties.needsLights ) {
  51790. // wire up the material to this renderer's lighting state
  51791. uniforms.ambientLightColor.value = lights.state.ambient;
  51792. uniforms.lightProbe.value = lights.state.probe;
  51793. uniforms.directionalLights.value = lights.state.directional;
  51794. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  51795. uniforms.spotLights.value = lights.state.spot;
  51796. uniforms.spotLightShadows.value = lights.state.spotShadow;
  51797. uniforms.rectAreaLights.value = lights.state.rectArea;
  51798. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  51799. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  51800. uniforms.pointLights.value = lights.state.point;
  51801. uniforms.pointLightShadows.value = lights.state.pointShadow;
  51802. uniforms.hemisphereLights.value = lights.state.hemi;
  51803. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  51804. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  51805. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  51806. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  51807. uniforms.spotLightMap.value = lights.state.spotLightMap;
  51808. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  51809. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  51810. // TODO (abelnation): add area lights shadow info to uniforms
  51811. }
  51812. materialProperties.currentProgram = program;
  51813. materialProperties.uniformsList = null;
  51814. return program;
  51815. }
  51816. function getUniformList( materialProperties ) {
  51817. if ( materialProperties.uniformsList === null ) {
  51818. const progUniforms = materialProperties.currentProgram.getUniforms();
  51819. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  51820. }
  51821. return materialProperties.uniformsList;
  51822. }
  51823. function updateCommonMaterialProperties( material, parameters ) {
  51824. const materialProperties = properties.get( material );
  51825. materialProperties.outputColorSpace = parameters.outputColorSpace;
  51826. materialProperties.batching = parameters.batching;
  51827. materialProperties.batchingColor = parameters.batchingColor;
  51828. materialProperties.instancing = parameters.instancing;
  51829. materialProperties.instancingColor = parameters.instancingColor;
  51830. materialProperties.instancingMorph = parameters.instancingMorph;
  51831. materialProperties.skinning = parameters.skinning;
  51832. materialProperties.morphTargets = parameters.morphTargets;
  51833. materialProperties.morphNormals = parameters.morphNormals;
  51834. materialProperties.morphColors = parameters.morphColors;
  51835. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  51836. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  51837. materialProperties.numIntersection = parameters.numClipIntersection;
  51838. materialProperties.vertexAlphas = parameters.vertexAlphas;
  51839. materialProperties.vertexTangents = parameters.vertexTangents;
  51840. materialProperties.toneMapping = parameters.toneMapping;
  51841. }
  51842. function setProgram( camera, scene, geometry, material, object ) {
  51843. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  51844. textures.resetTextureUnits();
  51845. const fog = scene.fog;
  51846. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  51847. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  51848. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  51849. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  51850. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  51851. const morphTargets = !! geometry.morphAttributes.position;
  51852. const morphNormals = !! geometry.morphAttributes.normal;
  51853. const morphColors = !! geometry.morphAttributes.color;
  51854. let toneMapping = NoToneMapping;
  51855. if ( material.toneMapped ) {
  51856. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  51857. toneMapping = _this.toneMapping;
  51858. }
  51859. }
  51860. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  51861. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  51862. const materialProperties = properties.get( material );
  51863. const lights = currentRenderState.state.lights;
  51864. if ( _clippingEnabled === true ) {
  51865. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  51866. const useCache =
  51867. camera === _currentCamera &&
  51868. material.id === _currentMaterialId;
  51869. // we might want to call this function with some ClippingGroup
  51870. // object instead of the material, once it becomes feasible
  51871. // (#8465, #8379)
  51872. clipping.setState( material, camera, useCache );
  51873. }
  51874. }
  51875. //
  51876. let needsProgramChange = false;
  51877. if ( material.version === materialProperties.__version ) {
  51878. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  51879. needsProgramChange = true;
  51880. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  51881. needsProgramChange = true;
  51882. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  51883. needsProgramChange = true;
  51884. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  51885. needsProgramChange = true;
  51886. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  51887. needsProgramChange = true;
  51888. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  51889. needsProgramChange = true;
  51890. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  51891. needsProgramChange = true;
  51892. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  51893. needsProgramChange = true;
  51894. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  51895. needsProgramChange = true;
  51896. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  51897. needsProgramChange = true;
  51898. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  51899. needsProgramChange = true;
  51900. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  51901. needsProgramChange = true;
  51902. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  51903. needsProgramChange = true;
  51904. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  51905. needsProgramChange = true;
  51906. } else if ( materialProperties.envMap !== envMap ) {
  51907. needsProgramChange = true;
  51908. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  51909. needsProgramChange = true;
  51910. } else if ( materialProperties.numClippingPlanes !== undefined &&
  51911. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  51912. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  51913. needsProgramChange = true;
  51914. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  51915. needsProgramChange = true;
  51916. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  51917. needsProgramChange = true;
  51918. } else if ( materialProperties.morphTargets !== morphTargets ) {
  51919. needsProgramChange = true;
  51920. } else if ( materialProperties.morphNormals !== morphNormals ) {
  51921. needsProgramChange = true;
  51922. } else if ( materialProperties.morphColors !== morphColors ) {
  51923. needsProgramChange = true;
  51924. } else if ( materialProperties.toneMapping !== toneMapping ) {
  51925. needsProgramChange = true;
  51926. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  51927. needsProgramChange = true;
  51928. }
  51929. } else {
  51930. needsProgramChange = true;
  51931. materialProperties.__version = material.version;
  51932. }
  51933. //
  51934. let program = materialProperties.currentProgram;
  51935. if ( needsProgramChange === true ) {
  51936. program = getProgram( material, scene, object );
  51937. }
  51938. let refreshProgram = false;
  51939. let refreshMaterial = false;
  51940. let refreshLights = false;
  51941. const p_uniforms = program.getUniforms(),
  51942. m_uniforms = materialProperties.uniforms;
  51943. if ( state.useProgram( program.program ) ) {
  51944. refreshProgram = true;
  51945. refreshMaterial = true;
  51946. refreshLights = true;
  51947. }
  51948. if ( material.id !== _currentMaterialId ) {
  51949. _currentMaterialId = material.id;
  51950. refreshMaterial = true;
  51951. }
  51952. if ( refreshProgram || _currentCamera !== camera ) {
  51953. // common camera uniforms
  51954. const reverseDepthBuffer = state.buffers.depth.getReversed();
  51955. if ( reverseDepthBuffer ) {
  51956. _currentProjectionMatrix.copy( camera.projectionMatrix );
  51957. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  51958. toReversedProjectionMatrix( _currentProjectionMatrix );
  51959. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  51960. } else {
  51961. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  51962. }
  51963. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  51964. const uCamPos = p_uniforms.map.cameraPosition;
  51965. if ( uCamPos !== undefined ) {
  51966. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  51967. }
  51968. if ( capabilities.logarithmicDepthBuffer ) {
  51969. p_uniforms.setValue( _gl, 'logDepthBufFC',
  51970. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  51971. }
  51972. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  51973. if ( material.isMeshPhongMaterial ||
  51974. material.isMeshToonMaterial ||
  51975. material.isMeshLambertMaterial ||
  51976. material.isMeshBasicMaterial ||
  51977. material.isMeshStandardMaterial ||
  51978. material.isShaderMaterial ) {
  51979. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  51980. }
  51981. if ( _currentCamera !== camera ) {
  51982. _currentCamera = camera;
  51983. // lighting uniforms depend on the camera so enforce an update
  51984. // now, in case this material supports lights - or later, when
  51985. // the next material that does gets activated:
  51986. refreshMaterial = true; // set to true on material change
  51987. refreshLights = true; // remains set until update done
  51988. }
  51989. }
  51990. // skinning and morph target uniforms must be set even if material didn't change
  51991. // auto-setting of texture unit for bone and morph texture must go before other textures
  51992. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  51993. if ( object.isSkinnedMesh ) {
  51994. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  51995. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  51996. const skeleton = object.skeleton;
  51997. if ( skeleton ) {
  51998. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  51999. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  52000. }
  52001. }
  52002. if ( object.isBatchedMesh ) {
  52003. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  52004. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  52005. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  52006. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  52007. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  52008. if ( object._colorsTexture !== null ) {
  52009. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  52010. }
  52011. }
  52012. const morphAttributes = geometry.morphAttributes;
  52013. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  52014. morphtargets.update( object, geometry, program );
  52015. }
  52016. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  52017. materialProperties.receiveShadow = object.receiveShadow;
  52018. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  52019. }
  52020. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  52021. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  52022. m_uniforms.envMap.value = envMap;
  52023. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  52024. }
  52025. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  52026. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  52027. }
  52028. if ( refreshMaterial ) {
  52029. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  52030. if ( materialProperties.needsLights ) {
  52031. // the current material requires lighting info
  52032. // note: all lighting uniforms are always set correctly
  52033. // they simply reference the renderer's state for their
  52034. // values
  52035. //
  52036. // use the current material's .needsUpdate flags to set
  52037. // the GL state when required
  52038. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  52039. }
  52040. // refresh uniforms common to several materials
  52041. if ( fog && material.fog === true ) {
  52042. materials.refreshFogUniforms( m_uniforms, fog );
  52043. }
  52044. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  52045. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  52046. }
  52047. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  52048. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  52049. material.uniformsNeedUpdate = false;
  52050. }
  52051. if ( material.isSpriteMaterial ) {
  52052. p_uniforms.setValue( _gl, 'center', object.center );
  52053. }
  52054. // common matrices
  52055. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  52056. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  52057. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  52058. // UBOs
  52059. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  52060. const groups = material.uniformsGroups;
  52061. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52062. const group = groups[ i ];
  52063. uniformsGroups.update( group, program );
  52064. uniformsGroups.bind( group, program );
  52065. }
  52066. }
  52067. return program;
  52068. }
  52069. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  52070. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  52071. uniforms.ambientLightColor.needsUpdate = value;
  52072. uniforms.lightProbe.needsUpdate = value;
  52073. uniforms.directionalLights.needsUpdate = value;
  52074. uniforms.directionalLightShadows.needsUpdate = value;
  52075. uniforms.pointLights.needsUpdate = value;
  52076. uniforms.pointLightShadows.needsUpdate = value;
  52077. uniforms.spotLights.needsUpdate = value;
  52078. uniforms.spotLightShadows.needsUpdate = value;
  52079. uniforms.rectAreaLights.needsUpdate = value;
  52080. uniforms.hemisphereLights.needsUpdate = value;
  52081. }
  52082. function materialNeedsLights( material ) {
  52083. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  52084. material.isMeshStandardMaterial || material.isShadowMaterial ||
  52085. ( material.isShaderMaterial && material.lights === true );
  52086. }
  52087. /**
  52088. * Returns the active cube face.
  52089. *
  52090. * @return {number} The active cube face.
  52091. */
  52092. this.getActiveCubeFace = function () {
  52093. return _currentActiveCubeFace;
  52094. };
  52095. /**
  52096. * Returns the active mipmap level.
  52097. *
  52098. * @return {number} The active mipmap level.
  52099. */
  52100. this.getActiveMipmapLevel = function () {
  52101. return _currentActiveMipmapLevel;
  52102. };
  52103. /**
  52104. * Returns the active render target.
  52105. *
  52106. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  52107. * is currently set.
  52108. */
  52109. this.getRenderTarget = function () {
  52110. return _currentRenderTarget;
  52111. };
  52112. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  52113. const renderTargetProperties = properties.get( renderTarget );
  52114. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  52115. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  52116. // The multisample_render_to_texture extension doesn't work properly if there
  52117. // are midframe flushes and an external depth buffer. Disable use of the extension.
  52118. renderTargetProperties.__useRenderToTexture = false;
  52119. }
  52120. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  52121. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  52122. renderTargetProperties.__hasExternalTextures = true;
  52123. };
  52124. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  52125. const renderTargetProperties = properties.get( renderTarget );
  52126. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  52127. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  52128. };
  52129. const _scratchFrameBuffer = _gl.createFramebuffer();
  52130. /**
  52131. * Sets the active rendertarget.
  52132. *
  52133. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  52134. * the canvas is set as the active render target instead.
  52135. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  52136. * Indicates the z layer to render in to when using 3D or array render targets.
  52137. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  52138. */
  52139. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  52140. _currentRenderTarget = renderTarget;
  52141. _currentActiveCubeFace = activeCubeFace;
  52142. _currentActiveMipmapLevel = activeMipmapLevel;
  52143. let useDefaultFramebuffer = true;
  52144. let framebuffer = null;
  52145. let isCube = false;
  52146. let isRenderTarget3D = false;
  52147. if ( renderTarget ) {
  52148. const renderTargetProperties = properties.get( renderTarget );
  52149. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  52150. // We need to make sure to rebind the framebuffer.
  52151. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  52152. useDefaultFramebuffer = false;
  52153. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  52154. textures.setupRenderTarget( renderTarget );
  52155. } else if ( renderTargetProperties.__hasExternalTextures ) {
  52156. // Color and depth texture must be rebound in order for the swapchain to update.
  52157. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  52158. } else if ( renderTarget.depthBuffer ) {
  52159. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  52160. const depthTexture = renderTarget.depthTexture;
  52161. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  52162. // check if the depth texture is compatible
  52163. if (
  52164. depthTexture !== null &&
  52165. properties.has( depthTexture ) &&
  52166. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  52167. ) {
  52168. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  52169. }
  52170. // Swap the depth buffer to the currently attached one
  52171. textures.setupDepthRenderbuffer( renderTarget );
  52172. }
  52173. }
  52174. const texture = renderTarget.texture;
  52175. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  52176. isRenderTarget3D = true;
  52177. }
  52178. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  52179. if ( renderTarget.isWebGLCubeRenderTarget ) {
  52180. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  52181. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  52182. } else {
  52183. framebuffer = __webglFramebuffer[ activeCubeFace ];
  52184. }
  52185. isCube = true;
  52186. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  52187. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  52188. } else {
  52189. if ( Array.isArray( __webglFramebuffer ) ) {
  52190. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  52191. } else {
  52192. framebuffer = __webglFramebuffer;
  52193. }
  52194. }
  52195. _currentViewport.copy( renderTarget.viewport );
  52196. _currentScissor.copy( renderTarget.scissor );
  52197. _currentScissorTest = renderTarget.scissorTest;
  52198. } else {
  52199. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  52200. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  52201. _currentScissorTest = _scissorTest;
  52202. }
  52203. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  52204. // being bound that are different sizes.
  52205. if ( activeMipmapLevel !== 0 ) {
  52206. framebuffer = _scratchFrameBuffer;
  52207. }
  52208. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52209. if ( framebufferBound && useDefaultFramebuffer ) {
  52210. state.drawBuffers( renderTarget, framebuffer );
  52211. }
  52212. state.viewport( _currentViewport );
  52213. state.scissor( _currentScissor );
  52214. state.setScissorTest( _currentScissorTest );
  52215. if ( isCube ) {
  52216. const textureProperties = properties.get( renderTarget.texture );
  52217. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  52218. } else if ( isRenderTarget3D ) {
  52219. const textureProperties = properties.get( renderTarget.texture );
  52220. const layer = activeCubeFace;
  52221. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer );
  52222. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  52223. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  52224. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  52225. const textureProperties = properties.get( renderTarget.texture );
  52226. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  52227. }
  52228. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  52229. };
  52230. /**
  52231. * Reads the pixel data from the given render target into the given buffer.
  52232. *
  52233. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  52234. * @param {number} x - The `x` coordinate of the copy region's origin.
  52235. * @param {number} y - The `y` coordinate of the copy region's origin.
  52236. * @param {number} width - The width of the copy region.
  52237. * @param {number} height - The height of the copy region.
  52238. * @param {TypedArray} buffer - The result buffer.
  52239. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  52240. */
  52241. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  52242. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  52243. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  52244. return;
  52245. }
  52246. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  52247. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  52248. framebuffer = framebuffer[ activeCubeFaceIndex ];
  52249. }
  52250. if ( framebuffer ) {
  52251. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52252. try {
  52253. const texture = renderTarget.texture;
  52254. const textureFormat = texture.format;
  52255. const textureType = texture.type;
  52256. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  52257. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  52258. return;
  52259. }
  52260. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  52261. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  52262. return;
  52263. }
  52264. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  52265. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  52266. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  52267. }
  52268. } finally {
  52269. // restore framebuffer of current render target if necessary
  52270. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  52271. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52272. }
  52273. }
  52274. };
  52275. /**
  52276. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  52277. *
  52278. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  52279. *
  52280. * @async
  52281. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  52282. * @param {number} x - The `x` coordinate of the copy region's origin.
  52283. * @param {number} y - The `y` coordinate of the copy region's origin.
  52284. * @param {number} width - The width of the copy region.
  52285. * @param {number} height - The height of the copy region.
  52286. * @param {TypedArray} buffer - The result buffer.
  52287. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  52288. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  52289. */
  52290. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  52291. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  52292. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  52293. }
  52294. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  52295. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  52296. framebuffer = framebuffer[ activeCubeFaceIndex ];
  52297. }
  52298. if ( framebuffer ) {
  52299. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  52300. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  52301. // set the active frame buffer to the one we want to read
  52302. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  52303. const texture = renderTarget.texture;
  52304. const textureFormat = texture.format;
  52305. const textureType = texture.type;
  52306. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  52307. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  52308. }
  52309. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  52310. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  52311. }
  52312. const glBuffer = _gl.createBuffer();
  52313. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  52314. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  52315. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  52316. // reset the frame buffer to the currently set buffer before waiting
  52317. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  52318. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  52319. // check if the commands have finished every 8 ms
  52320. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  52321. _gl.flush();
  52322. await probeAsync( _gl, sync, 4 );
  52323. // read the data and delete the buffer
  52324. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  52325. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  52326. _gl.deleteBuffer( glBuffer );
  52327. _gl.deleteSync( sync );
  52328. return buffer;
  52329. } else {
  52330. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  52331. }
  52332. }
  52333. };
  52334. /**
  52335. * Copies pixels from the current bound framebuffer into the given texture.
  52336. *
  52337. * @param {FramebufferTexture} texture - The texture.
  52338. * @param {Vector2} position - The start position of the copy operation.
  52339. * @param {number} [level=0] - The mip level. The default represents the base mip.
  52340. */
  52341. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  52342. const levelScale = Math.pow( 2, - level );
  52343. const width = Math.floor( texture.image.width * levelScale );
  52344. const height = Math.floor( texture.image.height * levelScale );
  52345. const x = position !== null ? position.x : 0;
  52346. const y = position !== null ? position.y : 0;
  52347. textures.setTexture2D( texture, 0 );
  52348. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  52349. state.unbindTexture();
  52350. };
  52351. const _srcFramebuffer = _gl.createFramebuffer();
  52352. const _dstFramebuffer = _gl.createFramebuffer();
  52353. /**
  52354. * Copies data of the given source texture into a destination texture.
  52355. *
  52356. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  52357. * {@link WebGLRenderer#initRenderTarget}.
  52358. *
  52359. * @param {Texture} srcTexture - The source texture.
  52360. * @param {Texture} dstTexture - The destination texture.
  52361. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  52362. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  52363. * @param {number} srcLevel - The source mipmap level to copy.
  52364. * @param {number} dstLevel - The destination mipmap level.
  52365. */
  52366. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  52367. // support the previous signature with just a single dst mipmap level
  52368. if ( dstLevel === null ) {
  52369. if ( srcLevel !== 0 ) {
  52370. // @deprecated, r171
  52371. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  52372. dstLevel = srcLevel;
  52373. srcLevel = 0;
  52374. } else {
  52375. dstLevel = 0;
  52376. }
  52377. }
  52378. // gather the necessary dimensions to copy
  52379. let width, height, depth, minX, minY, minZ;
  52380. let dstX, dstY, dstZ;
  52381. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  52382. if ( srcRegion !== null ) {
  52383. width = srcRegion.max.x - srcRegion.min.x;
  52384. height = srcRegion.max.y - srcRegion.min.y;
  52385. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  52386. minX = srcRegion.min.x;
  52387. minY = srcRegion.min.y;
  52388. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  52389. } else {
  52390. const levelScale = Math.pow( 2, - srcLevel );
  52391. width = Math.floor( image.width * levelScale );
  52392. height = Math.floor( image.height * levelScale );
  52393. if ( srcTexture.isDataArrayTexture ) {
  52394. depth = image.depth;
  52395. } else if ( srcTexture.isData3DTexture ) {
  52396. depth = Math.floor( image.depth * levelScale );
  52397. } else {
  52398. depth = 1;
  52399. }
  52400. minX = 0;
  52401. minY = 0;
  52402. minZ = 0;
  52403. }
  52404. if ( dstPosition !== null ) {
  52405. dstX = dstPosition.x;
  52406. dstY = dstPosition.y;
  52407. dstZ = dstPosition.z;
  52408. } else {
  52409. dstX = 0;
  52410. dstY = 0;
  52411. dstZ = 0;
  52412. }
  52413. // Set up the destination target
  52414. const glFormat = utils.convert( dstTexture.format );
  52415. const glType = utils.convert( dstTexture.type );
  52416. let glTarget;
  52417. if ( dstTexture.isData3DTexture ) {
  52418. textures.setTexture3D( dstTexture, 0 );
  52419. glTarget = _gl.TEXTURE_3D;
  52420. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  52421. textures.setTexture2DArray( dstTexture, 0 );
  52422. glTarget = _gl.TEXTURE_2D_ARRAY;
  52423. } else {
  52424. textures.setTexture2D( dstTexture, 0 );
  52425. glTarget = _gl.TEXTURE_2D;
  52426. }
  52427. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  52428. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  52429. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  52430. // used for copying data from cpu
  52431. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  52432. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  52433. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  52434. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  52435. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  52436. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  52437. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  52438. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  52439. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  52440. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  52441. // set up the src texture
  52442. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  52443. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  52444. if ( srcTexture.isDepthTexture ) {
  52445. const srcTextureProperties = properties.get( srcTexture );
  52446. const dstTextureProperties = properties.get( dstTexture );
  52447. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  52448. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  52449. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  52450. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  52451. for ( let i = 0; i < depth; i ++ ) {
  52452. // if the source or destination are a 3d target then a layer needs to be bound
  52453. if ( isSrc3D ) {
  52454. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  52455. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  52456. }
  52457. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  52458. }
  52459. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  52460. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  52461. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  52462. // get the appropriate frame buffers
  52463. const srcTextureProperties = properties.get( srcTexture );
  52464. const dstTextureProperties = properties.get( dstTexture );
  52465. // bind the frame buffer targets
  52466. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  52467. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  52468. for ( let i = 0; i < depth; i ++ ) {
  52469. // assign the correct layers and mip maps to the frame buffers
  52470. if ( isSrc3D ) {
  52471. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  52472. } else {
  52473. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  52474. }
  52475. if ( isDst3D ) {
  52476. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  52477. } else {
  52478. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  52479. }
  52480. // copy the data using the fastest function that can achieve the copy
  52481. if ( srcLevel !== 0 ) {
  52482. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  52483. } else if ( isDst3D ) {
  52484. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  52485. } else {
  52486. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  52487. }
  52488. }
  52489. // unbind read, draw buffers
  52490. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  52491. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  52492. } else {
  52493. if ( isDst3D ) {
  52494. // copy data into the 3d texture
  52495. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  52496. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  52497. } else if ( dstTexture.isCompressedArrayTexture ) {
  52498. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  52499. } else {
  52500. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  52501. }
  52502. } else {
  52503. // copy data into the 2d texture
  52504. if ( srcTexture.isDataTexture ) {
  52505. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  52506. } else if ( srcTexture.isCompressedTexture ) {
  52507. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  52508. } else {
  52509. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  52510. }
  52511. }
  52512. }
  52513. // reset values
  52514. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  52515. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  52516. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  52517. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  52518. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  52519. // Generate mipmaps only when copying level 0
  52520. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  52521. _gl.generateMipmap( glTarget );
  52522. }
  52523. state.unbindTexture();
  52524. };
  52525. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  52526. // @deprecated, r170
  52527. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  52528. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  52529. };
  52530. /**
  52531. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  52532. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  52533. * rendered to.
  52534. *
  52535. * @param {WebGLRenderTarget} target - The render target.
  52536. */
  52537. this.initRenderTarget = function ( target ) {
  52538. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  52539. textures.setupRenderTarget( target );
  52540. }
  52541. };
  52542. /**
  52543. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  52544. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  52545. *
  52546. * @param {Texture} texture - The texture.
  52547. */
  52548. this.initTexture = function ( texture ) {
  52549. if ( texture.isCubeTexture ) {
  52550. textures.setTextureCube( texture, 0 );
  52551. } else if ( texture.isData3DTexture ) {
  52552. textures.setTexture3D( texture, 0 );
  52553. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  52554. textures.setTexture2DArray( texture, 0 );
  52555. } else {
  52556. textures.setTexture2D( texture, 0 );
  52557. }
  52558. state.unbindTexture();
  52559. };
  52560. /**
  52561. * Can be used to reset the internal WebGL state. This method is mostly
  52562. * relevant for applications which share a single WebGL context across
  52563. * multiple WebGL libraries.
  52564. */
  52565. this.resetState = function () {
  52566. _currentActiveCubeFace = 0;
  52567. _currentActiveMipmapLevel = 0;
  52568. _currentRenderTarget = null;
  52569. state.reset();
  52570. bindingStates.reset();
  52571. };
  52572. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  52573. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  52574. }
  52575. }
  52576. /**
  52577. * Defines the coordinate system of the renderer.
  52578. *
  52579. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  52580. *
  52581. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  52582. * @default WebGLCoordinateSystem
  52583. * @readonly
  52584. */
  52585. get coordinateSystem() {
  52586. return WebGLCoordinateSystem;
  52587. }
  52588. /**
  52589. * Defines the output color space of the renderer.
  52590. *
  52591. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  52592. * @default SRGBColorSpace
  52593. */
  52594. get outputColorSpace() {
  52595. return this._outputColorSpace;
  52596. }
  52597. set outputColorSpace( colorSpace ) {
  52598. this._outputColorSpace = colorSpace;
  52599. const gl = this.getContext();
  52600. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  52601. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  52602. }
  52603. }
  52604. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  52605. exports.AddEquation = AddEquation;
  52606. exports.AddOperation = AddOperation;
  52607. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  52608. exports.AdditiveBlending = AdditiveBlending;
  52609. exports.AgXToneMapping = AgXToneMapping;
  52610. exports.AlphaFormat = AlphaFormat;
  52611. exports.AlwaysCompare = AlwaysCompare;
  52612. exports.AlwaysDepth = AlwaysDepth;
  52613. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  52614. exports.AmbientLight = AmbientLight;
  52615. exports.AnimationAction = AnimationAction;
  52616. exports.AnimationClip = AnimationClip;
  52617. exports.AnimationLoader = AnimationLoader;
  52618. exports.AnimationMixer = AnimationMixer;
  52619. exports.AnimationObjectGroup = AnimationObjectGroup;
  52620. exports.AnimationUtils = AnimationUtils;
  52621. exports.ArcCurve = ArcCurve;
  52622. exports.ArrayCamera = ArrayCamera;
  52623. exports.ArrowHelper = ArrowHelper;
  52624. exports.AttachedBindMode = AttachedBindMode;
  52625. exports.Audio = Audio;
  52626. exports.AudioAnalyser = AudioAnalyser;
  52627. exports.AudioContext = AudioContext;
  52628. exports.AudioListener = AudioListener;
  52629. exports.AudioLoader = AudioLoader;
  52630. exports.AxesHelper = AxesHelper;
  52631. exports.BackSide = BackSide;
  52632. exports.BasicDepthPacking = BasicDepthPacking;
  52633. exports.BasicShadowMap = BasicShadowMap;
  52634. exports.BatchedMesh = BatchedMesh;
  52635. exports.Bone = Bone;
  52636. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  52637. exports.Box2 = Box2;
  52638. exports.Box3 = Box3;
  52639. exports.Box3Helper = Box3Helper;
  52640. exports.BoxGeometry = BoxGeometry;
  52641. exports.BoxHelper = BoxHelper;
  52642. exports.BufferAttribute = BufferAttribute;
  52643. exports.BufferGeometry = BufferGeometry;
  52644. exports.BufferGeometryLoader = BufferGeometryLoader;
  52645. exports.ByteType = ByteType;
  52646. exports.Cache = Cache;
  52647. exports.Camera = Camera;
  52648. exports.CameraHelper = CameraHelper;
  52649. exports.CanvasTexture = CanvasTexture;
  52650. exports.CapsuleGeometry = CapsuleGeometry;
  52651. exports.CatmullRomCurve3 = CatmullRomCurve3;
  52652. exports.CineonToneMapping = CineonToneMapping;
  52653. exports.CircleGeometry = CircleGeometry;
  52654. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  52655. exports.Clock = Clock;
  52656. exports.Color = Color;
  52657. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  52658. exports.ColorManagement = ColorManagement;
  52659. exports.CompressedArrayTexture = CompressedArrayTexture;
  52660. exports.CompressedCubeTexture = CompressedCubeTexture;
  52661. exports.CompressedTexture = CompressedTexture;
  52662. exports.CompressedTextureLoader = CompressedTextureLoader;
  52663. exports.ConeGeometry = ConeGeometry;
  52664. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  52665. exports.ConstantColorFactor = ConstantColorFactor;
  52666. exports.Controls = Controls;
  52667. exports.CubeCamera = CubeCamera;
  52668. exports.CubeReflectionMapping = CubeReflectionMapping;
  52669. exports.CubeRefractionMapping = CubeRefractionMapping;
  52670. exports.CubeTexture = CubeTexture;
  52671. exports.CubeTextureLoader = CubeTextureLoader;
  52672. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  52673. exports.CubicBezierCurve = CubicBezierCurve;
  52674. exports.CubicBezierCurve3 = CubicBezierCurve3;
  52675. exports.CubicInterpolant = CubicInterpolant;
  52676. exports.CullFaceBack = CullFaceBack;
  52677. exports.CullFaceFront = CullFaceFront;
  52678. exports.CullFaceFrontBack = CullFaceFrontBack;
  52679. exports.CullFaceNone = CullFaceNone;
  52680. exports.Curve = Curve;
  52681. exports.CurvePath = CurvePath;
  52682. exports.CustomBlending = CustomBlending;
  52683. exports.CustomToneMapping = CustomToneMapping;
  52684. exports.CylinderGeometry = CylinderGeometry;
  52685. exports.Cylindrical = Cylindrical;
  52686. exports.Data3DTexture = Data3DTexture;
  52687. exports.DataArrayTexture = DataArrayTexture;
  52688. exports.DataTexture = DataTexture;
  52689. exports.DataTextureLoader = DataTextureLoader;
  52690. exports.DataUtils = DataUtils;
  52691. exports.DecrementStencilOp = DecrementStencilOp;
  52692. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  52693. exports.DefaultLoadingManager = DefaultLoadingManager;
  52694. exports.DepthFormat = DepthFormat;
  52695. exports.DepthStencilFormat = DepthStencilFormat;
  52696. exports.DepthTexture = DepthTexture;
  52697. exports.DetachedBindMode = DetachedBindMode;
  52698. exports.DirectionalLight = DirectionalLight;
  52699. exports.DirectionalLightHelper = DirectionalLightHelper;
  52700. exports.DiscreteInterpolant = DiscreteInterpolant;
  52701. exports.DodecahedronGeometry = DodecahedronGeometry;
  52702. exports.DoubleSide = DoubleSide;
  52703. exports.DstAlphaFactor = DstAlphaFactor;
  52704. exports.DstColorFactor = DstColorFactor;
  52705. exports.DynamicCopyUsage = DynamicCopyUsage;
  52706. exports.DynamicDrawUsage = DynamicDrawUsage;
  52707. exports.DynamicReadUsage = DynamicReadUsage;
  52708. exports.EdgesGeometry = EdgesGeometry;
  52709. exports.EllipseCurve = EllipseCurve;
  52710. exports.EqualCompare = EqualCompare;
  52711. exports.EqualDepth = EqualDepth;
  52712. exports.EqualStencilFunc = EqualStencilFunc;
  52713. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  52714. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  52715. exports.Euler = Euler;
  52716. exports.EventDispatcher = EventDispatcher;
  52717. exports.ExtrudeGeometry = ExtrudeGeometry;
  52718. exports.FileLoader = FileLoader;
  52719. exports.Float16BufferAttribute = Float16BufferAttribute;
  52720. exports.Float32BufferAttribute = Float32BufferAttribute;
  52721. exports.FloatType = FloatType;
  52722. exports.Fog = Fog;
  52723. exports.FogExp2 = FogExp2;
  52724. exports.FramebufferTexture = FramebufferTexture;
  52725. exports.FrontSide = FrontSide;
  52726. exports.Frustum = Frustum;
  52727. exports.GLBufferAttribute = GLBufferAttribute;
  52728. exports.GLSL1 = GLSL1;
  52729. exports.GLSL3 = GLSL3;
  52730. exports.GreaterCompare = GreaterCompare;
  52731. exports.GreaterDepth = GreaterDepth;
  52732. exports.GreaterEqualCompare = GreaterEqualCompare;
  52733. exports.GreaterEqualDepth = GreaterEqualDepth;
  52734. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  52735. exports.GreaterStencilFunc = GreaterStencilFunc;
  52736. exports.GridHelper = GridHelper;
  52737. exports.Group = Group;
  52738. exports.HalfFloatType = HalfFloatType;
  52739. exports.HemisphereLight = HemisphereLight;
  52740. exports.HemisphereLightHelper = HemisphereLightHelper;
  52741. exports.IcosahedronGeometry = IcosahedronGeometry;
  52742. exports.ImageBitmapLoader = ImageBitmapLoader;
  52743. exports.ImageLoader = ImageLoader;
  52744. exports.ImageUtils = ImageUtils;
  52745. exports.IncrementStencilOp = IncrementStencilOp;
  52746. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  52747. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  52748. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  52749. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  52750. exports.InstancedMesh = InstancedMesh;
  52751. exports.Int16BufferAttribute = Int16BufferAttribute;
  52752. exports.Int32BufferAttribute = Int32BufferAttribute;
  52753. exports.Int8BufferAttribute = Int8BufferAttribute;
  52754. exports.IntType = IntType;
  52755. exports.InterleavedBuffer = InterleavedBuffer;
  52756. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  52757. exports.Interpolant = Interpolant;
  52758. exports.InterpolateDiscrete = InterpolateDiscrete;
  52759. exports.InterpolateLinear = InterpolateLinear;
  52760. exports.InterpolateSmooth = InterpolateSmooth;
  52761. exports.InvertStencilOp = InvertStencilOp;
  52762. exports.KeepStencilOp = KeepStencilOp;
  52763. exports.KeyframeTrack = KeyframeTrack;
  52764. exports.LOD = LOD;
  52765. exports.LatheGeometry = LatheGeometry;
  52766. exports.Layers = Layers;
  52767. exports.LessCompare = LessCompare;
  52768. exports.LessDepth = LessDepth;
  52769. exports.LessEqualCompare = LessEqualCompare;
  52770. exports.LessEqualDepth = LessEqualDepth;
  52771. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  52772. exports.LessStencilFunc = LessStencilFunc;
  52773. exports.Light = Light;
  52774. exports.LightProbe = LightProbe;
  52775. exports.Line = Line;
  52776. exports.Line3 = Line3;
  52777. exports.LineBasicMaterial = LineBasicMaterial;
  52778. exports.LineCurve = LineCurve;
  52779. exports.LineCurve3 = LineCurve3;
  52780. exports.LineDashedMaterial = LineDashedMaterial;
  52781. exports.LineLoop = LineLoop;
  52782. exports.LineSegments = LineSegments;
  52783. exports.LinearFilter = LinearFilter;
  52784. exports.LinearInterpolant = LinearInterpolant;
  52785. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  52786. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  52787. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  52788. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  52789. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  52790. exports.LinearToneMapping = LinearToneMapping;
  52791. exports.LinearTransfer = LinearTransfer;
  52792. exports.Loader = Loader;
  52793. exports.LoaderUtils = LoaderUtils;
  52794. exports.LoadingManager = LoadingManager;
  52795. exports.LoopOnce = LoopOnce;
  52796. exports.LoopPingPong = LoopPingPong;
  52797. exports.LoopRepeat = LoopRepeat;
  52798. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  52799. exports.LuminanceFormat = LuminanceFormat;
  52800. exports.MOUSE = MOUSE;
  52801. exports.Material = Material;
  52802. exports.MaterialLoader = MaterialLoader;
  52803. exports.MathUtils = MathUtils;
  52804. exports.Matrix2 = Matrix2;
  52805. exports.Matrix3 = Matrix3;
  52806. exports.Matrix4 = Matrix4;
  52807. exports.MaxEquation = MaxEquation;
  52808. exports.Mesh = Mesh;
  52809. exports.MeshBasicMaterial = MeshBasicMaterial;
  52810. exports.MeshDepthMaterial = MeshDepthMaterial;
  52811. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  52812. exports.MeshLambertMaterial = MeshLambertMaterial;
  52813. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  52814. exports.MeshNormalMaterial = MeshNormalMaterial;
  52815. exports.MeshPhongMaterial = MeshPhongMaterial;
  52816. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  52817. exports.MeshStandardMaterial = MeshStandardMaterial;
  52818. exports.MeshToonMaterial = MeshToonMaterial;
  52819. exports.MinEquation = MinEquation;
  52820. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  52821. exports.MixOperation = MixOperation;
  52822. exports.MultiplyBlending = MultiplyBlending;
  52823. exports.MultiplyOperation = MultiplyOperation;
  52824. exports.NearestFilter = NearestFilter;
  52825. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  52826. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  52827. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  52828. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  52829. exports.NeutralToneMapping = NeutralToneMapping;
  52830. exports.NeverCompare = NeverCompare;
  52831. exports.NeverDepth = NeverDepth;
  52832. exports.NeverStencilFunc = NeverStencilFunc;
  52833. exports.NoBlending = NoBlending;
  52834. exports.NoColorSpace = NoColorSpace;
  52835. exports.NoToneMapping = NoToneMapping;
  52836. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  52837. exports.NormalBlending = NormalBlending;
  52838. exports.NotEqualCompare = NotEqualCompare;
  52839. exports.NotEqualDepth = NotEqualDepth;
  52840. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  52841. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  52842. exports.Object3D = Object3D;
  52843. exports.ObjectLoader = ObjectLoader;
  52844. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  52845. exports.OctahedronGeometry = OctahedronGeometry;
  52846. exports.OneFactor = OneFactor;
  52847. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  52848. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  52849. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  52850. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  52851. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  52852. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  52853. exports.OrthographicCamera = OrthographicCamera;
  52854. exports.PCFShadowMap = PCFShadowMap;
  52855. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  52856. exports.PMREMGenerator = PMREMGenerator;
  52857. exports.Path = Path;
  52858. exports.PerspectiveCamera = PerspectiveCamera;
  52859. exports.Plane = Plane;
  52860. exports.PlaneGeometry = PlaneGeometry;
  52861. exports.PlaneHelper = PlaneHelper;
  52862. exports.PointLight = PointLight;
  52863. exports.PointLightHelper = PointLightHelper;
  52864. exports.Points = Points;
  52865. exports.PointsMaterial = PointsMaterial;
  52866. exports.PolarGridHelper = PolarGridHelper;
  52867. exports.PolyhedronGeometry = PolyhedronGeometry;
  52868. exports.PositionalAudio = PositionalAudio;
  52869. exports.PropertyBinding = PropertyBinding;
  52870. exports.PropertyMixer = PropertyMixer;
  52871. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  52872. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  52873. exports.Quaternion = Quaternion;
  52874. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  52875. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  52876. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  52877. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  52878. exports.REVISION = REVISION;
  52879. exports.RGBADepthPacking = RGBADepthPacking;
  52880. exports.RGBAFormat = RGBAFormat;
  52881. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  52882. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  52883. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  52884. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  52885. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  52886. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  52887. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  52888. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  52889. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  52890. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  52891. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  52892. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  52893. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  52894. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  52895. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  52896. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  52897. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  52898. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  52899. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  52900. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  52901. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  52902. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  52903. exports.RGBDepthPacking = RGBDepthPacking;
  52904. exports.RGBFormat = RGBFormat;
  52905. exports.RGBIntegerFormat = RGBIntegerFormat;
  52906. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  52907. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  52908. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  52909. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  52910. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  52911. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  52912. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  52913. exports.RGDepthPacking = RGDepthPacking;
  52914. exports.RGFormat = RGFormat;
  52915. exports.RGIntegerFormat = RGIntegerFormat;
  52916. exports.RawShaderMaterial = RawShaderMaterial;
  52917. exports.Ray = Ray;
  52918. exports.Raycaster = Raycaster;
  52919. exports.RectAreaLight = RectAreaLight;
  52920. exports.RedFormat = RedFormat;
  52921. exports.RedIntegerFormat = RedIntegerFormat;
  52922. exports.ReinhardToneMapping = ReinhardToneMapping;
  52923. exports.RenderTarget = RenderTarget;
  52924. exports.RenderTarget3D = RenderTarget3D;
  52925. exports.RenderTargetArray = RenderTargetArray;
  52926. exports.RepeatWrapping = RepeatWrapping;
  52927. exports.ReplaceStencilOp = ReplaceStencilOp;
  52928. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  52929. exports.RingGeometry = RingGeometry;
  52930. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  52931. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  52932. exports.SRGBColorSpace = SRGBColorSpace;
  52933. exports.SRGBTransfer = SRGBTransfer;
  52934. exports.Scene = Scene;
  52935. exports.ShaderChunk = ShaderChunk;
  52936. exports.ShaderLib = ShaderLib;
  52937. exports.ShaderMaterial = ShaderMaterial;
  52938. exports.ShadowMaterial = ShadowMaterial;
  52939. exports.Shape = Shape;
  52940. exports.ShapeGeometry = ShapeGeometry;
  52941. exports.ShapePath = ShapePath;
  52942. exports.ShapeUtils = ShapeUtils;
  52943. exports.ShortType = ShortType;
  52944. exports.Skeleton = Skeleton;
  52945. exports.SkeletonHelper = SkeletonHelper;
  52946. exports.SkinnedMesh = SkinnedMesh;
  52947. exports.Source = Source;
  52948. exports.Sphere = Sphere;
  52949. exports.SphereGeometry = SphereGeometry;
  52950. exports.Spherical = Spherical;
  52951. exports.SphericalHarmonics3 = SphericalHarmonics3;
  52952. exports.SplineCurve = SplineCurve;
  52953. exports.SpotLight = SpotLight;
  52954. exports.SpotLightHelper = SpotLightHelper;
  52955. exports.Sprite = Sprite;
  52956. exports.SpriteMaterial = SpriteMaterial;
  52957. exports.SrcAlphaFactor = SrcAlphaFactor;
  52958. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  52959. exports.SrcColorFactor = SrcColorFactor;
  52960. exports.StaticCopyUsage = StaticCopyUsage;
  52961. exports.StaticDrawUsage = StaticDrawUsage;
  52962. exports.StaticReadUsage = StaticReadUsage;
  52963. exports.StereoCamera = StereoCamera;
  52964. exports.StreamCopyUsage = StreamCopyUsage;
  52965. exports.StreamDrawUsage = StreamDrawUsage;
  52966. exports.StreamReadUsage = StreamReadUsage;
  52967. exports.StringKeyframeTrack = StringKeyframeTrack;
  52968. exports.SubtractEquation = SubtractEquation;
  52969. exports.SubtractiveBlending = SubtractiveBlending;
  52970. exports.TOUCH = TOUCH;
  52971. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  52972. exports.TetrahedronGeometry = TetrahedronGeometry;
  52973. exports.Texture = Texture;
  52974. exports.TextureLoader = TextureLoader;
  52975. exports.TextureUtils = TextureUtils;
  52976. exports.TimestampQuery = TimestampQuery;
  52977. exports.TorusGeometry = TorusGeometry;
  52978. exports.TorusKnotGeometry = TorusKnotGeometry;
  52979. exports.Triangle = Triangle;
  52980. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  52981. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  52982. exports.TrianglesDrawMode = TrianglesDrawMode;
  52983. exports.TubeGeometry = TubeGeometry;
  52984. exports.UVMapping = UVMapping;
  52985. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  52986. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  52987. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  52988. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  52989. exports.Uniform = Uniform;
  52990. exports.UniformsGroup = UniformsGroup;
  52991. exports.UniformsLib = UniformsLib;
  52992. exports.UniformsUtils = UniformsUtils;
  52993. exports.UnsignedByteType = UnsignedByteType;
  52994. exports.UnsignedInt248Type = UnsignedInt248Type;
  52995. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  52996. exports.UnsignedIntType = UnsignedIntType;
  52997. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  52998. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  52999. exports.UnsignedShortType = UnsignedShortType;
  53000. exports.VSMShadowMap = VSMShadowMap;
  53001. exports.Vector2 = Vector2;
  53002. exports.Vector3 = Vector3;
  53003. exports.Vector4 = Vector4;
  53004. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  53005. exports.VideoFrameTexture = VideoFrameTexture;
  53006. exports.VideoTexture = VideoTexture;
  53007. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  53008. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  53009. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  53010. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  53011. exports.WebGLRenderTarget = WebGLRenderTarget;
  53012. exports.WebGLRenderer = WebGLRenderer;
  53013. exports.WebGLUtils = WebGLUtils;
  53014. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  53015. exports.WebXRController = WebXRController;
  53016. exports.WireframeGeometry = WireframeGeometry;
  53017. exports.WrapAroundEnding = WrapAroundEnding;
  53018. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  53019. exports.ZeroFactor = ZeroFactor;
  53020. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  53021. exports.ZeroStencilOp = ZeroStencilOp;
  53022. exports.createCanvasElement = createCanvasElement;
粤ICP备19079148号